Python OSDK

This page provides generic documentation for the Python OSDK, based on an Example Restaurant object type. You can generate documentation specific to your Ontology in Developer Console.

The Example Restaurant object type has the following properties:

PropertyAPI nameType
restaurant id (primary key)restaurantIdString
restaurant name (title)restaurantNameString
addressaddressString
e maileMailString
number of reviewsnumberOfReviewsInteger
phone numberphoneNumberString
review summaryreviewSummaryString

On this page

SectionWhat it covers
PrerequisitesInstalling your SDK and creating a client.
Load single restaurantFetching one object by primary key.
Access object RIDReading the RID of a loaded object with include_rid=True.
Load pages of example restaurantsPaging with page_size and page_token.
Load all example restaurantsIterating over every object.
Load ordered resultsSorting with order_by, asc, and desc.
FilteringNarrowing an object set with where, and the nine available search filters.
AggregationsComputing summary statistics, and the three available aggregation functions.
Types of group bysGrouping aggregation results.

Prerequisites

Every example on this page assumes a client variable that is already connected to your Ontology, and a generated object class such as ExampleRestaurant. How you create the client depends on where your code runs.

Inside Foundry

In a Foundry Python function, a Code Workspaces notebook, or a model adapter, the runtime supplies the hostname and credentials, so the constructor takes no arguments:

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

In a standalone Python application

Install your SDK using the values shown on your application Overview page in Developer Console, replacing each < > placeholder with your own value. The Python OSDK supports Python versions 3.10 through 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>"

Then create the client with user token authentication:

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>")

For the full walkthrough, including certificate setup and troubleshooting, see Bootstrap a new OSDK Python application. For a backend service that authenticates as an application rather than as a user, see Use the Ontology SDK with compute modules.

Verify your setup

Using the client you created for your environment, confirm that it works before running any other example on this page:

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

In these examples, ontology_sdk is the generated package name for your Developer Console application, and ExampleRestaurant is a class generated from one of your object types. Substitute both for your own values. Your package name is shown on your application Overview page.

The examples on this page target Python OSDK 2.x. If you are upgrading from 1.x, see the Python OSDK migration guide for the syntax changes, including the required .object_type accessor. Version-specific documentation is also available in-platform in the Developer Console at /workspace/developer-console/.

Load single restaurant

Parameters:

  • primaryKey string: The primary key of the Example Restaurant object you want to fetch.

Example query:

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

Example API response:

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" }

Access object RID

By default, the object RID is not included as an accessible attribute on loaded objects. To access an object's RID programmatically, pass include_rid=True to your loading method:

Copied!
1 2 3 # Load a single object with RID access result = client.ontology.objects.ExampleRestaurant.get("primaryKey", include_rid=True) object_rid = result.rid

The include_rid=True parameter can be used with other loading methods as well:

Copied!
1 2 3 4 5 6 7 8 # Iterate with RID access for restaurant in client.ontology.objects.ExampleRestaurant.iterate(include_rid=True): print(restaurant.rid) # Page with RID access result = client.ontology.objects.ExampleRestaurant.page(page_size=30, include_rid=True) for restaurant in result.data: print(restaurant.rid)

Load pages of example restaurants

Load a list of objects of a requested page size, after a given page token if present.

This endpoint uses the underlying object syncing technology of the object type. If the Example Restaurant object type is backed by Object Storage v2, there is no request limit. If it is backed by Object Storage v1 (Phonograph), there is a limit of 10,000 results: requesting more than 10,000 Example Restaurant objects returns an ObjectsExceededLimit error.

Parameters:

  • pageSize integer (optional): The size of the page to request, up to a maximum of 10,000. If not provided, the request loads up to 10,000 Example Restaurant objects. Subsequent pages use the pageSize of the initial page.
  • pageToken string (optional): If provided, requests a page with a size less than or equal to the pageSize of the first requested page.

Example query:

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

Example API response:

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" } // ... Rest of page ] }

Load all example restaurants

Loads all Example Restaurant objects. In Python, iterate() returns an iterator. Wrap it in list(...) to collect every result, or use take(n) to fetch a fixed number of objects as a list.

This endpoint uses the underlying object syncing technology of the object type. If the Example Restaurant object type is backed by Object Storage v2, there is no request limit. If it is backed by Object Storage v1 (Phonograph), there is a limit of 10,000 results: requesting more than 10,000 Example Restaurant objects returns an ObjectsExceededLimit error.

Example query:

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

