MaxStorage

Client

class odps.maxstorage.MaxStorageClient(odps: ODPS | None = None, *, account: BaseAccount | None = None, endpoint: str | None = None, project: str | None = None, schema: str | None = None, region: str | None = None, quota_name: str | None = None, tunnel_endpoint: str | None = None, user_agent: str | None = None, rest_client: RestClient | None = None, api_version: str = '2')[源代码]

Entry point for the MaxCompute Storage API.

Constructed from an odps.Odps entry (reuses RestClient + account) or standalone with explicit account/endpoint.

参数:
  • odps (ODPS, optional) -- The ODPS entry object. If given, the account/endpoint/project are derived from it.

  • account (Account, optional) -- Explicit account (when odps is not given).

  • endpoint (str, optional) -- Storage/tunnel endpoint override.

  • project (str, optional) -- Default project.

  • schema (str, optional) -- Default schema.

  • region (str, optional) -- Region name for V4 signing.

  • quota_name (str, optional) -- Quota name for resource management.

  • tunnel_endpoint (str, optional) -- Tunnel endpoint override (bypasses discovery).

  • user_agent (str, optional) -- Custom user agent string.

  • rest_client (RestClient, optional) -- Pre-configured RestClient (bypasses endpoint discovery).

  • api_version (str, default "2") -- API version: "2" → api/storage/v2, "3" → api/storage/v3.

property api_version: str

The negotiated API version ("2" or "3").

create_instance_read_session(instance, *, session_id: str | None = None, enable_limit: bool = False) → InstanceReadSession[源代码]

Create (or reload via session_id) an instance read session.

参数:
  • instance (Instance or str) -- odps.models.Instance or instance ID.

  • session_id (str, optional) -- Reload an existing session instead of creating a new one.

  • enable_limit (bool, default False) -- Allow LIMIT pushdown on the instance.

示例

>>> instance = odps.execute_sql("SELECT * FROM my_table LIMIT 100")
>>> session = client.create_instance_read_session(instance)
>>> reader = session.open_arrow_reader(offset=0, count=100)
>>> while True:
...     batch = reader.read()
...     if batch is None:
...         break
...     print(batch.to_pandas())
>>> reader.close()
create_table_read_session(table=None, *, descriptor: SessionDescriptor | None = None, session_id: str | None = None, columns: List[str] | None = None, partition_columns: List[str] | None = None, partitions: List[str] | None = None, bucket_ids: List[int] | None = None, split_options: SplitOptions | None = None, arrow_options: dict | None = None, filter_predicate: str | None = None, filter_predicate_fallback: bool = False, split_max_file_num: int = 0, incremental_read_options: IncrementalReadOptions | None = None, incremental_read_enabled: bool = False, session_ready_timeout: int | None = None) → TableReadSession[源代码]

Create (or reload via session_id) a table read session.

Alternatively, pass descriptor to restore a session locally from a SessionDescriptor exported elsewhere — no remote session is created or reloaded, and the descriptor is authoritative for schema, filters, incremental options, and split planning.

Polls until NORMAL (1s interval, session_ready_timeout default 3600s).

参数:
  • table (str or Table, optional) -- Table name or odps.models.Table. Required unless descriptor is given.

  • descriptor (SessionDescriptor, optional) -- Restore from a descriptor instead of creating a new session; supersedes table and every planning parameter below, and cannot be combined with table or session_id.

  • session_id (str, optional) -- Reload an existing session instead of creating a new one.

  • columns (list[str], optional) -- Data columns to project.

  • partition_columns (list[str], optional) -- Partition key columns to project (read partition values as data).

  • partitions (list[str], optional) -- Partition specs to filter, e.g. ["pt=20230101"].

  • bucket_ids (list[int], optional) -- Restrict reads to specific buckets of a bucketed table.

  • split_options (SplitOptions, optional) -- Split strategy (size, row-offset, or parallelism).

  • arrow_options (ArrowOptions, optional) -- Arrow read options (e.g. timestamp unit overrides).

  • filter_predicate (str, optional) -- Server-side filter predicate (SQL expression).

  • filter_predicate_fallback (bool, default False) -- Fall back to client-side filtering when the server rejects filter_predicate.

  • split_max_file_num (int, default 0) -- Maximum number of files per split (0 = server default).

  • incremental_read_options (IncrementalReadOptions, optional) -- Incremental-read configuration (mode + version range).

  • incremental_read_enabled (bool, default False) -- Enable incremental read for this session.

  • session_ready_timeout (int, optional) -- Override the default 3600s poll timeout.

示例

>>> read_session = client.create_table_read_session("my_table")
>>> for split in read_session.splits:
...     reader = read_session.open_arrow_reader(split)
...     while True:
...         batch = reader.read()
...         if batch is None:
...             break
...         print(batch.to_pandas())
...     reader.close()
>>> # Restore a planned session on a worker
>>> descriptor = SessionDescriptor.from_json(transferred_json)
>>> read_session = client.create_table_read_session(descriptor=descriptor)
create_table_write_session(table=None, *, descriptor: SessionDescriptor | None = None, session_id: str | None = None, partition_spec: str | None = None, overwrite: bool = False, write_mode: WriteMode = WriteMode.BATCH, quota_name: str | None = None, enable_schema_evolution: bool = False, required_data_format: DataFormat | None = None, batch_compatible_options: BatchCompatibleOptions | None = None) → TableWriteSession[源代码]

Create (or reload via session_id) a table write session.

Alternatively, pass descriptor to restore a batch-compatible session locally from a SessionDescriptor exported elsewhere — no remote session is created or reloaded. The restored session is descriptor-only: it can open block writers, but commit and abort stay with the coordinator session.

参数:
  • table (str or Table, optional) -- Table name or odps.models.Table. Required unless descriptor is given.

  • descriptor (SessionDescriptor, optional) -- Restore from a descriptor instead of creating a new session; supersedes table and every planning parameter below, and cannot be combined with table or session_id.

  • session_id (str, optional) -- Reload an existing session instead of creating a new one.

  • partition_spec (str, optional) -- Partition to write, e.g. "pt=20230101".

  • overwrite (bool, default False) -- Overwrite existing data in the partition.

  • write_mode (WriteMode, default WriteMode.BATCH) -- Batch, batch-compatible, or streaming write mode.

  • required_data_format (DataFormat, optional) -- Required data format for the session (e.g. DataFormat("Arrow", "V5")). When None the server applies its default. Forwarded as the RequiredDataFormat wire field consumed by the server.

  • batch_compatible_options (BatchCompatibleOptions, optional) -- Advanced settings for WriteMode.BATCH_COMPATIBLE. Ignored for other write modes.

示例

