Skip to content

API 参考 ​

Fluss Python 客户端的完整 API 参考。

Config ​

方法 / 属性配置键描述
Config(properties: dict = None)从键值对 dict 创建 config
bootstrap_serversbootstrap.servers获取/设置 coordinator server 地址
writer_request_max_sizewriter.request-max-size获取/设置最大请求大小(字节)
writer_ackswriter.acks获取/设置确认设置("all" 表示所有副本)
writer_retrieswriter.retries获取/设置失败重试次数
writer_batch_sizewriter.batch-size获取/设置写入批次大小(字节)。开启动态调整时作为上限;关闭时为固定批次大小
writer_dynamic_batch_size_enabledwriter.dynamic-batch-size.enabled获取/设置是否启用按表的动态批次大小估算(默认 true)
writer_dynamic_batch_size_minwriter.dynamic-batch-size-min获取/设置动态批次大小估算的下限(默认 256 KB;禁用时忽略)
writer_batch_timeout_mswriter.batch-timeout-ms获取/设置在发送前等待 writer 批次填满的最大时间(毫秒)
writer_bucket_no_key_assignerwriter.bucket.no-key-assigner获取/设置 bucket 分配策略("sticky" 或 "round_robin")
writer_dynamic_create_partition_enabledwriter.dynamic-create-partition.enabled获取/设置写入是否自动创建尚不存在的分区(默认 true);为 false 时,此类写入以 ErrorCode.PARTITION_NOT_EXISTS 失败
scanner_remote_log_prefetch_numscanner.remote-log.prefetch-num获取/设置预取的 remote log 段数量
remote_file_download_thread_numremote-file.download-thread-num获取/设置 remote log 下载线程数
scanner_remote_log_read_concurrencyscanner.remote-log.read-concurrency获取/设置单个 remote log 文件内的流式读取并发度
scanner_io_tmp_dirscanner.io.tmpdir获取/设置远程日志下载的父目录;None 表示使用操作系统临时目录加 /fluss
scanner_log_max_poll_recordsscanner.log.max-poll-records获取/设置单次 poll() 返回的最大记录数
scanner_log_fetch_max_bytesscanner.log.fetch.max-bytes获取/设置 LogScanner 每次 fetch 响应的最大字节数
scanner_log_fetch_min_bytesscanner.log.fetch.min-bytes获取/设置服务端返回 fetch 响应前必须累积的最小字节数
scanner_log_fetch_wait_max_time_msscanner.log.fetch.wait-max-time-ms获取/设置服务端为满足 min-bytes 可等待的最长时间(毫秒)
scanner_log_fetch_max_bytes_for_bucketscanner.log.fetch.max-bytes-for-bucket获取/设置 LogScanner 每个 bucket 每次 fetch 响应的最大字节数
scanner_log_check_crcscanner.log.check-crc获取/设置是否检查所拉取日志批次的 CRC(默认 true);服务端投影(projected)的批次不检查
lookup_queue_sizelookup.queue-size获取/设置发送队列容量;队列满时新的 lookup 会等待。每个 bucket 在等待 leader 期间也最多容纳这么多个 lookup;超出该 bucket 的 lookup 会立即因缓冲区耗尽错误而失败(默认 25600)
lookup_max_batch_sizelookup.max-batch-size获取/设置合并到单个请求中的 lookup 最大数量(默认 128)
lookup_batch_timeout_mslookup.batch-timeout-ms获取/设置 lookup 等待批次填满的最大毫秒数(默认 100)
lookup_max_inflight_requestslookup.max-inflight-requests获取/设置未确认 lookup 请求的最大数量(默认 128)
lookup_max_retrieslookup.max-retries获取/设置 lookup 的最大重试次数(默认 2147483647)。等待 bucket 的 leader 不算重试,因此这不是 lookup 超时
lookup_retry_backoff_mslookup.retry-backoff-ms获取/设置 lookup 重试的初始退避(毫秒),每次重试翻倍并带有 ±20% 抖动;也是无已知 leader 的 bucket 刷新之间的初始延迟,该延迟按 bucket 递增并由其 lookup 共享。0 表示立即重试和刷新(默认 100)
lookup_retry_max_backoff_mslookup.retry-max-backoff-ms获取/设置 lookup 重试退避的上限(毫秒),在抖动之前生效,同时也限制无已知 leader 的 bucket 刷新之间的延迟;必须 >= lookup_retry_backoff_ms(默认 1000)
connect_timeout_msconnect-timeout获取/设置连接建立超时(毫秒),包括 TCP 连接、API 协商和 SASL 认证
connection_max_idle_time_msconnection.max-idle-time-ms获取/设置空闲缓存连接被关闭的时间(毫秒),仍在等待这些连接的请求会以可重试错误失败;0 表示禁用关闭空闲连接(默认 600000)
security_protocolsecurity.protocol获取/设置安全协议("PLAINTEXT" 或 "sasl")
security_sasl_mechanismsecurity.sasl.mechanism获取/设置 SASL 机制(仅支持 "PLAIN")
security_sasl_usernamesecurity.sasl.username获取/设置 SASL 用户名(协议为 "sasl" 时必填)
security_sasl_passwordsecurity.sasl.password获取/设置 SASL 密码(协议为 "sasl" 时必填)

