注: 以下の翻訳の正確性は検証されていません。AIPを利用して英語版の原文から機械的に翻訳されたものです。

Python オントロジー SDK

このページでは、Example Restaurant オブジェクトタイプに基づいて、Python オントロジー SDK の汎用的なドキュメントを提供します。Developer Console でお使いのオントロジー固有のドキュメントを生成できます。

このページの例は、Python オントロジー SDK 2.x を対象としています。1.x からアップグレードする場合は、必須の .object_type アクセサーを含む構文の変更について、Python オントロジー SDK 移行ガイドを参照してください。バージョンごとのドキュメントは、プラットフォーム内の /workspace/developer-console/ にある Developer Console でも利用できます。

Example Restaurant オブジェクトタイプには、次のプロパティがあります。

プロパティAPI名データ型
restaurant id(主キー)restaurantId文字列
restaurant name(タイトル)restaurantName文字列
addressaddress文字列
e maileMail文字列
number of reviewsnumberOfReviewsInteger
phone numberphoneNumber文字列
review summaryreviewSummary文字列

このページの内容

セクション内容
前提条件SDK のインストールと client の作成。
レストランを1件読み込む主キーによる1個のオブジェクトの取得。
オブジェクト RID にアクセスするinclude_rid=True を使用した、読み込み済みオブジェクトの RID の読み取り。
サンプルレストランをページ単位で読み込むpage_size と page_token によるページング。
すべてのサンプルレストランを読み込むすべてのオブジェクトに対する反復処理。
取得オプションプロパティの選択、プロパティ修飾子の適用、オブジェクトメタデータの制御。
並べ替えた結果を読み込むorder_by、asc、desc による並べ替え。
絞り込みwhere によるオブジェクトセットの絞り込みと、利用可能な9種類の検索フィルター。
集計要約統計量の計算と、利用可能な3種類の集計関数。
グループ化の種類集計結果のグループ化。
シナリオをスコープとするクライアントを使用するシナリオの作成、またはシナリオへのアタッチ。

前提条件

このページのすべての例は、お使いのオントロジーにすでに接続されている client 変数と、ExampleRestaurant などの生成済みオブジェクトクラスがあることを前提としています。クライアントの作成方法は、コードを実行する場所によって異なります。

Foundry 内

Foundry の Python 関数、Code Workspaces のノートブック、またはモデルアダプターでは、ランタイムがホスト名と資格情報を指定するため、コンストラクターに引数は不要です。

Copied!
1 2 3 from ontology_sdk import FoundryClient client = FoundryClient()

スタンドアロンの Python アプリケーション内

Developer Console のアプリケーションの概要ページに表示されている値を使用して SDK をインストールし、各 < > プレースホルダーを実際の値に置き換えます。Python オントロジー SDK は、Python バージョン3.10から3.14をサポートしています。

Copied!
1 2 export FOUNDRY_TOKEN=<YOUR-TOKEN-FROM-GETTING-STARTED-PAGE> pip install <YOUR-PACKAGE-NAME> --upgrade --extra-index-url "https://:$FOUNDRY_TOKEN@<INDEX-URL>"

次に、ユーザートークン認証を使用してクライアントを作成します。

Copied!
1 2 3 4 5 6 import os from ontology_sdk import FoundryClient, UserTokenAuth auth = UserTokenAuth(token=os.environ["FOUNDRY_TOKEN"]) client = FoundryClient(auth=auth, hostname="<YOUR-FOUNDRY-URL>")

証明書のセットアップやトラブルシューティングを含む完全なウォークスルーについては、新しいオントロジー SDK Python アプリケーションをセットアップするを参照してください。ユーザーではなくアプリケーションとして認証するバックエンドサービスについては、Compute Module でオントロジー SDK を使用するを参照してください。

セットアップを確認する

お使いの環境用に作成した client を使用し、このページのほかの例を実行する前に、正常に動作することを確認してください。

Copied!
1 2 restaurants = client.ontology.objects.ExampleRestaurant.take(1) print(restaurants)

これらの例では、ontology_sdk は Developer Console アプリケーション用に生成されたパッケージ名、ExampleRestaurant はオブジェクトタイプの1つから生成されたクラスです。両方を実際の値に置き換えます。パッケージ名は、アプリケーションの概要ページに表示されます。

レストランを1件読み込む

パラメーター:

  • primaryKey string:取得する Example Restaurant オブジェクトの主キー。

クエリの例:

Copied!
1 result = client.ontology.objects.ExampleRestaurant.get("primaryKey")

API レスポンスの例:

Copied!
1 2 3 4 5 6 7 8 9 10 11 { "__rid": "ri.phonograph2-objects.main.object.00000000-0000-0000-0000-000000000000", "__primaryKey": "Restaurant Id", "eMail": "E Mail", "restaurantId": "Restaurant Id", "address": "Address", "reviewSummary": "Review Summary", "phoneNumber": "Phone Number", "numberOfReviews": 123, "restaurantName": "Restaurant Name" }

オブジェクト RID にアクセスする

デフォルトでは、読み込まれたオブジェクトに、アクセス可能な属性としてオブジェクト RID は含まれません。オブジェクトの RID にプログラムからアクセスするには、読み込みメソッドに include_rid=True を渡します。

Copied!
1 2 3 # RID にアクセスできるようにして1個のオブジェクトを読み込みます result = client.ontology.objects.ExampleRestaurant.get("primaryKey", include_rid=True) object_rid = result.rid

