このガイドでは、一般的な状況で PyMongoArrow スキーマを使用する方法の例を示します。
スキーマでネストされたデータ
集計操作または検索操作を実行するときに、 structオブジェクトを使用してネストされたデータのスキーマを提供できます。 サブドキュメントには、親ドキュメントと比較して名前が競合する場合があります。
>>> from pymongo import MongoClient... from pymongoarrow.api import Schema, find_arrow_all... from pyarrow import struct, field, int32... coll = MongoClient().db.coll... coll.insert_many(... [... {"start": "string", "prop": {"name": "foo", "start": 0}},... {"start": "string", "prop": {"name": "bar", "start": 10}},... ]... )... arrow_table = find_arrow_all(... coll, {}, schema=Schema({"start": str, "prop": struct([field("start", int32())])})... )... print(arrow_table)pyarrow.Tablestart: stringprop: struct<start: int32> child 0, start: int32----start: [["string","string"]]prop: [ -- is_valid: all not null -- child 0 type: int32[0,10]]Pandoras と NumPy を使用している場合でも、同じことができます。
>>> df = find_pandas_all(... coll, {}, schema=Schema({"start": str, "prop": struct([field("start", int32())])})... )... print(df) start prop0 string {'start': 0}1 string {'start': 10}プロジェクションを含むネストされたデータ
PyMongoArrow に渡す前に、プロジェクションを使用してデータをフラット化することもできます。 次の例えでは、非常に単純なネストされたドキュメント構造を使用してこれを行う方法を示しています。
>>> df = find_pandas_all(... coll,... {... "prop.start": {... "$gte": 0,... "$lte": 10,... }... },... projection={"propName": "$prop.name", "propStart": "$prop.start"},... schema=Schema({"_id": ObjectIdType(), "propStart": int, "propName": str}),... )... print(df) _id propStart propName0 b'c\xec2\x98R(\xc9\x1e@#\xcc\xbb' 0 foo1 b'c\xec2\x98R(\xc9\x1e@#\xcc\xbc' 10 bar集計操作を実行する際には、次の例に示すように、 $projectステージを使用してフィールドをフラット化できます。
>>> df = aggregate_pandas_all(... coll,... pipeline=[... {"$match": {"prop.start": {"$gte": 0, "$lte": 10}}},... {... "$project": {... "propStart": "$prop.start",... "propName": "$prop.name",... }... },... ],... )