FlussConnection ​

方法描述
await FlussConnection.create(config) -> FlussConnection连接到 Fluss 集群
conn.get_admin() -> FlussAdmin获取 admin 接口
await conn.get_table(table_path) -> FlussTable获取用于读写操作的表
await conn.close()关闭连接

支持 async with 语句(异步上下文管理器)。

FlussAdmin ​

方法描述
await create_database(name, database_descriptor=None, ignore_if_exists=False)创建数据库
await drop_database(name, ignore_if_not_exists=False, cascade=True)删除数据库
await list_databases() -> list[str]列出所有数据库
await database_exists(name) -> bool检查数据库是否存在
await get_database_info(name) -> DatabaseInfo获取数据库元数据
await create_table(table_path, table_descriptor, ignore_if_exists=False)创建表
await drop_table(table_path, ignore_if_not_exists=False)删除表
await get_table_info(table_path) -> TableInfo获取表元数据
await list_tables(database_name) -> list[str]列出数据库中的表
await table_exists(table_path) -> bool检查表是否存在
await list_offsets(table_path, bucket_ids, offset_spec) -> dict[int, int]获取各 bucket 的 offset
await list_partition_offsets(table_path, partition_name, bucket_ids, offset_spec) -> dict[int, int]获取某个分区各 bucket 的 offset
await create_partition(table_path, partition_spec, ignore_if_exists=False)创建分区
await drop_partition(table_path, partition_spec, ignore_if_not_exists=False)删除分区
await list_partition_infos(table_path) -> list[PartitionInfo]列出分区
await get_latest_lake_snapshot(table_path) -> LakeSnapshot获取最新 lake snapshot
await get_server_nodes() -> list[ServerNode]获取所有存活的服务端节点

ServerNode ​

属性描述
.id -> int服务端节点 ID
.host -> str服务端主机名
.port -> int端口号
.server_type -> str服务端类型("CoordinatorServer"、"TabletServer" 或 "Unknown")
.uid -> str唯一标识(例如 "cs-0"、"ts-1")

当客户端尚未确定端点类型时(例如 bootstrap 端点),会使用 "Unknown"。

FlussTable ​

方法描述
new_scan() -> TableScan创建 scan builder
new_append() -> TableAppend为 Log Table 创建 append builder
new_upsert() -> TableUpsert为 PK 表创建 upsert builder
new_lookup() -> TableLookup为 PK 表创建 lookup builder
get_table_info() -> TableInfo获取表元数据
get_table_path() -> TablePath获取表路径
has_primary_key() -> bool检查表是否有主键
属性描述
.arrow_schema -> pa.Schemawrite_arrow_batch 期望的 Arrow schema

TableScan ​

方法描述
.project(indices) -> TableScan按索引投影列
.project_by_name(names) -> TableScan按名称投影列
.limit(n) -> TableScan设置正的行数上限(启用 create_bucket_batch_scanner;log scanner 会拒绝)
.filter(predicate) -> TableScan下推过滤器以在服务端进行批次剪枝(参见 col)
await .create_log_scanner() -> LogScanner创建基于记录的 scanner(用于 poll());在 PrimaryKey Table 上订阅其 CDC changelog(逐记录 change_type)
await .create_record_batch_log_scanner() -> LogScanner创建基于批次的 scanner(用于 poll_arrow()、to_arrow() 等);仅限 Log Table——没有逐记录的 change type
.create_bucket_batch_scanner(bucket) -> BatchScanner对单个 bucket 进行有界扫描(需要 limit;在首次 next_batch() 时执行)

col ​

