1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

簡易Icebergクライアント実装で学ぶテーブル操作【SELECT編】

1
Last updated at Posted at 2025-12-17

Iceberg Advent Calendar 2025の18日目の記事になります。

はじめに

SparkやTrinoのようなIcebergクライアントの気持ちを理解するため、Pythonで簡易的なIcebergクライアントを実装してみようという記事になります。
本記事ではRESTカタログへのSELECT操作を対象にします。
既存のIcebergクライアントの動作を完全に模倣する目的ではないので、非効率なコードなどあるかもしれませんがご容赦ください。

実行環境

Iceberg関連

以下の構成になっています。

実際に動かすまでは以下の記事が非常に参考になります!

Python関連

  • Python 3.11.7
  • HTTPクライアント: requests==2.32.5
  • S3クライアント: boto3==1.40.62
  • Avro操作: avro==1.12.1
  • Parquet操作: pyarrow==22.0.0

それぞれのライブラリの使用目的は操作の中でわかると思います。

事前準備

テーブルを作ってデータを入れておく必要がありますが、ここはSparkで行います。
Spark 3.5.5で先程の構成のIceberg(Docker)を操作できるよう設定して実施しました。

DBを作成し、

CREATE DATABASE iceberg_db;

テーブルを作成します。
パーティションのカラムを1つ設定しておきます。
簡単にするためTransformなどは使用しません。
プロパティ類はデフォルト値のままにしているので、書き込み時にはzstd圧縮のParquetになります。

CREATE TABLE iceberg_db.orders (
  order_id   INT,
  category   STRING,
  amount     LONG,
  ordered_at TIMESTAMP
) USING iceberg
PARTITIONED BY (category)
;

スナップショットIDが複数発行されるよう複数回に分けてINSERTします。

INSERT INTO iceberg_db.orders
VALUES
  (1, 'electronics', 1500, TIMESTAMP '2025-01-01 10:00:00'),
  (2, 'electronics', 1200, TIMESTAMP '2025-01-01 10:05:00'),
  (3, 'electronics', 8500, TIMESTAMP '2025-01-01 11:00:00')
;
INSERT INTO iceberg_db.orders
VALUES
  (4, 'electronics', 9000, TIMESTAMP '2025-01-01 11:05:00'),
  (5,       'books', 1000, TIMESTAMP '2025-01-01 12:00:00')
;

これでSELECTしてみると以下のような状態になります。

SELECT * FROM iceberg_db.orders;
+--------+-----------+------+-------------------+
|order_id|category   |amount|ordered_at         |
+--------+-----------+------+-------------------+
|1       |electronics|1500  |2025-01-01 10:00:00|
|2       |electronics|1200  |2025-01-01 10:05:00|
|3       |electronics|8500  |2025-01-01 11:00:00|
|5       |books      |1000  |2025-01-01 12:00:00|
|4       |electronics|9000  |2025-01-01 11:05:00|
+--------+-----------+------+-------------------+

実装

準備ができたので実装に入っていきましょう。
今回のゴールは以下のクエリ相当のデータが見られるところまでとします。

SELECT order_id, ordered_at FROM iceberg_db.orders WHERE category = 'electronics' AND amount > 5000;

方針

方針を立てるため、まずは使えるエンドポイントを確認してみましょう。
REST APIの仕様は以下で確認できます。

今後も使う定数を適当に設定して、

ICEBERG_ENDPOINT = 'Dockerで立てたIcebergカタログに接続できる値を設定'
STORAGE_ENDPOINT = 'Dockerで立てたMinIOに接続できる値を設定'

/v1/configに対してGETリクエストを送ります。

import requests

response = requests.get(f'{ICEBERG_ENDPOINT}/v1/config')
response.json()

以下の感じで色々返ってくると思います。