>>> import pyarrow as pa
>>> write_session = client.create_table_write_session("my_table")
>>> writer = write_session.open_arrow_writer(stream_id="0")
>>> batch = pa.RecordBatch.from_arrays(
...     [pa.array([1, 2], pa.int64()), pa.array(["a", "b"], pa.string())],
...     schema=pa.schema([("id", pa.int64()), ("name", pa.string())]),
... )
>>> writer.write_batch(batch)
>>> writer.close()
>>> write_session.commit()
>>>
>>> # Batch-compatible mode
>>> from odps.maxstorage import BatchCompatibleOptions, WriteMode
>>> session = client.create_table_write_session(
...     "my_table",
...     write_mode=WriteMode.BATCH_COMPATIBLE,
...     batch_compatible_options=BatchCompatibleOptions(
...         enhance_write_check=True,
...     ),
... )
>>> results = []
>>> for block in range(2):
...     writer = session.open_block_writer(block, 0)
...     root = writer.create_vector_schema_root()
...     writer.write_batch(root)
...     results.append(writer.commit())
>>> session.commit(block_results=results)
open_blob_manager(table: Table | None = None) → BlobManager[源代码]

Return a BlobManager for standalone blob read/write.

table is optional — needed for write operations (write_blob_stream, write_blob_batch) to resolve the table identifier. Read operations (read_blobs, read_blob) do not need it.

参数:

table (str or Table, optional) -- Table name or odps.models.Table. Required for write operations; ignored for reads.

示例

>>> blob_manager = client.open_blob_manager("my_table")
>>> records = blob_manager.read_blobs([ref1, ref2])
>>> for record in records:
...     print(len(record.data))
preview_table(table, partition_spec: str | None = None, columns: List[str] | None = None, limit: int | None = None) → ArrowReader[源代码]

Preview initial rows of a table as an ArrowReader.

Uncompressed (preview sends no ACCEPT-ENCODING header); for compressed reads use create_table_read_session + open_arrow_reader.

参数:
  • table (str or Table) -- Table name or odps.models.Table.

  • partition_spec (str, optional) -- Partition spec, e.g. "pt=20230101".

  • columns (list[str], optional) -- Columns to project; None returns all.

  • limit (int, optional) -- Maximum rows to preview.

示例

>>> reader = client.preview_table("my_table", limit=10)
>>> while True:
...     batch = reader.read()
...     if batch is None:
...         break
...     print(batch.to_pandas())
>>> reader.close()
property storage_rest: RestClient

The dedicated RestClient tagged MAXSTORAGE.

property stub: StorageStub

The StorageStub for RPC operations.

Read Sessions

class odps.maxstorage.TableReadSession(stub: StorageStub, table_id: TableIdentifier, request: CreateTableReadSessionRequest, session_id: str | None = None, session_ready_timeout: int | None = None, *, _response: CreateTableReadSessionResponse | None = None, _rows_per_split: int = 0)[源代码]

A table read session.

Created by MaxStorageClient.create_table_read_session. After construction the session is guaranteed to be in the NORMAL status and its splits are materialized.

参数:
  • stub (StorageStub) -- The RPC layer.

  • table_id (TableIdentifier) -- Target table.

  • request (CreateTableReadSessionRequest) -- Creation request (partitions, split options, data format, ...).

  • session_id (str, optional) -- If given, reload an existing session instead of creating a new one.

  • session_ready_timeout (int, optional) -- Override options.maxstorage.session_ready_timeout (default 3600s).

示例

>>> session = client.create_table_read_session("my_table")
>>> for split in session.splits:
...     reader = session.open_arrow_reader(split)
...     while True:
...         batch = reader.read()
...         if batch is None:
...             break
...         process(batch)
...     reader.close()
property arrow_schema: pa.Schema

Arrow schema over all columns (data + partition).

close() → None[源代码]

Close the session. Best-effort; the server expires sessions on its own.

property enable_large_string: bool

Whether the server uses Arrow large-string columns.

property expiration_time: int | None

Session expiration time (from ExpirationTime).

property extended_arrow_ipc_enabled: bool

Whether the session negotiated the extended Arrow IPC format.

classmethod from_descriptor(stub: StorageStub, descriptor: SessionDescriptor) → TableReadSession[源代码]

Restore a read session locally from a descriptor, without any RPC.

The descriptor is authoritative for schema, filters, incremental options, and split planning; no remote session is created or reloaded, and the supplied stub is only used for subsequent reader calls.

property id: str | None

The session id.

property latest_txn_id: str | None

Latest transaction id (from LatestTxnId, used by incremental reads).

property latest_version: int | None

Latest data version (from LatestVersion, used by incremental reads).

open_arrow_reader(split: IndexedInputSplit | RowRangeInputSplit, *, max_batch_rows: int = 4096, skip_row_num: int = 0, max_batch_raw_size: int = 0, data_format: DataFormat | None = None, data_columns: List[str] | None = None, data_columns_unordered: bool = False, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None, async_read: bool = False, async_queue_size: int = 2) → ArrowReader[源代码]

Open an ArrowReader for split.

Compression follows the tunnel pattern: pass compress_option (a odps.tunnel.CompressOption) or the shorthand compress_algo/compress_level. Default None = uncompressed. compress_option takes priority over the shorthand kwargs.

When compression is requested, an ACCEPT-ENCODING header is sent on the stream-create request so the server compresses the Arrow stream; the reader then decompresses the response via odps.tunnel.io.stream.get_decompress_stream().

示例

>>> read_session = client.create_table_read_session("my_table")
>>> for split in read_session.splits:
...     reader = read_session.open_arrow_reader(split, max_batch_rows=1024)
...     while True:
...         batch = reader.read()
...         if batch is None:
...             break
...         print(batch.to_pandas())
...     reader.close()
>>>
>>> # Compressed read via shorthand
>>> reader = read_session.open_arrow_reader(
...     read_session.splits[0], compress_algo="zstd",
... )
>>> reader.close()
property record_count: int

Total row count in this session (from RecordCount).

-1 when the server does not report a record count — an absent count is unknown, not zero.

property session_stats: SessionStats | None

Estimated size / row count (SessionStats or None).

property split_mode: SplitMode

The SplitMode of this session.

property splits: list

The materialized list of input splits.

property supported_data_formats: List[DataFormat]

List of DataFormat supported by this session.

property table_schema: StorageSchema

The ReadSchema from the response DataSchema.

to_descriptor() → SessionDescriptor[源代码]

Export an immutable, credential-free description of this session.

The returned descriptor snapshots the current session state; later mutations of this session do not affect it.

class odps.maxstorage.InstanceReadSession(stub: StorageStub, instance_id: InstanceIdentifier, request: CreateInstanceReadSessionRequest, session_id: str | None = None)[源代码]

An instance read session.

Created by MaxStorageClient.create_instance_read_session. After construction the session is ready for reads; there is no split material and no polling.