fluss.col(name) 返回一个 ColumnRef,用于为 TableScan.filter() 构建过滤器。剪枝是保守的:返回的批次中仍可能包含不匹配的行,因此需要在结果上再次应用该谓词。

方法描述
col(name) >= value (>, <, <=, ==, !=)比较谓词
.equal(v), .not_equal(v)等同于 == 和 !=
.less_than(v), .less_or_equal(v)等同于 < 和 <=
.greater_than(v), .greater_or_equal(v)等同于 > 和 >=
.is_null(), .is_not_null()基于批次的 null 计数进行剪枝
.starts_with(p), .ends_with(s), .contains(i)字符串谓词
.is_in(values), .not_in(values)集合成员判断

谓词通过 & 和 |(或 and_()、or_())组合。

字面量是普通 Python 值,列的类型决定它们的编码方式,因此 col("id") >= 200 适用于任何整数列,而超出范围的 literal 会在创建 scanner 时被拒绝:

Python 类型Fluss 列类型
boolBOOLEAN
intTINYINT、SMALLINT、INT、BIGINT(检查范围)
floatDOUBLE,以及可精确表示时的 FLOAT
strCHAR、STRING
bytesBINARY、BYTES
None不可比较;使用 .is_null() / .is_not_null()
decimal.DecimalDECIMAL,若列的 scale 无法精确容纳则拒绝
datetime.dateDATE
datetime.timeTIME
datetime.datetime非时区感知时为 TIMESTAMP,时区感知时为 TIMESTAMP_LTZ
python
from fluss import col

hot = (col("id") >= 200) & col("name").starts_with("high")
scanner = await table.new_scan().filter(hot).create_log_scanner()

TableAppend ​

用于创建 AppendWriter 的 builder。通过 FlussTable.new_append() 获取。

方法描述
.create_writer() -> AppendWriter创建 append writer

TableUpsert ​

用于创建 UpsertWriter 的 builder。通过 FlussTable.new_upsert() 获取。

方法描述
.partial_update_by_name(columns) -> TableUpsert按列名配置部分更新
.partial_update_by_index(indices) -> TableUpsert按列索引配置部分更新
.create_writer() -> UpsertWriter创建 upsert writer

TableLookup ​

用于创建 Lookuper 或 PrefixLookuper 的 builder。通过 FlussTable.new_lookup() 获取。

方法描述
.create_lookuper() -> Lookuper创建主键 lookuper
.lookup_by(column_names) -> TablePrefixLookup切换为给定列(分区键 + bucket 键)的前缀扫描模式

TablePrefixLookup ​

用于创建 PrefixLookuper 的 builder。通过 TableLookup.lookup_by(columns) 获取。

方法描述
.create_lookuper() -> PrefixLookuper创建 prefix lookuper

AppendWriter ​

方法描述
.append(row) -> WriteResultHandle追加一行(dict、list 或 tuple)
.write_arrow(table)写入一个 PyArrow Table
.write_arrow_batch(batch) -> WriteResultHandle写入一个 PyArrow RecordBatch,其列类型必须匹配 table.arrow_schema
.write_pandas(df)写入一个 Pandas DataFrame
await .flush()刷新所有待处理的写入

UpsertWriter ​

方法描述
.upsert(row) -> WriteResultHandleUpsert 一行(按 PK 插入或更新)
.delete(pk) -> WriteResultHandle按主键删除一行
await .flush()刷新所有待处理的操作

WriteResultHandle ​

方法描述
await .wait()等待服务端确认本次写入

Lookuper ​

方法描述
await .lookup(pk) -> dict | None按主键查找一行

PrefixLookuper ​

方法描述
await .lookup(prefix) -> list[dict]查找所有匹配前缀键的行

LogScanner ​

方法描述
.subscribe(bucket_id, start_offset)订阅一个 bucket
.subscribe_buckets(bucket_offsets)订阅多个 bucket({bucket_id: offset})
.subscribe_partition(partition_id, bucket_id, start_offset)订阅一个分区 bucket
.subscribe_partition_buckets(partition_bucket_offsets)订阅多个分区 + bucket 组合({(part_id, bucket_id): offset})
.unsubscribe(bucket_id)取消订阅一个 bucket(非分区表)
.unsubscribe_partition(partition_id, bucket_id)取消订阅一个分区 bucket
await .poll(timeout_ms) -> ScanRecords轮询单条记录(仅 record scanner)
await .poll_arrow(timeout_ms) -> pa.Table以 Arrow Table 轮询(仅 batch scanner)
await .poll_record_batch(timeout_ms) -> list[RecordBatch]轮询带元数据的批次(仅 batch scanner)
.to_arrow_batch_reader() -> pa.RecordBatchReader惰性 Arrow RecordBatchReader,读取至最新 offset(仅 batch scanner)
await .to_arrow() -> pa.Table将所有已订阅数据读取为 Arrow Table(仅 batch scanner)
await .to_pandas() -> pd.DataFrame将所有已订阅数据读取为 DataFrame(仅 batch scanner)