include_rid=True パラメーターは、ほかの読み込みメソッドでも使用できます。

Copied!
1 2 3 4 5 6 7 8 # RID にアクセスできるようにして反復処理します for restaurant in client.ontology.objects.ExampleRestaurant.iterate(include_rid=True): print(restaurant.rid) # RID にアクセスできるようにしてページを取得します result = client.ontology.objects.ExampleRestaurant.page(page_size=30, include_rid=True) for restaurant in result.data: print(restaurant.rid)

サンプルレストランをページ単位で読み込む

指定したページサイズのオブジェクトのリストを読み込みます。ページトークンが指定されている場合は、そのトークンの後から読み込みます。

このエンドポイントは、オブジェクトタイプの基盤となるオブジェクト同期技術を使用します。Example Restaurant オブジェクトタイプが Object Storage v2 を使用している場合、リクエストの制限はありません。Object Storage v1 (Phonograph) を使用している場合、結果は10,000件に制限されます。10,000個を超える Example Restaurant オブジェクトをリクエストすると、ObjectsExceededLimit エラーが返されます。

パラメーター:

  • pageSize integer(任意):リクエストするページのサイズ。最大10,000です。値を指定しない場合は、リクエストによって最大10,000個の Example Restaurant オブジェクトが読み込まれます。後続のページには、最初のページの pageSize が使用されます。
  • pageToken string(任意):指定した場合、最初にリクエストしたページの pageSize 以下のサイズのページをリクエストします。

クエリの例:

Copied!
1 2 3 result = client.ontology.objects.ExampleRestaurant.page(page_size=30, page_token=None) page_token = result.next_page_token data = result.data