参数:
  • stub (StorageStub) -- The RPC layer.

  • instance_id (InstanceIdentifier) -- Target instance.

  • request (CreateInstanceReadSessionRequest) -- Creation request.

  • session_id (str, optional) -- If given, reload an existing session (DownloadID) instead of creating a new one.

property arrow_schema: pa.Schema

Arrow schema over all columns.

close() → None[源代码]

Close the session. No-op (added for symmetry).

property id: str | None

The download id (wire field DownloadID, not SessionId).

open_arrow_reader(offset: int = 0, count: int | None = None, *, columns: List[str] | None = None, task_name: str = 'AnonymousSQLTask', query_id: int = 0, enable_limit: bool = False, compress_option: CompressOption = None, compress_algo=None, compress_level=None, async_read: bool = False, async_queue_size: int = 2) → ArrowReader[源代码]

Open an ArrowReader for this instance read session.

task_name defaults to "AnonymousSQLTask" and warns when unset (i.e. left at the default) to surface the likely-missing task association.

Compression follows the same tunnel pattern as TableReadSession: compress_option (default None = uncompressed) or the shorthand compress_algo/compress_level. Uncompressed is the default; LZ4 and ZSTD are also supported.

示例

>>> instance = odps.execute_sql("SELECT * FROM my_table LIMIT 100")
>>> session = client.create_instance_read_session(instance)
>>> reader = session.open_arrow_reader(offset=0, count=100)
>>> while True:
...     batch = reader.read()
...     if batch is None:
...         break
...     print(batch.to_pandas())
>>> reader.close()
property quota_name: str | None

The quota name (from QuotaName), or None.

property record_count: int

Total row count (from RecordCount).

property table_schema: StorageSchema

The WriteSchema deserialized from TableSchema.

class odps.maxstorage.IndexedInputSplit(session_id: str, split_index: int)[源代码]

A split addressed by index — used when split_mode == SIZE.

session_id

The read-session id this split belongs to.

Type:

str

split_index

Zero-based index in [0, splits_count).

Type:

int

class odps.maxstorage.RowRangeInputSplit(session_id: str, offset: int, length: int)[源代码]

A split addressed by [offset, offset+length) — used when split_mode == ROW_OFFSET.

session_id

The read-session id this split belongs to.

Type:

str

offset

Starting row offset within the session.

Type:

int

length

Number of rows in this split.

Type:

int

Readers

class odps.maxstorage.ArrowReader(raw_response, schema: StorageSchema | None, compress_option: CompressOption = None, request_id: str = '', count: int = 0, async_read: bool = False, async_queue_size: int = 2, extended: bool = False)[源代码]

Arrow reader over a Storage-API read stream.

参数:
  • raw_response (requests.Response) -- Streaming HTTP response returned by the stub's create_*_read_stream.

  • schema (odps.maxstorage.models.schema.StorageSchema) -- The session's table schema (ReadSchema or WriteSchema). Used by get_as_record_reader to build odps.models.Record instances whose columns match the table schema.

  • compress_option (odps.tunnel.CompressOption, optional) -- When set, the response stream is decompressed via odps.tunnel.io.stream.get_decompress_stream().

  • request_id (str, optional) -- ODPS request id captured from the stream-create response headers.

  • count (int, optional) -- Total number of rows available to this reader (the split's row range length, or the instance read's requested count). Defaults to 0 (unknown). Exposed via the count property.

  • async_read (bool, optional) -- When True, a background thread pre-reads Arrow batches into a bounded queue, overlapping network I/O with batch processing. Default False.

  • async_queue_size (int, optional) -- Maximum number of batches buffered by the async reader (default 2). Larger values smooth latency spikes at the cost of memory.

  • extended (bool, optional) -- When True, the response stream uses the negotiated extended Arrow IPC format: tagged substreams with metrics frames separated from table rows. Metrics collected from the stream are exposed via metrics_metadata. Default False.

示例

>>> reader = read_session.open_arrow_reader(read_session.splits[0])
>>> while True:
...     batch = reader.read()
...     if batch is None:
...         break
...     print(batch.to_pandas())
>>> reader.close()
property arrow_schema: pa.Schema

The pyarrow.Schema of the underlying IPC stream.

property count: int

Total number of rows available to this reader (set at open time).

-1 when that number is unknown (the session did not report a record count and the split carries no row range).

get_as_record_reader() → ArrowRecordReader[源代码]

Return a record reader yielding odps.models.Record.

See ArrowRecordReader for type-conversion and BLOB-handling details.

get_request_id() → str[源代码]

ODPS request id of the stream-create request.

get_status() → str[源代码]

Return the reader status.

The Python port has no async-read lifecycle, so this is always "OK" once the stream is openable.

property metrics_metadata: dict | None

Metrics metadata collected from extended-IPC metrics substreams.

None for ordinary (non-extended) readers; a dict of merged metric key/value pairs for extended readers.

read() → pa.RecordBatch | None[源代码]

Read the next pyarrow.RecordBatch, or None at EOS.

read_next_batch() → pa.RecordBatch | None[源代码]

Alias for read(), matching the tunnel ArrowReader contract.

property schema: StorageSchema

The session's ODPS schema — matches the tunnel ArrowReader contract.

property table_schema: StorageSchema | None

The session's ODPS (Storage) schema.

class odps.maxstorage.ArrowRecordReader(arrow_reader)[源代码]

Record reader over a maxstorage ArrowReader.

Subclasses the tunnel ArrowRecordReader so that type conversion is identical to the tunnel record reader. The only divergence is BLOB columns: the tunnel never supports them, and odps.types.validate_value() rejects the Blob type. Here the Arrow binary value (the server-side blob reference) is stored directly as bytes, bypassing validation.

property count: int

Total rows available — delegates to the underlying ArrowReader.

Write Sessions

class odps.maxstorage.TableWriteSession(stub: StorageStub, table_id: TableIdentifier, *, session_id: str | None = None, partition_spec: str | None = None, overwrite: bool = False, write_mode: WriteMode = WriteMode.BATCH, quota_name: str | None = None, enable_schema_evolution: bool = False, required_data_format: DataFormat | None = None, batch_compatible_options: BatchCompatibleOptions | None = None, api_version: str = '2', _batch_compatible_response: BatchCompatibleSessionResponse | None = None)[源代码]

A write session for a MaxCompute table.

Created by MaxStorageClient.create_table_write_session().

参数:
  • stub (StorageStub) -- The RPC layer.

  • table_id (TableIdentifier) -- Target table.

  • session_id (str, optional) -- Reload an existing session instead of creating a new one.

  • partition_spec (str, optional) -- Partition to write, e.g. "pt=20230101".

  • write_mode (WriteMode, default WriteMode.BATCH) -- Batch or streaming write mode.

  • api_version (str, default "2") -- Storage API version ("2" or "3").

示例