注意: 不支持在同一个底层 scanner 上重叠调用 poll_* / to_arrow* / to_arrow_batch_reader。同一时间只能使用一条活跃的轮询/消费路径。

BatchScanner ​

对单个 bucket 的一次性有界扫描。通过 table.new_scan().limit(n).create_bucket_batch_scanner(bucket) 获取。扫描在下面第一次调用时执行,产出其唯一的批次一次,然后即被用尽(再次扫描需创建新的 scanner)。

方法描述
.bucket -> TableBucket正在扫描的 bucket(属性)
await .next_batch() -> RecordBatch | None执行扫描;返回该批次一次,之后返回 None
await .collect_all_batches() -> list[RecordBatch]排空为批次列表
await .to_arrow() -> pa.Table排空为单个 Arrow Table
await .to_pandas() -> pd.DataFrame排空为 Pandas DataFrame

ScanRecords ​

由 LogScanner.poll() 返回。记录按 bucket 分组。

注意: 扁平迭代和整数索引遍历 bucket 的顺序是任意的,在单个 ScanRecords 实例内保持一致,但在不同 poll() 调用之间可能不同。当 bucket 顺序重要时,请使用按 bucket 访问(.items()、.records(bucket))。

python
scan_records = await scanner.poll(timeout_ms=5000)

# Sequence access
scan_records[0]                              # first record
scan_records[-1]                             # last record
scan_records[:5]                             # first 5 records

# Per-bucket access
for bucket, records in scan_records.items():
    for record in records:
        print(f"bucket={bucket.bucket_id}, offset={record.offset}, row={record.row}")

# Flat iteration
for record in scan_records:
    print(record.row)

方法 ​

方法描述
.buckets() -> list[TableBucket]去重后的 bucket 列表
.records(bucket) -> list[ScanRecord]指定 bucket 的记录(若该 bucket 不存在则为空列表)
.count() -> int所有 bucket 的记录总数
.is_empty() -> bool检查是否为空

索引 ​

表达式返回描述
scan_records[0]ScanRecord按扁平索引获取记录
scan_records[-1]ScanRecord负数索引
scan_records[1:5]list[ScanRecord]切片
scan_records[bucket]list[ScanRecord]某个 bucket 的记录

映射协议 ​

方法 / 协议描述
.keys()等同于 .buckets()
.values()对记录列表的惰性迭代器,每个 bucket 一个
.items()对 (bucket, records) 对的惰性迭代器
len(scan_records)等同于 .count()
bucket in scan_records成员测试
for record in scan_records对所有记录进行扁平迭代

ScanRecord ​

属性描述
.offset -> int记录在 log 中的 offset
.timestamp -> int记录时间戳
.change_type -> ChangeType变更类型(AppendOnly、Insert、UpdateBefore、UpdateAfter、Delete)
.row -> dict行数据,格式为 {column_name: value}

RecordBatch ​

属性描述
.batch -> pa.RecordBatchArrow RecordBatch 数据
.bucket -> TableBucket该批次所属的 bucket
.base_offset -> int第一条记录的 offset
.last_offset -> int最后一条记录的 offset
.commit_timestamp -> int提交时间(毫秒时间戳)
.schema_id -> int来源 log batch 的 Schema ID

.commit_timestamp 在该 batch 不携带单一时间戳时为 fluss.NO_COMMIT_TIMESTAMP(-1);limit scan 会将多个 log batch 合并为一个 Arrow batch,因此属于这种情况。

.schema_id 是写入该 log batch 时所用 schema 的 ID。它可能与 batch 各列所属的 schema 不同,因为默认情况下 scanner 会将每个 batch 对齐到创建它时所使用的表 schema。对于 limit scan,它为 fluss.NO_SCHEMA_ID(-1);limit scan 会将多个 log batch 合并为一个 batch。

Schema ​