Example API response:

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" } // ... Rest of data ] }

Load ordered results

Load an ordered list of Example Restaurant objects by specifying a sort direction for specific properties. When calling via APIs, you specify sorting criteria in the fields array. When calling via SDKs, you can chain multiple order_by calls together. The sort order for strings is case-sensitive, meaning that numbers come before uppercase letters, which come before lowercase letters. For example, Cat comes before bat.

Parameters:

  • field string: The property you want to sort by. With the SDK, reference it as ExampleRestaurant.object_type.<property>.
  • direction asc | desc: The direction you want to sort in, either ascending or descending. With the SDK, use the asc() and desc() methods on the property accessor.

Example query:

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() )

In this example, ~ negates the filter that follows it, so ~ExampleRestaurant.object_type.restaurant_name.is_null() matches only the objects that have a restaurant name value. For the other Boolean operators available on filters, see Not filter, And filter, and Or filter.

Example API response:

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" // ...Rest of properties }, { "__rid": "ri.phonograph2-objects.main.object.00000000-0000-0000-0000-000000000000", "__primaryKey": "Object B", "restaurantName": "B" // ...Rest of properties } // ...Rest of page ] }

Filtering

The types of filtering you can perform depend on the types of the properties on a given object type. You can also combine these filters with Boolean expressions to construct more complex filters.

This endpoint uses the underlying object syncing technology of the object type. If the Example Restaurant object type is backed by Object Storage v2, there is no request limit. If it is backed by Object Storage v1 (Phonograph), there is a limit of 10,000 results: requesting more than 10,000 Example Restaurant objects returns an ObjectsExceededLimit error.

Parameters:

  • where SearchQuery (optional): Filter on a particular property. The possible operations depend on the type of the property.
  • orderBy OrderByQuery (optional): Order the results based on a particular property. If using the SDK, you can chain the .where call with an .order_by call to achieve the same result.
  • pageSize integer (optional): The size of the page to request, up to a maximum of 10,000. If not provided, the request loads up to 10,000 Example Restaurant objects. Subsequent pages use the pageSize of the initial page. If using the SDK, chain the .where call with the .page method and pass the page_size keyword argument.
  • pageToken string (optional): If provided, requests a page with a size less than or equal to the pageSize of the first requested page. If using the SDK, chain the .where call with the .page method and pass the page_token keyword argument.

Example query:

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

Example API response:

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 // ... Rest of properties } // ... Rest of page ] }

Types of search filters (SearchQuery)

The following filters are available, depending on the type of the property you filter on:

Contains any terms

Only applies to String properties. Returns Example Restaurant objects where restaurantName contains any of the whitespace-separated words (case-insensitive) in any order in the provided value.

Parameters:

  • field string: Name of the property to use (for example, restaurantName).
  • value string: Whitespace-separated set of words to match on. For example, foo bar matches bar baz but not baz qux.
  • fuzzy boolean: Allows approximate matching in search queries.

Example query:

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']))

Example API response:

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" // ... Rest of properties }, { "__rid": "ri.phonograph2-objects.main.object.00000000-0000-0000-0000-000000000001", "restaurantName": "bar baz" // ... Rest of properties } ] }

Contains all terms

Only applies to String properties. Returns Example Restaurant objects where restaurantName contains all the whitespace-separated words (case-insensitive) in any order in the provided value.

Parameters:

  • field string: Name of the property to use (for example, restaurantName).
  • value string: Whitespace-separated set of words to match on. For example, foo bar matches hello foo baz bar but not foo qux.
  • fuzzy boolean: Allows approximate matching in search queries.

Example query:

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']))

Example API response:

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" // ... Rest of properties } ] }

Contains all terms in order

Only applies to String properties. Returns Example Restaurant objects where restaurantName contains all the terms (case-insensitive) in the order provided and adjacent to each other.

Parameters:

  • field string: Name of the property to use (for example, restaurantName).
  • value string: Whitespace-separated set of words to match on. For example, foo bar matches hello foo bar baz but not bar foo qux.
  • prefix_last_term boolean: Set to True to match the final term as a prefix rather than as a whole word. Defaults to False.

Example query:

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))

Example API response:

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" // ... Rest of properties } ] }

Range comparison

Only applies to Numeric, String, and DateTime properties. Returns Example Restaurant objects where ExampleRestaurant.object_type.restaurant_name is less than a value.

Parameters:

  • field string: Name of the property to use (for example, restaurantName).
  • value string: Value to compare restaurant name to.