>>> import pyarrow as pa
>>> session = client.create_table_write_session("my_table")
>>> writer = session.open_arrow_writer(stream_id="0")
>>> batch = pa.RecordBatch.from_arrays(
...     [pa.array([1], pa.int64()), pa.array(["x"], pa.string())],
...     schema=pa.schema([("id", pa.int64()), ("name", pa.string())]),
... )
>>> writer.write_batch(batch)
>>> writer.close()
>>> session.commit()
abort() → None[源代码]

Abort the session to discard all uploaded data.

close() → None[源代码]

Auto-aborts if not committed.

Once a batch-compatible commit has been attempted, its outcome may be unknown even if the call failed; closing then performs no remote abort, and the coordinator must reconcile the session state separately. Descriptor-restored workers only close their local handle: they never abort the global session.

Either way the handle is finalized: no writer or commit is accepted afterwards, and an exported descriptor records the session as ABORTED (abort confirmed) or UNKNOWN (outcome not observed).

commit(stream_ids: List[str] | None = None, stream_versions: List[int] | None = None, block_results: Collection[BlockWriteResult] | None = None, wait_flying_writers_timeout_seconds: int | None = None) → None[源代码]

Commit the session to finalize all uploaded data.

For BATCH_COMPATIBLE mode, pass block_results (a collection of BlockWriteResult from successful block writers). The stream_ids / stream_versions parameters are not used in batch-compatible mode.

wait_flying_writers_timeout_seconds (batch-compatible mode only) bounds how long the server waits for in-flight writers before finalizing the commit; valid range is 1..600 seconds. None keeps the server default.

property descriptor_only: bool

Whether this session was restored from a descriptor.

Descriptor-restored sessions support block data operations only; global commit and abort stay with the coordinator session.

classmethod from_descriptor(stub: StorageStub, descriptor: SessionDescriptor) → TableWriteSession[源代码]

Restore a batch-compatible write session locally, without any RPC.

The restored session is descriptor-only: it can open block writers (which reserve quota per attempt) but cannot commit or abort the global session — those operations stay with the coordinator that created it. Closing the restored session never aborts the global session.

get_min_uncommitted_staging_id() → int[源代码]

Streaming only. Raises NotImplementedError on API v2.

property max_block_number: int | None

Exclusive block-number limit for batch-compatible sessions.

Returns None for non-batch-compatible modes or when the service omitted it. Valid block numbers are [0, max_block_number).

open_arrow_writer(stream_id: str, stream_version: int = 1, *, buffer_size: int = 67108864, auto_upload_blobs: bool = False, blob_checksum_type=None, blob_mime_type: str | None = None, blob_custom_file_name: str | None = None, blob_metadata_callback: callable | None = None, auto_flush_enabled: bool = True, auto_close_files: bool = False, resume: bool = False, max_pending_buffers: int = 1, exactly_once_mode: bool = False, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None) → TableArrowWriter[源代码]

Open a TableArrowWriter for this session.

If resume=True, calls getWriteStream; otherwise calls createTableWriteStream. Returns TableArrowBlobUploadWriter if auto_upload_blobs, else TableArrowWriter.

Both writer classes support get_as_record_writer() and the full blob-upload helper API (build_blob_write_item, write_blob_stream, write_blob_batch). The difference is whether BLOB cells in write_batch / get_as_record_writer are auto-uploaded:

  • auto_upload_blobs=False (default): BLOB columns must already contain reference bytes — upload them yourself via write_blob_batch first and place the returned references.

  • auto_upload_blobs=True: returns a TableArrowBlobUploadWriter that batch-uploads raw bytes/file-like BLOB cells and replaces them with references.

参数:
  • stream_id -- write stream identifier (string).

  • stream_version -- write stream version (default 1).

关键字参数:
  • buffer_size -- Arrow IPC buffer size in bytes (default 64 MiB).

  • auto_upload_blobs -- when True, return a TableArrowBlobUploadWriter that auto-uploads BLOB cells inline and replaces them with references.

  • blob_checksum_type -- checksum algorithm for blob uploads.

  • blob_mime_type -- session-level default MIME type, used as fallback when blob_metadata_callback is unset or returns None.

  • blob_custom_file_name -- session-level default custom file name (API v3 only), same fallback semantics as blob_mime_type.

  • blob_metadata_callback -- optional callable callback(row_index, column_name, blob_data) -> (mime_type, custom_file_name) | None invoked once per inline BLOB cell.

  • auto_flush_enabled -- whether to auto-flush when the buffer is full (default True).

  • auto_close_files -- when True, the writer closes file-like objects passed to it (e.g. via write_batch BLOB cells or write_blob_batch items) after they are consumed; objects without a close attribute or already closed are skipped.

  • resume -- when True, resume an existing write stream instead of creating a new one.

  • max_pending_buffers -- maximum number of pending async flush buffers for back-pressure (default 1).

  • exactly_once_mode -- enable exactly-once write semantics.

  • compress_option -- CompressOption for Arrow IPC compression.

  • compress_algo -- shorthand for compress_option — "zstd" / "lz4".

  • compress_level -- compression level.

示例

>>> import pyarrow as pa
>>> session = client.create_table_write_session("my_table")
>>> # Plain Arrow write
>>> writer = session.open_arrow_writer(stream_id="0")
>>> batch = pa.RecordBatch.from_arrays(
...     [pa.array([1, 2], pa.int64()), pa.array(["a", "b"], pa.string())],
...     schema=pa.schema([("id", pa.int64()), ("name", pa.string())]),
... )
>>> writer.write_batch(batch)
>>> writer.close()
>>> session.commit()
>>>
>>> # Auto-upload writer: inline BLOB cells are auto-uploaded
>>> writer = session.open_arrow_writer(
...     stream_id="0", auto_upload_blobs=True,
... )
>>> batch = pa.RecordBatch.from_arrays(
...     [pa.array([0], pa.int64()), pa.array([b"payload"], pa.binary())],
...     schema=pa.schema([("id", pa.int64()), ("blob", pa.binary())]),
... )
>>> writer.write_batch(batch)
>>> writer.close()
>>> session.commit()
open_block_writer(block_number: int, attempt_number: int, *, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None) → TableBlockWriter[源代码]

Create a TableBlockWriter for BATCH_COMPATIBLE mode.

Each call reserves a one-time upload quota for the given block_number + attempt_number pair. Retry the same block with a new attempt_number; do not reuse a committed or aborted writer.

Compression follows the other write interfaces: pass compress_option (a odps.tunnel.CompressOption) or the shorthand compress_algo/compress_level. Default None = uncompressed. When set, the block body is serialized as an Arrow IPC stream with the built-in codec ("zstd" / "lz4"), matching open_arrow_writer() — no HTTP Content-Encoding.

参数:
  • block_number -- zero-based block number.

  • attempt_number -- zero-based attempt number for this block.

