Singdata Lakehouse へのデータ取り込み完全ガイド

データ取り込み:ZettaPark の SAVE_AS_TABLE でデータを読み込む

概要

ユースケース

SAVE_AS_TABLE メソッドは、テーブルを自動で作成します。手動でテーブルを作成する必要がある ZettaPark の SQL INSERT に比べて、データの読み込み手順が簡単になります。また、SAVE_AS_TABLE は INSERT INTO を自動で最適化し、レコードを 1 件ずつではなく、一度に複数件挿入します。

実装手順

お使いのコンピューターで VS Code を開き、py_zettapark_save_as_table.py という名前のファイルを作成します。以下のコードを py_zettapark_save_as_table.py にコピーします。

import json import gzip from clickzetta.zettapark.session import Session from datetime import datetime

設定ファイルからパラメーターを読み込みます。

with open('config-ingest.json', 'r') as config_file: config = json.load(config_file) print("Connecting to Singdata Lakehouse.....\n")

セッションを作成します。

session = Session.builder.configs(config).create() print("Connection successful!...\n") target_table_name = "lift_tuckets_import_by_py_save_as_table" def save_as_table_to_clickzetta(session, schema, data): print('Saving data to Singdata Lakehouse') # Convert data to dataframe df = session.create_dataframe(data, schema=schema) # Save dataframe as table df.write.save_as_table(target_table_name, mode="overwrite", table_type="transient") print(f"Data saved to table {target_table_name}") if __name__ == "__main__": schema = None data = [] # Open the compressed JSON file and read the content with gzip.open('lift_tickets_data.json.gz', 'rt', encoding='utf-8') as file: for message in file: if message.strip(): # Ensure it's not an empty line record = json.loads(message) if 'schema' in record: schema = record['schema'] else: data.append(record) save_as_table_to_clickzetta(session, schema, data) session.close() print("Ingest complete")

VS Code で新しい「ターミナル」を開き、次のコマンドを実行して「環境設定」手順で作成した Python 環境を有効にします。すでに cz-ingest-examples 環境を使用している場合は、この手順を省略します。

conda activate cz-ingest-examples

続けて、同じターミナルで次のコマンドを実行します。

python py_zettapark_save_as_table.py

次のステップ

参考資料

ZettaPark クイックスタート