方法描述
Schema(schema: pa.Schema, primary_keys=None, auto_increment_column=None)从 PyArrow schema 创建。字段的可空性(pa.field(..., nullable=False))会被保留。auto_increment_column 必须指定一个 PrimaryKey Table 的 INT 或 BIGINT 列,且该列本身不是主键列。
.get_column_names() -> list[str]获取列名
.get_column_types() -> list[str]获取列类型名。不可空类型带有 " NOT NULL" 后缀(例如 "int NOT NULL")。
.get_columns() -> list[tuple[str, str]]获取 (name, type) 对。类型字符串的可空性格式与 .get_column_types() 相同。
.get_primary_keys() -> list[str]获取主键列
.get_auto_increment_columns() -> list[str]获取自增列,没有则为空

TableDescriptor ​

方法描述
TableDescriptor(schema, *, partition_keys=None, bucket_count=None, bucket_keys=None, comment=None, log_format=None, kv_format=None, properties=None, custom_properties=None)创建表描述符
.get_schema() -> Schema获取 schema

TablePath ​

方法 / 属性描述
TablePath(database, table)创建表路径
.database_name -> str数据库名
.table_name -> str表名

TableInfo ​

属性 / 方法描述
.table_id -> int表 ID
.table_path -> TablePath表路径
.num_buckets -> intbucket 数量
.schema_id -> intSchema ID
.comment -> str | None表注释
.created_time -> int创建时间戳
.modified_time -> int最后修改时间戳
.get_primary_keys() -> list[str]主键列
.get_partition_keys() -> list[str]分区列
.get_bucket_keys() -> list[str]Bucket key 列
.has_primary_key() -> bool是否有主键?
.is_partitioned() -> bool是否为分区表?
.get_schema() -> Schema获取表 schema
.get_column_names() -> list[str]列名
.get_column_count() -> int列数
.get_properties() -> dict所有表属性
.get_custom_properties() -> dict仅自定义属性

PartitionInfo ​

属性描述
.partition_id -> int分区 ID
.partition_name -> str分区名
.bucket_count -> int分区的 bucket 数

DatabaseDescriptor ​

方法 / 属性描述
DatabaseDescriptor(comment=None, custom_properties=None)创建描述符
.comment -> str | None数据库注释
.get_custom_properties() -> dict自定义属性

DatabaseInfo ​

属性 / 方法描述
.database_name -> str数据库名
.created_time -> int创建时间戳
.modified_time -> int最后修改时间戳
.get_database_descriptor() -> DatabaseDescriptor获取描述符

LakeSnapshot ​

属性 / 方法描述
.snapshot_id -> intSnapshot ID
.table_buckets_offset -> dict[TableBucket, int]所有 bucket 的 offset
.get_bucket_offset(bucket) -> int | None获取某个 bucket 的 offset
.get_table_buckets() -> list[TableBucket]获取所有 bucket

TableBucket ​

方法 / 属性描述
TableBucket(table_id, bucket)创建非分区 bucket
TableBucket.with_partition(table_id, partition_id, bucket)创建分区 bucket
.table_id -> int表 ID
.bucket_id -> intBucket ID
.partition_id -> int | None分区 ID(非分区时为 None)

FlussError ​

属性描述
.message -> str错误信息
.error_code -> int错误码(客户端错误为 ErrorCode.CLIENT_ERROR,否则为服务端错误码)

所有 Fluss 特定错误(连接失败、表未找到、schema 不匹配等)都会抛出此异常。它继承自 Exception。有关匹配特定错误码的详情,请参阅 错误处理。

常量 ​

常量值描述
fluss.EARLIEST_OFFSET-2从最早可用的 offset 开始读取

OffsetSpec ​

方法描述
OffsetSpec.earliest()最早可用的 offset
OffsetSpec.latest()最新 offset
OffsetSpec.timestamp(ts)大于等于给定时间戳(毫秒)的 offset

要从最新 offset 开始读取(仅新记录),请在订阅前通过 list_offsets 解析当前 offset:

python
offsets = await admin.list_offsets(table_path, [0], fluss.OffsetSpec.latest())
scanner.subscribe(bucket_id=0, start_offset=offsets[0])

ChangeType ​

值短字符串描述
ChangeType.AppendOnly (0)+A仅追加
ChangeType.Insert (1)+I插入
ChangeType.UpdateBefore (2)-U更新行的旧值
ChangeType.UpdateAfter (3)+U更新行的新值
ChangeType.Delete (4)-D删除

Fluss 中文文档