关键字参数:
  • compress_option -- CompressOption for Arrow IPC compression.

  • compress_algo -- shorthand for compress_option — "zstd" / "lz4".

  • compress_level -- compression level.

抛出:

Descriptor-restored sessions reject new writers once a commit has been attempted on the session or the last observed session status is no longer NORMAL.

to_descriptor() → SessionDescriptor[源代码]

Export an immutable, credential-free description of this session.

Only BATCH_COMPATIBLE sessions support descriptors; other write modes are rejected until their distinct recovery contracts exist.

A descriptor exported after a commit was attempted cannot reopen writers on the restoring side, even when the last observed session status is still NORMAL.

Session Descriptors

class odps.maxstorage.SessionDescriptor(root)[源代码]

Immutable, versioned description of a storage session.

Export with a session's to_descriptor(), serialize with to_json(), and parse on the worker with from_json(). Bind to a worker session through TableReadSession.from_descriptor / TableWriteSession.from_descriptor or the matching MaxStorageClient factory methods. Restoration never creates or reloads a remote session; a restored write session has only block-writing authority.

property arrow: Dict[str, str] | None

Write Arrow encoding units, or None for read descriptors.

classmethod create(kind, table, metadata, route_token=None, arrow=None, rows_per_split=None)[源代码]

Build a descriptor from wire-form (PascalCase) session metadata.

参数:
  • kind (SessionKind or str) -- The session purpose; a string value must equal the enum value ("batch-read" / "incremental-read" / "batch-write").

  • table (TableIdentifier or dict) -- Table identity (project / table / optional schema).

  • metadata (dict) -- Wire-form session metadata; unknown fields are dropped.

  • route_token (str, optional) -- Opaque routing token from the session response.

  • arrow (dict, optional) -- Write encoding units, e.g. {"timestampUnit": "NANO", "datetimeUnit": "MILLI"}.

  • rows_per_split (int, optional) -- Row-offset chunk size for ROW_OFFSET read sessions.

classmethod from_json(text)[源代码]

Parse a descriptor from JSON without network or config access.

property kind: SessionKind

The session purpose, as a SessionKind.

property metadata: Dict[str, Any]

Session metadata in wire (PascalCase) form.

property route_token: str | None

Opaque routing token, or None.

property rows_per_split: int

Row-offset chunk size (0 when the descriptor carries none).

property session_id: str

The session identifier from the metadata.

property session_status: str

The last observed session status from the metadata.

property table: Dict[str, Any]

project / table / optional schema.

Type:

Table identity

property table_identifier

The table identity as a TableIdentifier.

to_json()[源代码]

Serialize to the canonical JSON form.

Writers

class odps.maxstorage.TableArrowWriter(stub: StorageStub, table_id: TableIdentifier, session_id: str, stream_id: str, stream_version: int = 1, *, write_mode: WriteMode = WriteMode.BATCH, route_token: str | None = None, buffer_size: int = 67108864, auto_flush_enabled: bool = True, auto_close_files: bool = False, resume: bool = False, max_pending_buffers: int = 1, exactly_once_mode: bool = False, compress_option: CompressOption | None = None, api_version: str = '2', session: TableWriteSession | None = None)[源代码]

Arrow batch writer for a table write stream.

Caches serialized Arrow batches and flushes them as a single Arrow IPC stream body via stub.write_table().

参数:
  • stub (StorageStub) -- The RPC layer.

  • table_id (TableIdentifier) -- Target table.

  • session_id (str) -- Write session ID.

  • stream_id (str) -- Write stream ID (use different IDs for parallel writers).

  • stream_version (int, default 1) -- Write stream version.

  • write_mode (WriteMode, default WriteMode.BATCH) -- Batch or streaming write mode.

  • route_token (str, optional) -- Server routing token for session affinity.

  • compress_option (odps.tunnel.CompressOption, optional) -- Arrow IPC compression for write batches.

  • api_version (str, default "2") -- Storage API version ("2" or "3").

示例

>>> import pyarrow as pa
>>> writer = write_session.open_arrow_writer(stream_id="0")
>>> batch = pa.RecordBatch.from_arrays(
...     [pa.array([1, 2], pa.int64()), pa.array(["a", "b"], pa.string())],
...     schema=pa.schema([("id", pa.int64()), ("name", pa.string())]),
... )
>>> writer.write_batch(batch)
>>> writer.close()
>>> write_session.commit()
build_blob_write_item(data: bytes | IOBase, *, column_name: str | None = None, partition_spec: str | None = None, distribution_key: str | None = None, mime_type: str | None = None, custom_file_name: str | None = None, checksum_type=ChecksumType.NONE) → BlobWriteItem[源代码]

Build a BlobWriteItem from writer-resolved state.

column_name is resolved to the server-assigned column ID via WriteSchema.find_all_blob_column_ids() (same dot-path keys). When omitted, the sole top-level pure-BLOB column is auto-selected (raises if the schema has multiple BLOB columns or any nested BLOB column). partition_spec accepts the same types as PartitionSpec (str, dict, or PartitionSpec). api_version is stamped from the writer so v3-only fields (custom_file_name) are gated automatically.

示例

>>> writer = write_session.open_arrow_writer(stream_id="0")
>>> items = [
...     writer.build_blob_write_item(
...         b"payload", column_name="blob", mime_type="image/png",
...     )
... ]
close() → None[源代码]

Flush remaining data, then closeWriteStream.

Skips closeWriteStream when (a) streaming with session_id == "default" OR (b) stream_id == "default"; otherwise closes the stream.

The async-flush executor is always shut down (even if flush or closeWriteStream raises) so its worker thread is joined.

flush() → None[源代码]

Send all cached batches as one Arrow IPC stream body.

If an async flush is in flight, awaits and surfaces its exception first, then sync-flushes the remaining buffer.

flush_async() → Future[源代码]

Async flush using a ThreadPoolExecutor + Semaphore for backpressure.

Captures all buffer state (including _cached_record_batches needed for compressed writes), submits the flush to a background worker, and retains the Future in a pending deque so failures surface from the next write_batch / flush / close. The semaphore provides real backpressure: when max_pending_buffers flushes are in flight the next flush_async blocks until one completes.

Every submitted Future is tracked in _pending_futures (not a single scalar) so that flush(), close(), and set_row_offset() await all pending uploads, and a failure in one buffer is not erased by a success in another.

On async failure the captured rows are restored to the live cache (appended after any live data to preserve submission order) so the caller can retry. Returns the Future (a completed Future when there is nothing to flush) so callers can always .result() it.

get_as_record_writer(row_count_per_batch: int = 1024, blob_batch_file_num: int = 1000)[源代码]

Return a record-oriented writer wrapping this writer.

Returns DeltaTableRecordWriter if an __operation column is found in either system_columns or columns; otherwise AppendTableRecordWriter.