Comparison types:

  • Less than <
  • Greater than >
  • Less than or equal to <=
  • Greater than or equal to >=

Example query:

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")

Equal to

Only applies to Boolean, DateTime, Numeric, and String properties. Searches for Example Restaurant objects where restaurantName equals the given value.

Parameters:

  • field string: Name of the property to use (for example, restaurantName).
  • value string: Value to check restaurant name against for equality.

Example query:

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")

Example API response:

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" // ... Rest of properties } ] }

Null check

Only applies to Array, Boolean, DateTime, Numeric, and String properties. Searches for Example Restaurant objects based on whether a value for restaurantName exists.

Parameters:

  • field string: Name of the property to use (for example, restaurantName).
  • value boolean: Whether restaurant name exists. In the Python SDK, is_null() takes no arguments. To find objects where the property is set, negate the filter with ~, as in ~ExampleRestaurant.object_type.restaurant_name.is_null().

Example query:

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 filter

Returns Example Restaurant objects where the query is not satisfied. This can be further combined with other Boolean filter operations.

Parameters:

  • value SearchQuery: The search query to invert.

Example query:

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 filter

Returns Example Restaurant objects where all queries are satisfied. This can be further combined with other Boolean filter operations.

Parameters:

  • value SearchQuery[]: The set of search queries to and together.

Example query:

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 filter

Returns Example Restaurant objects where any of the specified queries are satisfied. This can be further combined with other Boolean filter operations.

Parameters:

  • value SearchQuery[]: The set of search queries to or together.

Example query:

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>') )

Aggregations

Perform aggregations on Example Restaurant objects.

Parameters:

  • aggregation Aggregation[] (optional): Set of aggregation functions to perform. With the SDK, you can chain aggregation computations together with further searches using .where.
  • groupBy GroupBy[] (optional): A set of groupings to create for aggregation results. If using the SDK, chain a .group_by call.
  • where SearchQuery (optional): Filter on a particular property. The possible operations depend on the type of the property.

Example query:

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() )

Example API response:

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

Types of aggregations (Aggregation)

The following aggregation functions are available:

Approximate distinct

Computes an approximate number of distinct values for restaurantName.

Parameters:

  • field string: Name of the property to use (for example, restaurantName).
  • name string (optional): Alias for the computed count. By default, this is distinctCount.

Example query:

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 = ( # This is equivalent to the previous example, but uses metric_name # as the name instead of the default distinctCount. client.ontology.objects.ExampleRestaurant .aggregate( {"metric_name": ExampleRestaurant.object_type.restaurant_name.approximate_distinct()} ) .compute() )

Example API response:

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

Count

Computes the total count of Example Restaurant objects.

Parameters:

  • name string (optional): Alias for the computed count. By default, this is count.

Example query:

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

Example API response:

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

Numeric aggregations

Only applies to numeric properties. Calculate the maximum, minimum, sum, or average of a numeric property for Example Restaurant objects.

Parameters:

  • field string: Name of the property to use (for example, numberOfReviews).
  • name string (optional): An alias for the computed value. By default, this is avg.

Aggregation types:

  • Average: avg()
  • Maximum: max()
  • Minimum: min()
  • Sum: sum()

Example query:

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 = ( # This is equivalent to the previous example, but uses metric_name # as the name instead of the default avg. client.ontology.objects.ExampleRestaurant .aggregate( {"metric_name": ExampleRestaurant.object_type.number_of_reviews.avg()} ) .compute() )

Example API response:

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

Types of group bys (GroupBy)

You can group aggregation results by the exact values of a property.

Exact grouping

Groups Example Restaurant objects by exact values of restaurantName.

Parameters:

  • field string: Name of the property to use (for example, restaurantName).
  • maxGroupCount integer (optional): Maximum number of groupings of restaurantName to create. If using the SDK, pass this to the exact method.

Example query:

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() )

Example API response:

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

Group by linked object properties

For a many-to-one relationship, use with_properties to materialize the linked object's derived property. Then, group by the materialized property.

The following example sums the number of reviews for Example Restaurants, grouped by a property on a linked object. Replace linked_object and linked_property with the link and property names from your own Ontology:

Derived properties are a beta feature. To use with_properties and the derived accessor, run your code inside the AllowBetaFeatures context described in Beta features.

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() )

Key steps:

  1. Use with_properties to add a property by pulling it from a linked object via the derived accessor.
  2. Filter out rows where the property is null.
  3. Use the property as the grouping key in group_by, then aggregate.