Skip to content

PrimaryKey Table ​

PrimaryKey Table 支持 upsert、delete 和点查(point lookup)操作。

创建 PrimaryKey Table ​

将 primary_keys 传给 fluss.Schema:

python
import pyarrow as pa

schema = fluss.Schema(
    pa.schema([
        pa.field("id", pa.int32()),
        pa.field("name", pa.string()),
        pa.field("age", pa.int64()),
    ]),
    primary_keys=["id"],
)
table_path = fluss.TablePath("fluss", "users")
await admin.create_table(table_path, fluss.TableDescriptor(schema, bucket_count=3), ignore_if_exists=True)

Upsert、Delete、Lookup ​

python
table = await conn.get_table(table_path)

# Upsert (fire-and-forget, flush at the end)
writer = table.new_upsert().create_writer()
writer.upsert({"id": 1, "name": "Alice", "age": 25})
writer.upsert({"id": 2, "name": "Bob", "age": 30})
await writer.flush()

# Per-record acknowledgment (for read-after-write)
handle = writer.upsert({"id": 3, "name": "Charlie", "age": 35})
await handle.wait()

# Delete by primary key
handle = writer.delete({"id": 2})
await handle.wait()

# Lookup
lookuper = table.new_lookup().create_lookuper()
result = await lookuper.lookup({"id": 1})
if result:
    print(f"Found: name={result['name']}, age={result['age']}")

部分更新 ​

更新特定列而保留其他列:

python
partial_writer = table.new_upsert().partial_update_by_name(["id", "age"]).create_writer()
partial_writer.upsert({"id": 1, "age": 27})  # only updates age
await partial_writer.flush()

订阅 Changelog(CDC) ​

每个 PrimaryKey Table 都维护一份其行级变更的 changelog。使用 record 模式的 scanner——与 Log Table 相同的 API——读取它以流式获取 CDC 事件。每个 ScanRecord 都带有 change_type:+I(插入)、-U / +U(更新前后的旧值与新值)以及 -D(删除,携带旧行)。

python
table = await conn.get_table(table_path)
scanner = await table.new_scan().create_log_scanner()

# Subscribe to every bucket from the start of the changelog.
num_buckets = (await admin.get_table_info(table_path)).num_buckets
scanner.subscribe_buckets({i: fluss.EARLIEST_OFFSET for i in range(num_buckets)})

while True:
    records = await scanner.poll(3000)
    if records.is_empty():
        break
    for record in records:
        print(record.change_type.short_string(), record.row)  # +I / -U / +U / -D

在使用默认 changelog 模式('table.changelog.image' = 'FULL')时,更新一个 key 会发出 -U/+U 对,删除它会发出 -D;WAL 模式在更新时只发出 +U。要从已提交的位置而非开头恢复,请在特定 offset 处 subscribe。

Limit Scan ​

要在不提供 key 的情况下读取某个 bucket 当前状态中最多 n 行,使用 batch scanner。服务端会以 Arrow 批次返回去重后的当前行——便于预览或作为 DataFusion 数据源。

python
bucket = fluss.TableBucket(table.get_table_info().table_id, 0)
scanner = table.new_scan().limit(10).create_bucket_batch_scanner(bucket)
arrow_table = await scanner.to_arrow()

Limit 按 bucket 生效;要覆盖多 bucket 表,需扫描每个 bucket。

Fluss 中文文档