On a plain TableArrowWriter, BLOB cells must already contain reference bytes. On a TableArrowBlobUploadWriter, raw bytes / file-like values are auto-uploaded and replaced with references.

参数:
  • row_count_per_batch -- rows per Arrow batch flush.

  • blob_batch_file_num -- max blobs per batch upload.

get_row_offset() → int[源代码]

In EO mode, fetch the latest server-side RowOffset; else return local.

set_row_offset(new_row_offset: int) → None[源代码]

Flush cached data with current offset, then update (EO mode only).

Awaits any in-flight async flush first so the detached flush cannot race with the offset change and write rows at the wrong position.

write_batch(batch) → None[源代码]

Serialize a batch to Arrow IPC bytes and cache it.

batch may be a pa.Table or pa.RecordBatch. Auto-flushes at buffer_size.

BLOB column values are sent inline as-is. To auto-upload raw bytes and replace them with references, use TableArrowBlobUploadWriter via auto_upload_blobs=True.

write_blob_batch(items, *, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None) → WriteBlobResponse[源代码]

Batch blob upload. Returns WriteBlobResponse.

Streams frames to the server via chunked transfer-encoding — the full batch body is never materialized.

示例

>>> writer = write_session.open_arrow_writer(stream_id="0")
>>> items = [
...     writer.build_blob_write_item(b"a", column_name="blob"),
...     writer.build_blob_write_item(b"b", column_name="blob"),
... ]
>>> resp = writer.write_blob_batch(items)
>>> print(len(resp.blob_references))
write_blob_stream(*, column_name: str | None = None, partition_spec: str | None = None, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None) → BlobStreamWriter[源代码]

Streaming single blob upload with MD5 verification.

Returns a BlobStreamWriter that streams data to the server via chunked transfer-encoding — the full blob is never materialized.

column_name is the dot-path name (a key of WriteSchema.find_all_blob_column_ids()) resolved to the server-assigned column ID internally. When omitted, the sole top-level pure-BLOB column is auto-selected (raises if the schema has multiple BLOB columns or any nested BLOB column).

partition_spec accepts the same types as PartitionSpec (str, dict, or PartitionSpec instance), e.g. "pt=20230101" or {"pt": "20230101"}.

示例

>>> writer = write_session.open_arrow_writer(stream_id="0")
>>> sw = writer.write_blob_stream(column_name="blob")
>>> sw.write(b"payload data")
>>> resp = sw.finish()
>>> print(resp.blob_reference)
class odps.maxstorage.TableArrowBlobUploadWriter(*args, blob_checksum_type=None, blob_mime_type: str | None = None, blob_custom_file_name: str | None = None, blob_metadata_callback: callable | None = None, **kwargs)[源代码]

Arrow writer that auto-uploads BLOB cells and replaces with references.

Subclass of TableArrowWriter. write_batch is overridden to batch-upload raw bytes / file-like BLOB cells via table_batch_write_blob and replace them with reference bytes before forwarding to super().write_batch.

Use this writer when you want inline BLOB content uploaded automatically — create it via auto_upload_blobs=True on TableWriteSession.open_arrow_writer().

参数:
  • *args -- Forwarded to TableArrowWriter.

  • **kwargs -- Forwarded to TableArrowWriter.

  • blob_checksum_type (BlobWriteItem.ChecksumType, optional) -- Checksum algorithm for blob uploads.

  • blob_mime_type (str, optional) -- Session-level default MIME type for blobs.

  • blob_custom_file_name (str, optional) -- Session-level default custom file name (API v3 only).

  • blob_metadata_callback (callable, optional) -- callback(row_index, column_name, blob_data) -> (mime_type, custom_file_name) | None invoked once per inline BLOB cell.

write_batch(batch) → None[源代码]

Override: batch-upload BLOB cells, replace with refs, then super().

A pa.Table may contain multiple record-batch chunks; each chunk is processed independently.

class odps.maxstorage.TableBlockWriter(stub: StorageStub, table_id: TableIdentifier, session_id: str, block_number: int, attempt_number: int, route_token: str, quota_token: str, data_schema: BatchCompatibleDataSchema, enhance_write_check: bool, compress_option: CompressOption | None = None)[源代码]

Arrow writer for one block in WriteMode.BATCH_COMPATIBLE.

Each instance corresponds to one block_number + attempt_number pair. Batches are buffered in memory until commit() or close() finalizes the upload as a single Arrow IPC stream.

When constructed with a compress_option, the uploaded stream uses Arrow IPC's built-in codec (zstd / lz4), matching the writer returned by open_arrow_writer().

Prefer commit() when the returned BlockWriteResult will be used directly. Calling abort() discards buffered batches without creating a remote writer result; the service releases the unused quota reservation after it expires.

Do not reuse a writer after it has been committed, aborted, or closed. Retry the same block with a new attempt_number.

abort() → None[源代码]

Discard locally buffered data without sending it to the service.

bytes_written() → int[源代码]

Total bytes written (uploaded + currently cached).

close() → None[源代码]

Finalize the writer, uploading the block if not already done.

If abort() was called, this is a no-op. Otherwise it uploads the buffered batches. Prefer commit() when the result is needed.

commit() → BlockWriteResult[源代码]

Finalize the block upload and return the commit result.

After commit(), the writer is closed and cannot be reused. Raises IOError if the writer was aborted.

create_vector_schema_root() → pa.Table[源代码]

Create a pyarrow.VectorSchemaRoot matching the session schema.

property schema: pa.Schema

The Arrow schema for this block.

write_batch(root: pa.Table | pa.RecordBatch) → None[源代码]

Buffer one Arrow batch (RecordBatch or Table).

Empty batches are silently skipped. The input schema must match the session schema.

class odps.maxstorage.AppendTableRecordWriter(arrow_writer: TableArrowWriter, row_count_per_batch: int = 1024, blob_batch_file_num: int = 1000)[源代码]

Row-oriented writer wrapping TableArrowWriter.

Converts Record -> Arrow batches. When the underlying writer has auto_upload_blobs=True, BLOB columns are intercepted: file-like objects and raw bytes/bytearray are batch-uploaded by the record writer itself and replaced with references pass through unchanged. When auto_upload_blobs=False, BLOB cells must already contain reference bytes.

close() → None[源代码]

Flush remaining records, then close the underlying writer.

flush() → None[源代码]

Flush buffered records, then flush the underlying writer.

write(record) → None[源代码]

Write a single record.

Accepts odps.types.Record, list, or tuple. BLOB columns may contain: bytes/bytearray (batch-uploaded by the record writer), file-like (streamed in chunks, never fully materialized), str (blob reference, passed through), None (null).

Auto-flushes when row_count >= row_count_per_batch or when the accumulated blob file count >= blob_batch_file_num.