API レスポンスの例:

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 { "nextPageToken": "v1.000000000000000000000000000000000000000000000000000000000000000000000000", "data": [ { "__rid": "ri.phonograph2-objects.main.object.00000000-0000-0000-0000-000000000000", "__primaryKey": "Restaurant Id", "eMail": "E Mail", "restaurantId": "Restaurant Id", "address": "Address", "reviewSummary": "Review Summary", "phoneNumber": "Phone Number", "numberOfReviews": 123, "restaurantName": "Restaurant Name" } // ... ページの残り ] }

すべてのサンプルレストランを読み込む

すべての Example Restaurant オブジェクトを読み込みます。Python では、iterate() はイテレーターを返します。すべての結果を収集するには list(...) で囲み、固定数のオブジェクトをリストとして取得するには take(n) を使用します。

このエンドポイントは、オブジェクトタイプの基盤となるオブジェクト同期技術を使用します。Example Restaurant オブジェクトタイプが Object Storage v2 を使用している場合、リクエストの制限はありません。Object Storage v1 (Phonograph) を使用している場合、結果は10,000件に制限されます。10,000個を超える Example Restaurant オブジェクトをリクエストすると、ObjectsExceededLimit エラーが返されます。

クエリの例:

Copied!
1 2 objects_iterator = client.ontology.objects.ExampleRestaurant.iterate() objects = list(objects_iterator)

API レスポンスの例:

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 { "data": [ { "__rid": "ri.phonograph2-objects.main.object.00000000-0000-0000-0000-000000000000", "__primaryKey": "Restaurant Id", "eMail": "E Mail", "restaurantId": "Restaurant Id", "address": "Address", "reviewSummary": "Review Summary", "phoneNumber": "Phone Number", "numberOfReviews": 123, "restaurantName": "Restaurant Name" } // ... データの残り ] }

取得オプション

Python オントロジー SDK の読み込みメソッドは、返されるプロパティとオブジェクトのメタデータを制御するパラメーターを受け取ります。以下のテーブルは同期メソッドの一覧です。対応する非同期メソッドも同じパラメーターを受け取ります。

パラメーターサポートされるメソッド説明
propertiesget(), page(), iterate(), take()指定した生成済みプロパティ参照に対応するプロパティのみを返します。
apply_modifiersget(), page(), iterate(), take()設定済みのリデューサーによって選択された値など、特定のプロパティについて異なる表現を返すようリクエストします。
include_ridget(), page(), iterate(), take()返されるオブジェクトの rid 属性に値を設定します。デフォルト値は False です。
load_property_securitiesget(), page(), iterate(), take()返されるオブジェクトのプロパティレベルのセキュリティメタデータを読み込みます。デフォルト値は False です。
load_ontology_defined_derived_propertiesget(), page(), iterate(), take()オントロジーで定義された派生プロパティの読み込みを明示的にリクエストまたは抑制します。
page_sizepage()各ページの最大オブジェクト数を設定します。
page_tokenpage()以前のページイテレーターの next_page_token からページングを再開します。
num_itemstake()返すオブジェクトの最大数を設定します。

プロパティを選択する

返されるプロパティを制限するには、生成済みプロパティ参照を properties パラメーターに渡します。properties を省略すると、オントロジー SDK はそのオブジェクトタイプで通常読み込まれるすべてのプロパティを返します。次の例では、restaurant_id と restaurant_name のみを返します。

Copied!
1 2 3 4 5 6 7 result = client.ontology.objects.ExampleRestaurant.page( page_size=30, properties=[ ExampleRestaurant.object_type.restaurant_id, ExampleRestaurant.object_type.restaurant_name, ], )

配列プロパティを選択すると、Ontology Manager でプロパティリデューサーが設定されている場合でも、リデューサーが適用されていない完全な値が返されます。同じ動作は、ネイティブの派生プロパティとオントロジーで定義された派生プロパティにも適用されます。

プロパティ修飾子を適用する

ベータ版

Python オントロジー SDK のプロパティ修飾子は、開発のベータ版段階にあります。開発が活発に進められている間は、機能が変更される場合があります。

サポート対象のプロパティ設定を持つ生成済みオブジェクトタイプには、それぞれ ApplyModifiers クラスが含まれます。このクラスのインスタンスを apply_modifiers に渡します。生成されたクラスでは、各プロパティに指定できる修飾子が、そのオントロジー設定でサポートされているものに制限されます。

  • "applyReducers": リデューサーが設定された配列プロパティに対して、配列全体ではなく、選択された配列要素を返します。
  • "extractMainValue": メイン値が設定された構造体プロパティに対して、メイン値フィールドのみを返します。
  • "applyReducersAndExtractMainValue": 両方の機能が設定された構造体配列に対して、リデューサーで1個の構造体を選択し、そのメイン値フィールドを返します。

properties も渡す場合は、apply_modifiers で指定したすべてのプロパティを含めます。そうしないと、オントロジー SDK は ValueError を発生させます。

たとえば、Equipment オブジェクトタイプに、null を許容する Date 配列型の maintenance_history プロパティがあり、最新の日付を選択するリデューサーが設定されているとします。apply_modifiers を指定せずにこのプロパティを選択すると、配列全体が返されます。

Copied!
1 2 3 4 5 6 7 8 9 10 11 equipment = client.ontology.objects.Equipment.get( "E-100", properties=[ Equipment.object_type.equipment_id, Equipment.object_type.maintenance_history, ], ) if equipment is not None: # list[date] | None full_maintenance_history = equipment.maintenance_history

リデューサーを適用した表現をリクエストするには、生成された EquipmentApplyModifiers クラスを使用します。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 from ontology_sdk.ontology.objects.equipment import EquipmentApplyModifiers equipment = client.ontology.objects.Equipment.get( "E-100", properties=[ Equipment.object_type.equipment_id, Equipment.object_type.maintenance_history, ], apply_modifiers=EquipmentApplyModifiers( maintenance_history="applyReducers", ), ) if equipment is not None and equipment.modified_properties is not None: # date | None most_recent_maintenance_date = ( equipment.modified_properties.maintenance_history )

修飾子を適用した場合は、modified_properties を通じて変換後の値にアクセスします。通常のプロパティ属性は None になります。この例では、equipment.modified_properties.maintenance_history に、配列全体ではなくリデューサーによって選択された1個の日付が格納されます。修飾子を適用しても、保存されているプロパティデータや派生プロパティのデータは変更されません。完全な値が必要な場合は、修飾子を省略して通常のプロパティ属性を読み取ります。

並べ替えた結果を読み込む

特定のプロパティの並べ替え方向を指定して、並べ替えた Example Restaurant オブジェクトのリストを読み込みます。API 経由で呼び出す場合は、fields 配列で並べ替え条件を指定します。SDK 経由で呼び出す場合は、複数の order_by 呼び出しを連結できます。文字列の並べ替えでは大文字と小文字が区別され、数字、大文字、小文字の順になります。たとえば、Cat は bat より前になります。

パラメーター:

  • field string:並べ替えに使用するプロパティです。SDK では、ExampleRestaurant.object_type.<property> として参照します。
  • direction asc | desc:昇順または降順の並べ替え方向です。SDK では、プロパティアクセサーの asc() メソッドと desc() メソッドを使用します。

クエリの例:

Copied!
1 2 3 4 5 6 7 8 from ontology_sdk.ontology.objects import ExampleRestaurant ordered_restaurants = ( client.ontology.objects.ExampleRestaurant .where(~ExampleRestaurant.object_type.restaurant_name.is_null()) .order_by(ExampleRestaurant.object_type.restaurant_name.asc()) .iterate() )

この例では、~ はその後に続くフィルターを否定するため、~ExampleRestaurant.object_type.restaurant_name.is_null() は restaurant name の値を持つオブジェクトにのみ一致します。フィルターで利用可能なその他のブール演算子については、Not フィルター、And フィルター、Or フィルターを参照してください。

API レスポンスの例:

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 { "nextPageToken": "v1.000000000000000000000000000000000000000000000000000000000000000000000000", "data": [ { "__rid": "ri.phonograph2-objects.main.object.00000000-0000-0000-0000-000000000000", "__primaryKey": "Object A", "restaurantName": "A" // ...残りのプロパティ }, { "__rid": "ri.phonograph2-objects.main.object.00000000-0000-0000-0000-000000000000", "__primaryKey": "Object B", "restaurantName": "B" // ...残りのプロパティ } // ...ページの残り ] }

リンク

リンクの走査には、単一のオブジェクトのインスタンスから開始するか、オブジェクトセットから開始するかに応じて、2つの形式があります。以下の例では、Example Restaurant に多対一の city リンクと一対多の reviews リンクがあることを前提としています。ご自身のオントロジーのリンクAPI名に置き換えてください。

オブジェクトのインスタンスでは、各リンクはリンクAPI名をスネークケースにした名前のメソッドです。一対一または多対一のリンクは、リンクされたオブジェクトまたは None を返します。一対多または多対多のリンクはオブジェクトセットを返すため、すべてのオブジェクトセットメソッドを使用できます。

クエリの例:

Copied!
1 2 3 4 5 6 7 8 restaurant = client.ontology.objects.ExampleRestaurant.get("primaryKey") # 多対一リンクは、リンクされたオブジェクトまたは None を返します。 city = restaurant.city() # 一対多リンクはオブジェクトセットを返します。 for review in restaurant.reviews().iterate(): ...

オブジェクトセットでは、各リンクに対して、リンク先のタイプのオブジェクトセットを返す search_around_<link_name>() メソッドが生成されます。そのため、走査を連結し、フィルターや集計と組み合わせることができます。

クエリの例:

Copied!
1 reviews = client.ontology.objects.ExampleRestaurant.search_around_reviews()

リンクが実行時にしか判明しない場合、search_around() はリンクAPI名を文字列として受け取り、対応する型付きメソッドを呼び出します。リンクが既知の場合は、型付きの search_around_<link_name>() メソッドを優先して使用してください。search_around() は、指定された名前がそのオブジェクトタイプで有効なリンクでない場合、RuntimeError を発生させます。

クエリの例:

Copied!
1 linked = client.ontology.objects.ExampleRestaurant.search_around("reviews")

フィルタリング

実行できるフィルタリングの種類は、指定されたオブジェクトタイプのプロパティのデータ型によって異なります。また、これらのフィルターをブール式で組み合わせて、より複雑なフィルターを構成することもできます。

このエンドポイントは、オブジェクトタイプの基盤となるオブジェクト同期技術を使用します。Example Restaurant オブジェクトタイプが Object Storage v2 を使用している場合、リクエストの制限はありません。Object Storage v1 (Phonograph) を使用している場合、結果は10,000件に制限されます。10,000個を超える Example Restaurant オブジェクトをリクエストすると、ObjectsExceededLimit エラーが返されます。

パラメーター:

  • where SearchQuery(任意):特定のプロパティで絞り込みます。利用可能な操作は、プロパティのデータ型によって異なります。
  • orderBy OrderByQuery(任意):特定のプロパティに基づいて結果を並べ替えます。SDK を使用する場合は、.where 呼び出しに .order_by 呼び出しを連結することで、同じ結果になります。
  • pageSize integer(任意):リクエストするページのサイズで、最大10,000件です。値を指定しない場合は、リクエストによって最大10,000個の Example Restaurant オブジェクトが読み込まれます。後続のページでは、最初のページの pageSize が使用されます。SDK を使用する場合は、.where 呼び出しに .page メソッドを連結し、page_size キーワード引数を渡します。
  • pageToken string(任意):指定した場合、最初にリクエストしたページの pageSize 以下のサイズのページをリクエストします。SDK を使用する場合は、.where 呼び出しに .page メソッドを連結し、page_token キーワード引数を渡します。

クエリの例:

Copied!
1 2 3 4 5 6 7 from ontology_sdk.ontology.objects import ExampleRestaurant result = client.ontology.objects.ExampleRestaurant.where( ExampleRestaurant.object_type.restaurant_name.is_null() ).page(page_size=30) page_token = result.next_page_token data = result.data

API レスポンスの例:

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 { "nextPageToken": "v1.000000000000000000000000000000000000000000000000000000000000000000000000", "data": [ { "__rid": "ri.phonograph2-objects.main.object.00000000-0000-0000-0000-000000000000", "__primaryKey": "Restaurant Id", "restaurantName": null // ... 残りのプロパティ } // ... ページの残り ] }

検索フィルターの種類(SearchQuery)

絞り込みに使用するプロパティのデータ型に応じて、次のフィルターを利用できます。

いずれかの語句を含む

文字列プロパティにのみ適用されます。指定された値に含まれる空白区切りの単語のいずれかを、順序にかかわらず restaurantName に含む Example Restaurant オブジェクトを返します(大文字と小文字は区別されません)。

パラメーター:

  • field string:使用するプロパティの名前(例:restaurantName)。
  • value string:一致させる単語を空白で区切ったものです。たとえば、foo bar は bar baz に一致しますが、baz qux には一致しません。
  • fuzzy boolean:検索クエリで近似一致を許可します。

クエリの例:

Copied!
1 2 3 from ontology_sdk.ontology.objects import ExampleRestaurant example_restaurant_object_set = client.ontology.objects.ExampleRestaurant.where(ExampleRestaurant.object_type.restaurant_name.contains_any_term(['foo bar']))

API レスポンスの例:

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 { "nextPageToken": "v1.000000000000000000000000000000000000000000000000000000000000000000000000", "data": [ { "__rid": "ri.phonograph2-objects.main.object.00000000-0000-0000-0000-000000000000", "__primaryKey": "Restaurant Id", "restaurantName": "foo bar baz" // ... 残りのプロパティ }, { "__rid": "ri.phonograph2-objects.main.object.00000000-0000-0000-0000-000000000001", "restaurantName": "bar baz" // ... 残りのプロパティ } ] }

すべての語句を含む

文字列プロパティにのみ適用されます。指定された値に含まれる空白区切りの単語をすべて、順序にかかわらず restaurantName に含む Example Restaurant オブジェクトを返します(大文字と小文字は区別されません)。

パラメーター:

  • field string:使用するプロパティの名前(例:restaurantName)。
  • value string:一致させる単語を空白で区切ったものです。たとえば、foo bar は hello foo baz bar に一致しますが、foo qux には一致しません。
  • fuzzy boolean:検索クエリで近似一致を許可します。

クエリの例:

Copied!
1 2 3 from ontology_sdk.ontology.objects import ExampleRestaurant example_restaurant_object_set = client.ontology.objects.ExampleRestaurant.where(ExampleRestaurant.object_type.restaurant_name.contains_all_terms(['foo bar']))

API レスポンスの例:

Copied!
1 2 3 4 5 6 7 8 9 10 11 { "nextPageToken": "v1.000000000000000000000000000000000000000000000000000000000000000000000000", "data": [ { "__rid": "ri.phonograph2-objects.main.object.00000000-0000-0000-0000-000000000000", "__primaryKey": "Restaurant Id", "restaurantName": "hello foo baz bar" // ... 残りのプロパティ } ] }

すべての語句を順番に含む

文字列プロパティにのみ適用されます。指定された順序で、すべての語句が互いに隣接する形で restaurantName に含まれる Example Restaurant オブジェクトを返します(大文字と小文字は区別されません)。

パラメーター:

  • field string:使用するプロパティの名前(例:restaurantName)。
  • value string:一致させる単語を空白で区切ったものです。たとえば、foo bar は hello foo bar baz に一致しますが、bar foo qux には一致しません。
  • prefix_last_term boolean:最後の語句を単語全体ではなく接頭辞として一致させるには、True に設定します。デフォルトは False です。

クエリの例:

Copied!
1 2 3 from ontology_sdk.ontology.objects import ExampleRestaurant example_restaurant_object_set = client.ontology.objects.ExampleRestaurant.where(ExampleRestaurant.object_type.restaurant_name.contains_all_terms_in_order(['foo'], prefix_last_term=True))

API レスポンスの例:

Copied!
1 2 3 4 5 6 7 8 9 10 11 { "nextPageToken": "v1.000000000000000000000000000000000000000000000000000000000000000000000000", "data": [ { "__rid": "ri.phonograph2-objects.main.object.00000000-0000-0000-0000-000000000000", "__primaryKey": "Restaurant Id", "restaurantName": "foo bar baz" // ... 残りのプロパティ } ] }

範囲比較

数値、文字列、DateTime プロパティにのみ適用されます。ExampleRestaurant.object_type.restaurant_name が指定の値より小さい Example Restaurant オブジェクトを返します。

パラメーター:

  • field string:使用するプロパティの名前(例:restaurantName)。
  • value string:restaurant name の比較対象となる値。

比較の種類:

  • より小さい <
  • より大きい >
  • 以下 <=
  • 以上 >=

クエリの例:

Copied!
1 2 3 from ontology_sdk.ontology.objects import ExampleRestaurant example_restaurant_object_set = client.ontology.objects.ExampleRestaurant.where(ExampleRestaurant.object_type.restaurant_name < "Restaurant Name")

等しい

ブール値、DateTime、数値、文字列プロパティにのみ適用されます。restaurantName が指定された値と等しい Example Restaurant オブジェクトを検索します。

パラメーター:

  • field string:使用するプロパティの名前(例:restaurantName)。
  • value string:restaurant name と等しいかどうかを確認する値。

クエリの例:

Copied!
1 2 3 from ontology_sdk.ontology.objects import ExampleRestaurant example_restaurant_object_set = client.ontology.objects.ExampleRestaurant.where(ExampleRestaurant.object_type.restaurant_name == "Restaurant Name")

API レスポンスの例:

Copied!
1 2 3 4 5 6 7 8 9 10 11 { "nextPageToken": "v1.000000000000000000000000000000000000000000000000000000000000000000000000", "data": [ { "__rid": "ri.phonograph2-objects.main.object.00000000-0000-0000-0000-000000000000", "__primaryKey": "Restaurant Id", "restaurantName": "Restaurant Name" // ... 残りのプロパティ } ] }

null チェック

配列、ブール値、DateTime、数値、文字列プロパティにのみ適用されます。restaurantName の値が存在するかどうかに基づいて、Example Restaurant オブジェクトを検索します。

パラメーター:

  • field string:使用するプロパティの名前(例:restaurantName)。
  • value boolean:restaurant name が存在するかどうか。Python SDK では、is_null() は引数を取りません。プロパティが設定されているオブジェクトを検索するには、~ExampleRestaurant.object_type.restaurant_name.is_null() のように、~ でフィルターを否定します。

クエリの例:

Copied!
1 2 3 from ontology_sdk.ontology.objects import ExampleRestaurant example_restaurant_object_set = client.ontology.objects.ExampleRestaurant.where(ExampleRestaurant.object_type.restaurant_name.is_null())

Not フィルター

クエリを満たさない Example Restaurant オブジェクトを返します。ほかのブールフィルター操作とさらに組み合わせることができます。

パラメーター:

  • value SearchQuery:反転する検索クエリ。

クエリの例:

Copied!
1 2 3 from ontology_sdk.ontology.objects import ExampleRestaurant example_restaurant_object_set = client.ontology.objects.ExampleRestaurant.where(~ExampleRestaurant.object_type.restaurant_id.is_null())

And フィルター

すべてのクエリを満たす Example Restaurant オブジェクトを返します。ほかのブールフィルター操作とさらに組み合わせることができます。

パラメーター:

  • value SearchQuery[]:and で結合する検索クエリ。

クエリの例:

Copied!
1 2 3 4 5 6 from ontology_sdk.ontology.objects import ExampleRestaurant example_restaurant_object_set = client.ontology.objects.ExampleRestaurant.where( ~ExampleRestaurant.object_type.restaurant_id.is_null() & (ExampleRestaurant.object_type.restaurant_id == '<primaryKey>') )

Or フィルター

指定されたクエリのいずれかを満たす Example Restaurant オブジェクトを返します。ほかのブールフィルター操作とさらに組み合わせることができます。

パラメーター:

  • value SearchQuery[]:or で結合する検索クエリ。

クエリの例:

Copied!
1 2 3 4 5 6 from ontology_sdk.ontology.objects import ExampleRestaurant example_restaurant_object_set = client.ontology.objects.ExampleRestaurant.where( ExampleRestaurant.object_type.restaurant_id.is_null() | (ExampleRestaurant.object_type.restaurant_id == '<primaryKey>') )

集計

Example Restaurant オブジェクトに対して集計を実行します。

パラメーター:

  • aggregation Aggregation[](任意):実行する集計関数。SDK では、.where を使用して集計計算と追加の検索を連結できます。
  • groupBy GroupBy[](任意):集計結果に対して作成するグループ化。SDK を使用する場合は、.group_by 呼び出しを連結します。
  • where SearchQuery(任意):特定のプロパティに対するフィルター。利用可能な操作は、プロパティのデータ型によって異なります。

クエリの例:

Copied!
1 2 3 4 5 6 7 8 9 from ontology_sdk.ontology.objects import ExampleRestaurant num_example_restaurant = ( client.ontology.objects.ExampleRestaurant .where(~ExampleRestaurant.object_type.restaurant_name.is_null()) .group_by(ExampleRestaurant.object_type.restaurant_name.exact()) .count() .compute() )

API レスポンスの例:

{
    excludedItems: 0,
    data: [{
        group: {
            "restaurantName": "Restaurant Name"
        },
        metrics: [
            {
                name: "count",
                value: 100
            }
        ]
    }]
}

集計の種類(Aggregation)

次の集計関数を利用できます。

近似一意数

restaurantName の一意な値の近似数を計算します。

パラメーター:

  • field string:使用するプロパティの名前(例:restaurantName)。
  • name string(任意):計算された件数のエイリアス。デフォルトは distinctCount です。

クエリの例:

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from ontology_sdk.ontology.objects import ExampleRestaurant num_distinct_restaurant_names = ( client.ontology.objects.ExampleRestaurant .approximate_distinct(ExampleRestaurant.object_type.restaurant_name) .compute() ) num_distinct_restaurant_names = ( # これは前の例と同等ですが、名前として metric_name を # デフォルトの distinctCount の代わりに使用します。 client.ontology.objects.ExampleRestaurant .aggregate( {"metric_name": ExampleRestaurant.object_type.restaurant_name.approximate_distinct()} ) .compute() )

API レスポンスの例:

{
    excludedItems: 0,
    data: [{
        group: {},
        metrics: [
            {
                name: "distinctCount",
                value: 100
            }
        ]
    }]
}

件数

Example Restaurant オブジェクトの総件数を計算します。

パラメーター:

  • name string(任意):計算された件数のエイリアス。デフォルトは count です。

クエリの例:

Copied!
1 2 3 4 5 num_example_restaurant = ( client.ontology.objects.ExampleRestaurant .count() .compute() )

API レスポンスの例:

{
    excludedItems: 0,
    data: [{
        group: {},
        metrics: [
            {
                name: "count",
                value: 100
            }
        ]
    }]
}

数値集計

数値型のプロパティにのみ適用されます。Example Restaurant オブジェクトの数値型のプロパティについて、最大値、最小値、合計、または平均を計算します。

パラメーター:

  • field string:使用するプロパティの名前(例:numberOfReviews)。
  • name string(任意):計算された値のエイリアス。デフォルトは avg です。

集計の種類:

  • 平均:avg()
  • 最大値:max()
  • 最小値:min()
  • 合計:sum()

クエリの例:

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from ontology_sdk.ontology.objects import ExampleRestaurant avg_number_of_reviews = ( client.ontology.objects.ExampleRestaurant .avg(ExampleRestaurant.object_type.number_of_reviews) .compute() ) avg_number_of_reviews = ( # これは前の例と同等ですが、名前として metric_name を # デフォルトの avg の代わりに使用します。 client.ontology.objects.ExampleRestaurant .aggregate( {"metric_name": ExampleRestaurant.object_type.number_of_reviews.avg()} ) .compute() )

API レスポンスの例:

{
    excludedItems: 0,
    data: [{
        group: {},
        metrics: [
            {
                name: "avg",
                value: 100
            }
        ]
    }]
}

グループ化の種類(GroupBy)

プロパティの値の完全一致で集計結果をグループ化できます。

完全一致によるグループ化

restaurantName の値の完全一致で Example Restaurant オブジェクトをグループ化します。

パラメーター:

  • field string:使用するプロパティの名前(例:restaurantName)。
  • maxGroupCount integer(任意):作成する restaurantName のグループの最大数。SDK を使用する場合は、これを exact メソッドに渡します。

クエリの例:

Copied!
1 2 3 4 5 6 7 8 from ontology_sdk.ontology.objects import ExampleRestaurant num_example_restaurant = ( client.ontology.objects.ExampleRestaurant .group_by(ExampleRestaurant.object_type.restaurant_name.exact()) .count() .compute() )

API レスポンスの例:

{
    excludedItems: 0,
    data: [{
        group: {
            "restaurantName": "Restaurant Name"
        },
        metrics: [
            {
                name: "count",
                value: 100
            }
        ]
    }]
}

リンクされたオブジェクトのプロパティでグループ化する

多対一の関係では、with_properties を使用して、リンクされたオブジェクトの派生プロパティを実体化します。その後、実体化したプロパティでグループ化します。

次の例では、リンクされたオブジェクトのプロパティでグループ化し、Example Restaurant のレビュー数を合計します。linked_object と linked_property を、ご自身のオントロジーのリンク名とプロパティ名に置き換えます。

派生プロパティはベータ機能です。with_properties と derived アクセサーを使用するには、ベータ機能で説明されている AllowBetaFeatures コンテキスト内でコードを実行してください。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from ontology_sdk.ontology.objects import ExampleRestaurant restaurants = client.ontology.objects.ExampleRestaurant result = ( restaurants.with_properties( linked_property= ExampleRestaurant.object_type.derived.linked_object().linked_property.get() ) .where( ~ExampleRestaurant.object_type.derived.property("linked_property").is_null() ) .group_by( ExampleRestaurant.object_type.derived.property("linked_property").exact() ) .aggregate({"sum": ExampleRestaurant.object_type.number_of_reviews.sum()}) .compute() .to_dict() )

主な手順:

  1. with_properties を使用して、derived アクセサー経由でリンクされたオブジェクトからプロパティを取得し、追加します。
  2. プロパティが null である行を除外します。
  3. group_by のグループ化キーとしてそのプロパティを使用し、集計します。

オントロジーに対するアクション

client.ontology.actions を通じてアクションを適用します。このセクションの例では、action_example や parameter_example などのプレースホルダー名を使用しています。ご自身のオントロジーのAPI名に置き換えてください。

ActionConfig は、アクションの検証、実行、またはその両方を行うかどうか、および結果の編集内容をレスポンスに含めるかどうかを制御します。編集内容を利用する前に、response.validation.result を確認してください。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 from foundry_sdk_runtime.types import ( ActionConfig, ActionMode, ReturnEditsMode, SyncApplyActionResponse ) response: SyncApplyActionResponse = client.ontology.actions.action_example( action_config=ActionConfig( mode=ActionMode.VALIDATE_AND_EXECUTE, return_edits=ReturnEditsMode.ALL), parameter_example="value" ) if response.validation.result == "VALID": ... print(response) # 出力例: # SyncApplyActionResponse( # validation=ValidateActionResponse( # result='VALID', # submission_criteria=[], # parameters={} # ), # edits=ObjectEdits( # type='edits', # edits=[ # AddObject( # primary_key='value', # object_type='ExampleObjectType', # type='addObject' # ) # ], # added_object_count=1, # modified_objects_count=0, # deleted_objects_count=0, # added_links_count=0, # deleted_links_count=0 # ) # )

ValidationResult は Literal であるため、上記のように文字列 "VALID" と比較します。foundry_sdk.v2.ontologies.models からインポートします。

バッチアクションを適用する

client.ontology.batch_actions を通じて、1回の呼び出しで複数のパラメーターセットに同じアクションを適用します。バッチ適用では、すべてが適用されるか、何も適用されないかのいずれかになります。バッチ内のいずれかのアクションが失敗すると、バッチ内の編集はどれも適用されません。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 from foundry_sdk_runtime.types import BatchActionConfig, BatchApplyActionResponse, ReturnEditsMode from ontology_sdk.ontology.action_types import ActionExampleBatchRequest response: BatchApplyActionResponse = client.ontology.batch_actions.action_example( batch_action_config=BatchActionConfig(return_edits=ReturnEditsMode.ALL), requests=[ ActionExampleBatchRequest( parameter_example="value_1" ), ActionExampleBatchRequest( parameter_example="value_2" ) ] ) print(response) # 出力例: # BatchApplyActionResponse( # edits=BatchActionObjectEdits( # type='edits', # edits=[ # AddObject( # primary_key='value_1', # object_type='ExampleObjectType', # type='addObject' # ), # AddObject( # primary_key='value_2', # object_type='ExampleObjectType', # type='addObject' # ) # ], # added_object_count=2, # modified_objects_count=0, # deleted_objects_count=0, # added_links_count=0, # deleted_links_count=0 # ) # )

クエリ

client.ontology.queries を通じて公開済みの関数を実行します。引数はすべてキーワード引数です。戻り値の型は関数の宣言によって異なり、以下の各形式は、生の識別子ではなくインスタンスとして返されます。

オブジェクト出力

Copied!
1 2 3 4 5 result: Object = client.ontology.queries.query_object_output(object_id = 1) print(result) # 出力例: # Object(id = 1)

オブジェクトセット出力

Copied!
1 2 3 4 5 result: ObjectSet = client.ontology.queries.query_object_set_output(object_id = 1) print(result) # 出力例: # ObjectSet(object_set_definition=...)

添付ファイル出力

Copied!
1 2 3 4 5 result: Attachment = client.ontology.queries.query_attachment_output(object_id = 1) print(result) # 出力例: # Attachment(rid="ri.attachments.main.attachment.2c1432f8-0378-45f2-8280-55d858cb71fc")

2次元集計出力

Copied!
1 2 3 4 5 6 7 8 9 10 result: QueryTwoDimensionalAggregation = client.ontology.queries.query_two_dimensional_output() print(result) # 出力例: # QueryTwoDimensionalAggregation( # groups=[ # QueryAggregation(key='1', value=2.0), # QueryAggregation(key='2', value=3.0) # ] # )

3次元集計出力

内側のバケットは、どちらの階層でも groups キーの下に格納されます。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 result: QueryThreeDimensionalAggregation = client.ontology.queries.query_three_dimensional_output() print(result) # 出力例: # QueryThreeDimensionalAggregation( # groups=[ # NestedQueryAggregation( # key='1', # groups=[ # QueryAggregation(key='ABC', value=2.0), # QueryAggregation(key='DEF', value=4.0) # ] # ), # NestedQueryAggregation( # key='2', # groups=[ # QueryAggregation(key='GHI', value=1.0), # QueryAggregation(key='JKL', value=1.0) # ] # ) # ] # )

マップ出力

Copied!
1 2 3 4 5 6 7 8 result: dict[Object, int] = client.ontology.queries.query_map_output(object_id = 1) print(result) # 出力例: # { # Object(id=1): 1, # Object(id=2): 3 # }

添付ファイル

client.ontology.attachments を通じて、ファイルを添付ファイルとしてアップロードします。返される Attachment には、ファイルのメタデータを取得する get_metadata() と、コンテンツを読み取る read() が用意されています。

アップロードされた添付ファイルは一時的なものです

アップロードから1時間以内に、適用されたアクションによってオブジェクトのプロパティに書き込まれなかった添付ファイルは、コンテンツとともに削除されます。添付ファイルを保持するには、返された RID を、添付ファイルプロパティに書き込むアクションに渡してください。添付ファイルがオブジェクトに書き込まれるまでは、アップロードしたユーザーのみが読み取れます。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 result: Attachment = client.ontology.attachments.upload( file_path="file.json", attachment_name="myFile" ) print(result) # Example output: # Attachment(rid=ri.attachments.main.attachment.00000000-0000-0000-0000-000000000000) print(result.get_metadata()) # Example output: # AttachmentMetadata( # rid='ri.attachments.main.attachment.00000000-0000-0000-0000-000000000000', # filename='myFile', # size_bytes=20, # media_type='*/*', # type='single' # ) print(result.read().getvalue()) # Example output: # b'My example file.\n'

オブジェクトのプロパティタイプ

マーキングとベクトルのプロパティはベータ機能です。ベータ機能で説明されている AllowBetaFeatures コンテキスト内で読み取ります。メディアプロパティは、以下に示すように直接読み取ります。

マーキング

マーキングは、適用されたマーキングの条件をすべて満たすユーザーにリソースへのアクセスを制限する、必須のセキュリティ制御を表す文字列です。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 from foundry_sdk_runtime import AllowBetaFeatures from foundry_sdk_runtime.markings import Marking my_object_set = client.ontology.objects.Object with AllowBetaFeatures(): my_object = my_object_set.get(1) print(my_object.marking_property) # 出力例: # Marking("MyMarking")

メディア

メディアプロパティからは、コンテンツ、メタデータ、および Media Reference を取得できます。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 from foundry_sdk_runtime.media import Media my_object_set = client.ontology.objects.Object my_object = my_object_set.get(1) print(my_object.media_property) # 出力例: # Media("media_property") print(my_object.media_property.get_media_content()) # 出力例: # <_io.BytesIO object at 0x106ed32c0> print(my_object.media_property.get_media_metadata()) # 出力例: # MediaMetadata( # path='my_file.png' # size_bytes=1408 # media_type='image/png' # ) print(my_object.media_property.get_media_reference()) # 出力例: # MediaReference( # mime_type='image/png' # reference=MediaSetViewItemWrapper( # media_set_view_item=MediaSetViewItem( # media_set_rid='ri.mio.main.media-set.00000000-0000-0000-0000-000000000000', # media_set_view_rid='ri.mio.main.view.00000000-0000-0000-0000-000000000000', # media_item_rid='ri.mio.main.media-item.00000000-0000-0000-0000-000000000000', # token=None # ), # type='mediaSetViewItem' # ) # )

ベクトル

ベクトルプロパティは Float のリストであり、最近傍フィルターに使用できます。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 from foundry_sdk_runtime import AllowBetaFeatures from foundry_sdk_runtime.vectors import Vector from ontology_sdk.ontology.objects import Object my_object_set = client.ontology.objects.Object with AllowBetaFeatures(): my_object = my_object_set.get( 1, properties=[Object.object_type.vector_property] ) print(my_object.vector_property) # 出力例: # Vector([0.014408838003873825, ..., -0.012173213064670563])

シナリオをスコープとするクライアントを使用する

試験的

オントロジーシナリオのサポートは、開発の試験的段階にあり、お使いのエンロールメントでは利用できない場合があります。開発が活発に進められている間は、機能が変更される場合があります。

オントロジー SDK は、オントロジーシナリオの作成や操作にも使用できます。シナリオを使用すると、メインのオントロジーを変更することなく What-if 分析を作成できます。シナリオをスコープとするクライアントを作成するか、RID を指定して既存のシナリオにアタッチします。Foundry は、このクライアントからの呼び出しを、シナリオの分離されたサンドボックス内で評価します。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 from foundry_sdk_runtime import AllowBetaFeatures from osdk import ScenarioClient with AllowBetaFeatures(): # 新しいシナリオを作成します。これにより、プラットフォームを呼び出してシナリオを生成します。 scenario_client = ScenarioClient.create(client) # または、RID を使って既存のシナリオにアタッチします。 scenario_client = ScenarioClient( client, scenario_rid="ri.actions..scenario.0000-..." ) result = scenario_client.ontology.objects.ExampleRestaurant.get("primaryKey")

シナリオをスコープとするクライアントの追加機能を探索し、バージョン要件を確認するには、オントロジー SDK でシナリオを使用するを参照してください。