{'defaults': {},
 'overrides': {},
 'endpoints': ['POST v1/oauth/tokens',
  'POST https://auth-server.com/token',
  'GET v1/config',
  'GET /v1/{prefix}/namespaces',
  ...

今回の環境だとカタログ側でのpushdown関連(/v1/{prefix}/namespaces/{namespace}/tables/{table}/plan等)が使えないので全部自力でやる必要があります。
以下の手順で進めていくことにします。

  1. メタデータファイルの取得
  2. マニフェストリストの取得
  3. マニフェストファイルの特定
  4. データファイルの特定
  5. 該当データの特定

メタデータファイルの取得

テーブルの内容を取得するため、/v1/{prefix}/namespaces/{namespace}/tables/{table}に対してGETリクエストを送ります。
今回の環境では{prefix}の部分は不要でした。

response = requests.get(f'{ICEBERG_ENDPOINT}/v1/namespaces/iceberg_db/tables/orders')
metadata = response.json()

以下のような値(長いので一部省略)が返ってきます。
メタデータファイルの場所だけでなくその中身もまとめて送られてきます。
metadata-locationとかを見るとわかりますが、MinIOのバケット名はiceberg-warehouseにしています。

{'metadata-location': 's3://iceberg-warehouse/iceberg_db/orders/metadata/00002-d6221b81-6f51-479c-ae59-9de284062ac8.metadata.json',
 'metadata': {'format-version': 2,
  'table-uuid': '93a310a9-28b9-4922-8c86-7ba72390d3d5',
  'location': 's3://iceberg-warehouse/iceberg_db/orders',
  'last-sequence-number': 2,
  'last-updated-ms': 1765880456874,
  'last-column-id': 4,
  'current-schema-id': 0,
  'schemas': [{'type': 'struct',
    'schema-id': 0,
    'fields': [{'id': 1, 'name': 'order_id', 'required': False, 'type': 'int'},
     {'id': 2, 'name': 'category', 'required': False, 'type': 'string'},
     {'id': 3, 'name': 'amount', 'required': False, 'type': 'long'},
     {'id': 4,
      'name': 'ordered_at',
      'required': False,
      'type': 'timestamptz'}]}],
  'default-spec-id': 0,
  'partition-specs': [{'spec-id': 0,
    'fields': [{'name': 'category',
      'transform': 'identity',
      'source-id': 2,
      'field-id': 1000}]}],
  'last-partition-id': 1000,
  'default-sort-order-id': 0,
  'sort-orders': [{'order-id': 0, 'fields': []}],
  'properties': {'owner': 'www', 'write.parquet.compression-codec': 'zstd'},
  'current-snapshot-id': 2054114450535991964,
  'refs': {'main': {'snapshot-id': 2054114450535991964, 'type': 'branch'}},
  'snapshots': [{'sequence-number': 1, ...},
   {'sequence-number': 2,
    'snapshot-id': 2054114450535991964,
    'parent-snapshot-id': 516998103003569791,
    'timestamp-ms': 1765880456874,
    'summary': {'operation': 'append',
     'spark.app.id': 'local-1761807475664',
     'added-data-files': '2',
     'added-records': '2',
     'added-files-size': '2556',
     'changed-partition-count': '2',
     'total-records': '5',
     'total-files-size': '3937',
     'total-data-files': '3',
     'total-delete-files': '0',
     'total-position-deletes': '0',
     'total-equality-deletes': '0',
     'engine-version': '3.5.5',
     'app-id': 'local-1761807475664',
     'engine-name': 'spark',
     'iceberg-version': 'Apache Iceberg 1.9.1 (commit f40208ae6fb2f33e578c2637d3dea1db18739f31)'},
    'manifest-list': 's3://iceberg-warehouse/iceberg_db/orders/metadata/snap-2054114450535991964-1-2031965e-0a65-4d4d-8a5c-4af8aa9d8d99.avro',
    'schema-id': 0}],
  'statistics': [],
  'partition-statistics': [],
  'snapshot-log': [...],
  'metadata-log': [...]}}

マニフェストリストの取得

メタデータから現在のスナップショットID、各スナップショットIDに対応するマニフェストリストの場所がわかります。

current_snapshot_id = metadata['metadata']['current-snapshot-id']
current_manifest_list = next((s['manifest-list'] for s in metadata['metadata']['snapshots'] if s['snapshot-id'] == current_snapshot_id), None)

場所がわかったらマニフェストリストを取得します。
S3のシークレットはDockerコンテナ起動時に設定したものを使います。

import boto3

bucket, key = current_manifest_list.removeprefix('s3://').split('/', 1)

s3 = boto3.client('s3', endpoint_url=STORAGE_ENDPOINT, aws_access_key_id='admin', aws_secret_access_key='password', region_name='us-east-1')
manifest_list_content = s3.get_object(Bucket=bucket, Key=key)['Body'].read()

取得したマニフェストリストファイルはAvro形式になっておりそのまま表示しても読めないので、いい感じに処理します。

import io
from avro.datafile import DataFileReader
from avro.io import DatumReader

with DataFileReader(io.BytesIO(manifest_list_content), DatumReader()) as reader:
    manifests = [r for r in reader]

中身が取れてそうです。

[{'manifest_path': 's3://iceberg-warehouse/iceberg_db/orders/metadata/2031965e-0a65-4d4d-8a5c-4af8aa9d8d99-m0.avro',
  'manifest_length': 7468,
  'partition_spec_id': 0,
  'content': 0,
  'sequence_number': 2,
  'min_sequence_number': 2,
  'added_snapshot_id': 2054114450535991964,
  'added_files_count': 2,
  'existing_files_count': 0,
  'deleted_files_count': 0,
  'added_rows_count': 2,
  'existing_rows_count': 0,
  'deleted_rows_count': 0,
  'partitions': [{'contains_null': False,
    'contains_nan': False,
    'lower_bound': b'books',
    'upper_bound': b'electronics'}],
  'key_metadata': None},
 {'manifest_path': 's3://iceberg-warehouse/iceberg_db/orders/metadata/71c20e66-2fc1-4ed0-b6ef-58ebfa5fe9e0-m0.avro',
  'manifest_length': 7431,
  'partition_spec_id': 0,
  'content': 0,
  'sequence_number': 1,
  'min_sequence_number': 1,
  'added_snapshot_id': 516998103003569791,
  'added_files_count': 1,
  'existing_files_count': 0,
  'deleted_files_count': 0,
  'added_rows_count': 3,
  'existing_rows_count': 0,
  'deleted_rows_count': 0,
  'partitions': [{'contains_null': False,
    'contains_nan': False,
    'lower_bound': b'electronics',
    'upper_bound': b'electronics'}],
  'key_metadata': None}]

マニフェストファイルの特定

マニフェストの情報が2つ取れましたが、それぞれ今回のSELECT内容に関係あるのかを確認しましょう。
パーティションの上限・下限が情報として含まれているのでこれを使えば絞り込めそうです。
今回はWHERE句に指定した条件がcategory = 'electronics'とamount > 5000なので、それぞれの条件について以下を判定すれば良さそうです。

conditions = [
  ('category', '=', 'electronics'),
  ('amount', '>', 5000)
]
  1. パーティションカラムについての条件なのか
  2. そのマニフェストファイルに紐づくデータファイルは指定した条件を満たすのか

まずはパーティションカラムの判定を考えます。
マニフェストリストの1つめの要素だけまず見てみると、partition_spec_idがあります。
メタデータのpartition-specs項目がこれと合致するものを持ってくればその時点でのパーティションカラムがわかりそうです。

manifest = manifests[0]
partition_spec_id = manifest['partition_spec_id']
partition_spec = next((s for s in metadata['metadata']['partition-specs'] if s['spec-id'] == partition_spec_id), None)

transform無しのcategoryがパーティションカラムになってることがわかります。

{'spec-id': 0,
 'fields': [{'name': 'category',
   'transform': 'identity',
   'source-id': 2,
   'field-id': 1000}]}

ちょっと雑にやってますがWHEREで指定した内容を満たすのかチェックします。

is_match = True

for col, op, val in conditions:
    partition_index, partition_field = next(((n, p['name']) for n, p in enumerate(partition_spec['fields']) if p['name'] == col), (None, None))
    
    if partition_field is None:
        # パーティションカラムでない場合スキップ
        continue

    partition_stats = manifest['partitions'][partition_index]
    lower_bound = partition_stats['lower_bound'].decode('utf-8')
    upper_bound = partition_stats['upper_bound'].decode('utf-8')
    match op:
        case '=':
            cond_result = (lower_bound <= val <= upper_bound)
        case '>':
            cond_result = (upper_bound > val)
        case '<':
            cond_result = (lower_bound < val)
        case '>=':
            cond_result = (upper_bound >= val)
        case '<=':
            cond_result = (lower_bound <= val)
        case _:
            cond_result = None  # 未対応の演算子

    if not cond_result:
        is_match = False
        break

ここまでは1つのマニフェストに対してだけ検証しましたが、これをそれぞれのマニフェストについて検証すれば良さそうです。

target_manifest_paths = []

for manifest in manifests:
    # 対象のマニフェストかの検証

    if is_match:
        target_manifest_paths.append(manifest['manifest_path'])

今回は2ファイルとも条件を満たしています。

['s3://iceberg-warehouse/iceberg_db/orders/metadata/2031965e-0a65-4d4d-8a5c-4af8aa9d8d99-m0.avro',
 's3://iceberg-warehouse/iceberg_db/orders/metadata/71c20e66-2fc1-4ed0-b6ef-58ebfa5fe9e0-m0.avro']

データファイルの特定

特定したマニフェストファイルの中身を見てみましょう。
今回もとりあえず1ファイルだけ。

target_manifest_path = target_manifest_paths[0]
bucket, key = target_manifest_path.removeprefix('s3://').split('/', 1)

s3 = boto3.client('s3', endpoint_url=STORAGE_ENDPOINT, aws_access_key_id='admin', aws_secret_access_key='password', region_name='us-east-1')
manifest_file_content = s3.get_object(Bucket=bucket, Key=key)['Body'].read()

with DataFileReader(io.BytesIO(manifest_file_content), DatumReader()) as reader:
    manifest_rows = [r for r in reader]

データファイル毎の統計情報が取れます。
ここの情報で絞り込むにはpartition、lower_bounds、upper_boundsあたりが使えそうです。
本当はstatusとかも見るべきなのかもですが簡単にやりたいので見て見ぬふりをします。

[{'status': 1,
  'snapshot_id': 2054114450535991964,
  'sequence_number': None,
  'file_sequence_number': None,
  'data_file': {'content': 0,
   'file_path': 's3://iceberg-warehouse/iceberg_db/orders/data/category=books/00000-289-e27eef8a-5bf1-4cc1-bd6a-d4120cef5900-0-00002.parquet',
   'file_format': 'PARQUET',
   'partition': {'category': 'books'},
   'record_count': 1,
   'file_size_in_bytes': 1257,
   'column_sizes': [{'key': 1, 'value': 39},
    {'key': 2, 'value': 44},
    {'key': 3, 'value': 43},
    {'key': 4, 'value': 43}],
   'value_counts': [{'key': 1, 'value': 1},
    {'key': 2, 'value': 1},
    {'key': 3, 'value': 1},
    {'key': 4, 'value': 1}],
   'null_value_counts': [{'key': 1, 'value': 0},
    {'key': 2, 'value': 0},
    {'key': 3, 'value': 0},
    {'key': 4, 'value': 0}],
   'nan_value_counts': [],
   'lower_bounds': [{'key': 1, 'value': b'\x05\x00\x00\x00'},
    {'key': 2, 'value': b'books'},
    {'key': 3, 'value': b'\xe8\x03\x00\x00\x00\x00\x00\x00'},
    {'key': 4, 'value': b'\x00L\xc7=\x9c*\x06\x00'}],
   'upper_bounds': [{'key': 1, 'value': b'\x05\x00\x00\x00'},
    {'key': 2, 'value': b'books'},
    {'key': 3, 'value': b'\xe8\x03\x00\x00\x00\x00\x00\x00'},
    {'key': 4, 'value': b'\x00L\xc7=\x9c*\x06\x00'}],
   'key_metadata': None,
   'split_offsets': [4],
   'equality_ids': None,
   'sort_order_id': 0,
   'referenced_data_file': None}},
 {'status': 1,
  'snapshot_id': 2054114450535991964,
  'sequence_number': None,
  'file_sequence_number': None,
  'data_file': {'content': 0,
   'file_path': 's3://iceberg-warehouse/iceberg_db/orders/data/category=electronics/00000-289-e27eef8a-5bf1-4cc1-bd6a-d4120cef5900-0-00001.parquet',
   'file_format': 'PARQUET',
   'partition': {'category': 'electronics'},
   'record_count': 1,
   'file_size_in_bytes': 1299,
   'column_sizes': [{'key': 1, 'value': 39},
    {'key': 2, 'value': 50},
    {'key': 3, 'value': 43},
    {'key': 4, 'value': 43}],
   'value_counts': [{'key': 1, 'value': 1},
    {'key': 2, 'value': 1},
    {'key': 3, 'value': 1},
    {'key': 4, 'value': 1}],
   'null_value_counts': [{'key': 1, 'value': 0},
    {'key': 2, 'value': 0},
    {'key': 3, 'value': 0},
    {'key': 4, 'value': 0}],
   'nan_value_counts': [],
   'lower_bounds': [{'key': 1, 'value': b'\x04\x00\x00\x00'},
    {'key': 2, 'value': b'electronics'},
    {'key': 3, 'value': b'(#\x00\x00\x00\x00\x00\x00'},
    {'key': 4, 'value': b'\x00K\x15y\x9b*\x06\x00'}],
   'upper_bounds': [{'key': 1, 'value': b'\x04\x00\x00\x00'},
    {'key': 2, 'value': b'electronics'},
    {'key': 3, 'value': b'(#\x00\x00\x00\x00\x00\x00'},
    {'key': 4, 'value': b'\x00K\x15y\x9b*\x06\x00'}],
   'key_metadata': None,
   'split_offsets': [4],
   'equality_ids': None,
   'sort_order_id': 0,
   'referenced_data_file': None}}]

1ファイルだけ見てみましょう。
まずはパーティションの判定から。

manifest_row = manifest_rows[0]

data_file_stats = ['data_file']
partition = data_file_stats['partition']
is_match = True

for col, op, val in conditions:
    partition_value = partition.get(col)

    if partition_value is None:
        # パーティションカラムでない場合スキップ
        continue
    
    match op:
        case '=':
            cond_result = (partition_value == val)
        case '>':
            cond_result = (partition_value > val)
        case '<':
            cond_result = (partition_value < val)
        case '>=':
            cond_result = (partition_value >= val)
        case '<=':
            cond_result = (partition_value <= val)
        case _:
            cond_result = None  # 未対応の演算子

    if not cond_result:
        is_match = False
        break

データファイルの1つめは{'category': 'books'}のためWHEREの条件を満たさず対象外になります。
2つめは対象になるので、カラムの上限・下限の情報でもう少し絞り込んでみましょう。
{'key': 1, 'value': b'\x04\x00\x00\x00'}のようなカラムのIDを使用した形式で入っているので、メタデータからスキーマ情報を取ってくる必要がありそうです。

current_schema_id = metadata['metadata']['current-schema-id']
current_schema = next((s for s in metadata['metadata']['schemas'] if s['schema-id'] == current_schema_id), None)

カラム名・ID・型の情報が取れました。

{'type': 'struct',
 'schema-id': 0,
 'fields': [{'id': 1, 'name': 'order_id', 'required': False, 'type': 'int'},
  {'id': 2, 'name': 'category', 'required': False, 'type': 'string'},
  {'id': 3, 'name': 'amount', 'required': False, 'type': 'long'},
  {'id': 4, 'name': 'ordered_at', 'required': False, 'type': 'timestamptz'}]}

これを使って判定してみましょう。
上限と下限はbytes型で取れているので、カラムの型に応じて変換してあげてから条件式と比較します。

from datetime import datetime

data_file_stats = manifest_rows[1]['data_file']
lower_bounds = data_file_stats['lower_bounds']
upper_bounds = data_file_stats['upper_bounds']
is_match = True

for col, op, val in conditions:
    field_id, field_type = next(((f['id'], f['type']) for f in current_schema['fields'] if f['name'] == col), (None, None))

    lower_bound_bytes = next((lb['value'] for lb in lower_bounds if lb['key'] == field_id), None)
    upper_bound_bytes = next((ub['value'] for ub in upper_bounds if ub['key'] == field_id), None)
    match field_type:
        case 'int' | 'long':
            lower_bound = int.from_bytes(lower_bound_bytes, byteorder='little')
            upper_bound = int.from_bytes(upper_bound_bytes, byteorder='little')
        case 'string':
            lower_bound = lower_bound_bytes.decode('utf-8')
            upper_bound = upper_bound_bytes.decode('utf-8')
        case 'timestamptz':
            lower_bound = datetime.fromtimestamp(int.from_bytes(lower_bound_bytes, byteorder='little') / 1_000_000)
            upper_bound = datetime.fromtimestamp(int.from_bytes(upper_bound_bytes, byteorder='little') / 1_000_000)
        case _:
            # 未対応のデータ型
            lower_bound = None
            upper_bound = None
        
    match op:
        case '=':
            cond_result = (lower_bound <= val <= upper_bound)
        case '>':
            cond_result = (upper_bound > val)
        case '<':
            cond_result = (lower_bound < val)
        case '>=':
            cond_result = (upper_bound >= val)
        case '<=':
            cond_result = (lower_bound <= val)
        case _:
            cond_result = None  # 未対応の演算子
    if not cond_result:
        is_match = False
        break

今回のWHERE句の内容だとcategory(ID=2、文字列型)とamount(ID=3、数値型)なので、統計情報的には以下が該当します。
どちらのカラムについてもWHERE句の条件を満たしているので、このデータファイルは処理対象となります。

  • 下限
    • {'key': 2, 'value': b'electronics'}(electronics)
    • {'key': 3, 'value': b'(#\x00\x00\x00\x00\x00\x00'}(9000)
  • 上限
    • {'key': 2, 'value': b'electronics'}(electronics)
    • {'key': 3, 'value': b'(#\x00\x00\x00\x00\x00\x00'}(9000)

ここまでの処理も各マニフェストの各データファイルに適用することで処理対象のデータファイルが特定できます。
色々省略してますが以下の感じです。

target_data_file_paths = []

for manifest in manifests:
    # 対象のマニフェストかの検証

    if not is_match:
        continue

    # マニフェストファイルの読み込み

    for manifest_row in manifest_rows:
        data_file_stats = manifest_row['data_file']

        # パーティションでの対象データファイルかの判定

        if not is_match:
            continue

        # カラムの統計情報での対象データファイルかの判定

        if is_match:
            target_data_file_paths.append(data_file_stats['file_path'])

target_data_file_pathsは以下になりました。

['s3://iceberg-warehouse/iceberg_db/orders/data/category=electronics/00000-289-e27eef8a-5bf1-4cc1-bd6a-d4120cef5900-0-00001.parquet',
 's3://iceberg-warehouse/iceberg_db/orders/data/category=electronics/00000-286-1a246983-7318-441a-b64a-b405083d4742-0-00001.parquet']

該当データの特定

Parquetファイルの特定まで行けばここから先はIcebergだけの話があまり多くなさそうなのとだいぶ長くなってしまったのでここからはさらに雑にやらせていただきます。

S3上にあるParquetファイルを読みこんでいきましょう。
s3fsとかを使うと楽 + Parquetの必要な部分だけを読むとかができそうですが、ここまでと同様boto3でゴリ押します。
まずはParquetファイルを開くところまで。

target_data_file_path = target_data_file_paths[0]

import io
import pyarrow.parquet as pq

bucket, key = target_data_file_path.removeprefix('s3://').split('/', 1)

s3 = boto3.client('s3', endpoint_url=STORAGE_ENDPOINT, aws_access_key_id='admin', aws_secret_access_key='password', region_name='us-east-1')
data_file_content = s3.get_object(Bucket=bucket, Key=key)['Body'].read()

f = io.BytesIO(data_file_content)
parquet_file = pq.ParquetFile(f)

データファイルで見られるIceberg的な工夫としてはスキーマ情報をメタデータとして持っていることでしょう。

print(parquet_file.metadata.metadata)
print(parquet_file.schema)

Iceberg側の現在のスキーマIDがわかれば、特定のカラムについてParquet側での対応するカラムもわかるということです。

{b'iceberg.schema': b'{"type":"struct","schema-id":0,"fields":[{"id":1,"name":"order_id","required":true,"type":"int"},{"id":2,"name":"category","required":true,"type":"string"},{"id":3,"name":"amount","required":true,"type":"long"},{"id":4,"name":"ordered_at","required":true,"type":"timestamptz"}]}'}
<pyarrow._parquet.ParquetSchema object at 0x141be99c0>
required group field_id=-1 table {
  required int32 field_id=1 order_id;
  required binary field_id=2 category (String);
  required int64 field_id=3 amount;
  required int64 field_id=4 ordered_at (Timestamp(isAdjustedToUTC=true, timeUnit=microseconds, is_from_converted_type=false, force_set_converted_type=false));
}

とはいえサクッとやっちゃいます。
これで特定のファイルでの対象レコードが取れます。

import pyarrow.compute as pc

target_cols = ['order_id', 'ordered_at', 'amount']
tbl = parquet_file.read(columns=target_cols)

filtered = tbl.filter(pc.field('amount') > 5000)

result = filtered.select(['order_id', 'ordered_at'])

ということで全データファイルに対してこれを実行。

import io
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq

tables = []

for target_data_file_path in target_data_file_paths:
    # Parquetファイルの読み込み

    # 結果テーブルの取得

    tables.append(result)

final_table = pa.concat_tables(tables)

無事に出ました!

   order_id                ordered_at
0         4 2025-01-01 02:05:00+00:00
1         3 2025-01-01 02:00:00+00:00

まとめ

だいぶ長くなってしまいましたが読んでいただきありがとうございます。
最後の方で急に雑になってすいません。
Icebergのメタデータ層と少し仲良くなれた気がしていますし、Parquetファイルの理解もちょっと深まりました。
実際にはここに集計やらJOINやら、更にはタイムトラベルとかも入ってくるので想像するだけで気が遠くなります。
気力があればSELECT以外もやりたいと思ってこのタイトルにしてますがあまり期待しないでください。
巨人の肩には乗ったほうがいいということが学べ、SparkやTrinoへの感謝もより深まったのでいい経験になりました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?