class odps.maxstorage.DeltaTableRecordWriter(arrow_writer: TableArrowWriter, row_count_per_batch: int = 1024, blob_batch_file_num: int = 1000)[源代码]

Record writer for Delta Tables (primary key tables).

write() stamps __operation='U' (UPSERT) and delete() stamps __operation='D' (DELETE) on each record. Both operations can be freely interleaved on a single writer instance.

delete(record) → None[源代码]

Write a record as a DELETE (__operation='D').

write(record) → None[源代码]

Write a record as an UPSERT (__operation='U').

Write Results

class odps.maxstorage.BlockWriteResult(session_id: str, block_number: int, attempt_number: int, record_count: int, commit_message: str)[源代码]

Result produced by a successful TableBlockWriter.commit().

The service commit message remains an implementation detail. Applications should retain or transport this object and pass it to TableWriteSession.commit() with the block_results parameter.

Blob I/O

class odps.maxstorage.BlobManager(client: MaxStorageClient, table_id: TableIdentifier | None = None)[源代码]

Standalone blob read/write manager.

Constructed from a MaxStorageClient; reuses its StorageStub for all HTTP operations.

参数:
  • client (MaxStorageClient) -- The parent client.

  • table_id (TableIdentifier, optional) -- Table identifier — required for write operations (write_blob_stream, write_blob_batch).

示例

>>> blob_manager = client.open_blob_manager("my_table")
>>> # Read blobs by reference
>>> for record in blob_manager.read_blobs([ref1, ref2]):
...     print(len(record.data))
>>> # Stream a single blob
>>> reader = blob_manager.read_blobs([ref], stream=True)
>>> while True:
...     chunk = reader.read(4096)
...     if not chunk:
...         break
...     process(chunk)
build_blob_write_item(data, session_id, *, column_name=None, partition_spec=None, distribution_key=None, mime_type=None, custom_file_name=None, checksum_type=ChecksumType.NONE) → BlobWriteItem[源代码]

Build a BlobWriteItem from writer-resolved state.

column_name is resolved to the server-assigned column ID via the write schema. When omitted, the sole top-level pure-BLOB column is auto-selected (raises if the schema has multiple BLOB columns or any nested BLOB column). partition_spec accepts the same types as PartitionSpec. api_version is stamped from the client so v3-only fields are gated automatically.

示例

>>> blob_manager = client.open_blob_manager("my_table")
>>> write_session = client.create_table_write_session("my_table")
>>> items = [
...     blob_manager.build_blob_write_item(
...         b"payload", write_session.id, column_name="blob",
...         mime_type="application/octet-stream",
...     )
... ]
read_blob(blob_reference: str | bytes, *, compress_option: CompressOption | None = None, compress_algo=None) → BytesIO[源代码]

Download a single blob and return a io.BytesIO over its data.

Delegates to read_blobs() with a single-element reference list. The server returns a raw unframed stream for single-ref requests, so no frame headers are parsed. Compression follows the same pattern as read_blobs(): compress_option (default None = uncompressed) or the shorthand compress_algo. The reference must be UTF-8 decodable.

示例

>>> blob_manager = client.open_blob_manager()
>>> bio = blob_manager.read_blob(ref)
>>> data = bio.read()
>>> print(len(data))
read_blobs(blob_references: List[str | bytes], *, compress_option: CompressOption | None = None, compress_algo=None, stream: bool = False) → BlobDataIterator | BlobStreamReader[源代码]

Download blobs by their references.

The server's response framing depends on the number of references:

  • Single reference: the server returns raw unframed blob bytes (no [HeaderLen][Header][DataLen][Data] frames). The entire decompressed payload is yielded as one BlobRecord.

  • Multiple references: the server returns a framed stream with one frame per blob. Each BlobRecord carries the blob's MIME type and custom file name (v3+) from the frame header.

References must be UTF-8 decodable strings or bytes. Binary (non-UTF-8) references returned for nested BLOB columns are not supported by the generic BlobRead endpoint; reading them raises StorageClientError. Compression follows the tunnel pattern: compress_option (default None = uncompressed) or the shorthand compress_algo. Pass compress_algo="lz4" / "zstd" to request a compressed response. When stream=True, returns a BlobStreamReader for incremental file-like reads; otherwise returns a BlobDataIterator yielding BlobRecord.

示例

>>> blob_manager = client.open_blob_manager()
>>> # Materialize each blob
>>> for record in blob_manager.read_blobs([ref1, ref2]):
...     print(len(record.data))
>>>
>>> # Incremental streaming read
>>> reader = blob_manager.read_blobs([ref], stream=True)
>>> while True:
...     chunk = reader.read(4096)
...     if not chunk:
...         break
...     process(chunk)
...     reader = reader.next()
write_blob_batch(items: List[BlobWriteItem], session_id: str, stream_id: str, *, stream_version: int = 1, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None) → WriteBlobResponse[源代码]

Batch-upload multiple blobs in one request.

Each BlobWriteItem is framed and streamed to the server via chunked transfer-encoding — the full batch body is never materialized. Compression via compress_option (default None = uncompressed). Returns WriteBlobResponse with blob_references matching input order.

示例

>>> blob_manager = client.open_blob_manager("my_table")
>>> write_session = client.create_table_write_session("my_table")
>>> items = [
...     blob_manager.build_blob_write_item(
...         b"a", write_session.id, column_name="blob",
...     ),
...     blob_manager.build_blob_write_item(
...         b"b", write_session.id, column_name="blob",
...     ),
... ]
>>> resp = blob_manager.write_blob_batch(
...     items, write_session.id, stream_id="0",
... )
>>> print(len(resp.blob_references))
write_blob_stream(session_id: str, stream_id: str, *, stream_version: int = 1, column_name: str | None = None, partition_spec: str | dict | PartitionSpec | None = None, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None) → BlobStreamWriter[源代码]

Create a streaming writer for a single blob upload.

Uses chunked transfer-encoding; compression via compress_option (default None = uncompressed; ZSTD/LZ4_FRAME opt-in via Content-Encoding). The returned BlobStreamWriter computes MD5 incrementally and verifies on finish().

column_name is the dot-path name (a key of WriteSchema.find_all_blob_column_ids()), resolved to the server-assigned column ID via the write schema. When omitted, the sole top-level pure-BLOB column is auto-selected (raises if the schema has multiple BLOB columns or any nested BLOB column).

partition_spec accepts the same types as PartitionSpec (str, dict, or PartitionSpec).

示例

>>> blob_manager = client.open_blob_manager("my_table")
>>> write_session = client.create_table_write_session("my_table")
>>> sw = blob_manager.write_blob_stream(
...     write_session.id, stream_id="0", column_name="blob",
... )
>>> sw.write(b"payload data")
>>> resp = sw.finish()
>>> print(resp.blob_reference)
class odps.maxstorage.BlobRecord(data: bytes, mime_type: str | None, custom_file_name: str | None = None)[源代码]

A single downloaded blob yielded by BlobDataIterator.

custom_file_name is only populated when the client targets API v3+; it is None on v2 (the CustomFileName header is not parsed).

class odps.maxstorage.BlobDataIterator(raw_stream, api_version: str = '2', expected_count: int | None = None, crc_strip: bool = True)[源代码]

Iterator yielding BlobRecord per blob.

read_data(size: int = -1) → bytes[源代码]

Read up to size bytes of the current blob's data (for BlobStreamReader).

Skip remaining_bytes of unread data and the trailing footer.

class odps.maxstorage.BlobStreamReader(iterator: BlobDataIterator)[源代码]

File-like reader for streaming blob data from a BlobDataIterator.

Provides read(size) for incremental reads of the current blob, mime_type / custom_file_name properties, and a next() method to advance to the next blob. Avoids materializing entire blobs.

If next() is called before the current blob is fully read, the reader auto-drains the remaining bytes. Returns None from next() when no more blobs remain.

next() → BlobStreamReader | None[源代码]

Advance to the next blob in-place. Returns self or None.

class odps.maxstorage.BlobStreamWriter(upload: Callable, compress_option: CompressOption | None = None, api_version: str = '2')[源代码]

Stream writer for single blob upload with MD5 checksum verification.

Wraps a RequestsIO + compressor pipeline. Data written via write() is compressed (if requested) and streamed to the server in chunks via chunked transfer-encoding — the full blob is never held in memory. MD5 is computed incrementally on the uncompressed data and verified against the server response on finish().

finish() → WriteBlobResponse[源代码]

Finish writing, send the data, and verify MD5.

Returns the parsed WriteBlobResponse on success. Raises odps.errors.ChecksumError on MD5 mismatch, or MaxStorageError if the upload fails with a non-200 response.

writable() → bool[源代码]

Return whether object was opened for writing.

If False, write() will raise OSError.

class odps.maxstorage.BlobWriteItem(data, *, column_id, partition_values=None, distribution_key=None, mime_type=None, custom_file_name=None, checksum_type=ChecksumType.NONE, api_version='2')[源代码]

A single blob item for batch upload.

备注

Prefer TableArrowWriter.build_blob_write_item() or BlobManager.build_blob_write_item() to construct items — they resolve column_id, normalize partition_spec, and stamp api_version automatically. Constructing BlobWriteItem directly requires knowledge of server-assigned column IDs and wire-format details.

Schema and Options

class odps.maxstorage.WriteMode(value)[源代码]

Write-session mode.

BATCH / BATCH_COMPATIBLE -- data visible only after commit. STREAMING / STREAMING_REALTIME -- data visible immediately on flush.

is_streaming()[源代码]

True for STREAMING / STREAMING_REALTIME.

class odps.maxstorage.SplitMode(value)[源代码]

Data-splitting strategy for read sessions.

JSON values: "Size", "Parallelism", "RowOffset", "Bucket".

class odps.maxstorage.SplitOptions(split_mode: object = None, split_unit: str = 'ByteSize', split_number: int = 268435456, cross_partition: bool = True, bucket_sort: bool = False)[源代码]

Controls how a read session splits data.

Fields

split_modeSplitMode

Strategy: SIZE (default), ROW_OFFSET, PARALLELISM, BUCKET.

split_unitstr

Unit of split_number. Default "ByteSize".

split_numberint

Target split size (bytes) for SIZE mode, or row count for ROW_OFFSET. Default 256 MiB.

cross_partitionbool

Whether splits may cross partition boundaries. Default True.

bucket_sortbool

Whether bucket split results keep the clustered ordering. Only meaningful for BUCKET splits. Default False.

class odps.maxstorage.IncrementalReadOptions(version: str | None = None, from_: int | str | None = None, to: int | str | None = None, start_txn_id: str | None = None)[源代码]

Incremental-read configuration.

Wire fields: {Mode, From, To, StartTxnId}. version selects the incremental mode; from_/to are version boundaries (int) or timestamps (str); start_txn_id requests exactly-once incremental reads starting after the given transaction id.

class odps.maxstorage.BatchCompatibleOptions(enhance_write_check: bool = False, max_field_size: int = 0, dynamic_partition_limit: int = -1)[源代码]

Immutable advanced settings for WriteMode.BATCH_COMPATIBLE.

Pass directly to MaxStorageClient.create_table_write_session() via the batch_compatible_options parameter.

When unset, the server applies its own defaults. max_field_size (if set) must be at least 1024 bytes; dynamic_partition_limit uses -1 to mean "server default".

classmethod create_default() → BatchCompatibleOptions[源代码]

Return the default options (all server-side defaults).

property max_field_size: int

Zero means the server should use its project-level default.

class odps.maxstorage.DataFormat(type='Arrow', version='V5')[源代码]

Arrow data-format descriptor.

JSON: {"Type": "Arrow", "Version": "V5"} (defaults). Not an enum — it carries two free-form string fields.

class odps.maxstorage.SessionStatus(value)[源代码]

Read/write session lifecycle status.

classmethod from_string(value)[源代码]

Parse a status string; None/empty -> UNKNOWN.

class odps.maxstorage.SessionKind(value)[源代码]

What a session descriptor describes.

Members BATCH_READ / INCREMENTAL_READ / BATCH_WRITE; their JSON values are "batch-read" / "incremental-read" / "batch-write".

classmethod from_string(value)[源代码]

Parse a descriptor kind, accepting a member or its string value.

Unknown values raise ValueError: the kind is part of the descriptor contract, so it must not fall back silently.

class odps.maxstorage.Status(value)[源代码]

Writer / stream status.

class odps.maxstorage.TimestampUnit(value)[源代码]

Arrow timestamp precision.

JSON: "second", "milli", "micro", "nano".

Errors

class odps.maxstorage.MaxStorageError(msg, request_id=None, code=None, host_id=None, instance_id=None, endpoint=None, tag=None, response_headers=None, status_code=None)[源代码]

Base class for all maxstorage errors.

class odps.maxstorage.StorageServiceError(http_status, error_code=None, message=None, request_id=None)[源代码]

Server-side error.

Fields

http_statusint

HTTP status code of the failing response.

error_codestr

Server error code parsed from the JSON body.

messagestr

Human-readable error message.

request_idstr

x-odps-request-id response header (may be None).

class odps.maxstorage.StorageClientError(msg, request_id=None, code=None, host_id=None, instance_id=None, endpoint=None, tag=None, response_headers=None, status_code=None)[源代码]

Client-side error (network, invalid parameters, etc.).

class odps.maxstorage.BlobDownloadError(message, failed_blob_ref=None)[源代码]

Blob download failure — carries the failing blob reference.