Object sets

An object set is a description of a group of objects: every scoop shop on the island, the deliveries that serve the shops running short, the batches made from one silo. You build it from filters, link traversals and derived properties, and nothing runs until you load a page, count it or aggregate it. Every screen, function and agent tool in the platform reads the Ontology this way, through the object query service, with the reader's permissions applied to every row

DefinitionImmutable and lazy. Each method returns a new set
OperationsFilter, follow across links, derive, union, intersect, subtract
TerminalsLoad a page, aggregate, count
Limits3 hops, 1,000 objects per page, 10,000 buckets

In the platform today

Built
  • Object set queries run in the platform service, through POST /api/v2/query, POST /api/v2/query/aggregate and POST /api/v2/types/{type}/objects/search
  • A query names a type or an interface in from, filters it with where, and takes steps: {"follow": "<link type id>"} in either direction, up to 3 hops, {"where": …} and {"derive": {name: expression}} with arithmetic, comparisons and functions such as round, coalesce and date_diff, or a spatial $distance
  • A where after a derive step, or in the same step, filters on the derived names, on object types and interface sets alike; derived values come only from stored properties the caller can read, and a name equal to a readable property is refused (DERIVED_NAME_TAKEN)
  • The reader's access labels, row policy and hidden properties apply at every hop
  • Every filter operator in the table below is built except $overlaps
  • A load takes select, orderBy, pageSize (100 by default, 1,000 at most) and pageToken, and returns objectType, totalCount, data and nextPageToken
  • An aggregate takes group, a list of property names, and measure, {name: {op, property}} with count, sum, avg, min, max or countDistinct
On request
  • Key sets, saved and pinned sets, set algebra, derived values from other derived values, link-aggregation and function-computed derived properties, the index and scan pool, explain, snapshot page tokens and rate limits

The query model

An object set is a tree. The leaves name where objects come from: every object of a type, every object that implements an interface, a fixed list of primary keys, or a saved set. Inner nodes narrow, move or combine. The root is evaluated only when a terminal is called, and the whole tree is planned at once, so the order you write filters in does not change the plan

NodeSDKWhat it produces
frommso.objects(Shop)Every object of the type the reader can see
interfacemso.objects(ColdStorageAsset)Every object of every type implementing the interface, read through the interface's properties
keysmso.objects(Shop).fromKeys([...])Exactly the listed primary keys, up to 10,000 by default and 100,000 on request
filter.where({...})The objects of the input that match the predicate
follow.follow("link")The distinct objects at the other end of a link from any object in the input
derive.derive({...})The same objects with extra, computed properties
union, intersect, subtract.union(other)Set algebra on objects of the same type, by primary key
referenceclient.savedSet("weekend-at-risk")The definition of a saved set, expanded at query time
fromScoop shop filterprovince = NS deriveshort, expression filtershort > 0 tubs followstops loadpage of 50 Each step works on the objects the step before it returned. The filter on the derived shortfall keeps 14 shops, so follow reads the delivery stops of those 14 shops, not of every shop
A filter early in the tree narrows every step after it

Filters

A filter is a predicate over the properties of the set's type. A bare object of property and value means equality, and several keys mean all of them must hold. Operators are explicit and typed, so a filter that compares a temperature to a string fails at compile time in the SDK and with 400 INVALID_ARGUMENT.QUERY_FAILED over HTTP

OperatorApplies toMeaning
$eq, $neAny scalarEqual, not equal. $ne does not match null
$in, $ninAny scalarOne of up to 1,000 values by default, 10,000 on request, or none of them
$lt, $lte, $gt, $gteNumbers, dates, timestamps, stringsRange comparisons. Strings compare by Unicode code point
$missingAny propertytrue for missing values, false for present ones
$has, $hasAllArraysThe array holds the value, or every listed value
$prefixStringsPrefix, ignoring case
$anyWord, $allWords, $phrase, $fuzzySearchable stringsFull-text predicates, described in search
$near, $inBox, $inArea, $overlapsGeopoints and geoshapesSpatial predicates, described in geospatial
$and, $or, $notPredicatesBoolean combinations, nested up to 16 levels

Comparisons never match null. A shop with no recorded freezer temperature is in neither { freezerTemp: { $lt: -20 } } nor { freezerTemp: { $gte: -20 } }. Ask for it with $missing. This rule is deliberate: a missing reading is a different operational fact from a cold freezer

const lateRuns = mso.objects(Delivery).where({
  $and: [
    { status: { $in: ["Scheduled", "In transit", "At risk"] } },
    { eta: { $gt: "2026-10-29T18:00:00-03:00" } },
    { $or: [{ crossing: { $ne: "None" } }, { stops: { $gt: 3 } }] },
    { $not: { carrierCode: { $missing: true } } },
  ],
});

The same set as JSON, which is what the SDK sends and what you write when calling the API directly

{
  "query": {
    "from": "delivery",
    "where": {
      "$and": [
        {"status": {"$in": ["Scheduled", "In transit", "At risk"]}},
        {"eta": {"$gt": "2026-10-29T21:00:00Z"}},
        {"$or": [
          {"crossing": {"$ne": "None"}},
          {"stops": {"$gt": 3}}
        ]},
        {"$not": {"carrierCode": {"$missing": true}}}
      ]
    }
  }
}

Traversing links

follow moves a set across a link type. The result is the distinct set of objects on the other side that are linked to at least one object in the input, so following 14 shops to their delivery stops returns each stop once, and following those stops to deliveries returns each delivery once even if it serves three of the shops. You name the link by its link type ID, from either end. On request, you name it by the ID of the side you start on, which is why every link type has a name for each direction

A query may chain up to 3 hops. Each hop can be filtered, and filters after a hop apply to the new type. The recall question, "where is the product from the batches this check tested", is three hops from a QA test

from mso_client import Client
from ontology_types import Qatest   # python -m mso_client.generate --out ontology_types

client = Client("https://creamery.ontology.marklandstreet.com", token=token)

# Forward trace from a failed quality check to every lot of affected product not yet sold
lots = (
    client.objects(Qatest)
    .where(testNo="QA-7710")
    .follow("tested-batch-test")                     # hop 1: QA test to tested batch
    .follow("tested-batch-batch")                    # hop 2: tested batch to production batch
    .follow("lot-batch")                             # hop 3: production batch to shipped lot
    .where({"status": {"$ne": "Sold through"}})
)
for lot in lots.iterate(page_size=200):
    print(lot.lotNo, lot.placeKind, lot.shopId)

Traversal over a foreign-key link is a lookup on the key property. On request, traversal over a many-to-many link reads the link table

Permissions apply at every hop

A traversal never passes through an object the reader cannot see. If a shops manager cannot see Shipped lot objects, a follow from Reefer delivery through lots to Scoop shop returns nothing for that manager, rather than leaking the shops the hidden lots would have reached

Derived properties

derive adds properties that are computed at query time and never stored. Once defined, a derived property can be filtered on, sorted by, aggregated and returned, exactly like a stored one. There are four kinds

KindExampleNotes
Link aggregationCount of a shop's deliveries scheduled this weekcount, sum, avg, min, max, distinct counts, and lists or sets of values
Linked valueThe silo id of a batch's milk sourceOnly across to-one links, where a single value exists
ExpressionstaffNeeded - staffOnShiftArithmetic, date math, coalesce, case, on stored and other derived properties of the same object
Function-computedweekend_cover(shop), tubs shortA published query function, called in batches

Today, derive takes an expression string over the same object, such as "staffNeeded - staffOnShift", or $distance, and a later where filters on it: .derive({ staffGap: "staffNeeded - staffOnShift" }).where({ staffGap: { $gt: 0 } }). On request, derived values from linked objects and functions, as below

const shops = mso.objects(Shop)
  .where({ province: "NS" })
  .derive({
    deliveriesThisWeek: (s) => s.follow("delivery-stop-shop").follow("delivery-stop-delivery")
      .where({ eta: { $gte: "2026-10-26", $lt: "2026-11-02" } })
      .count(),
    staffGap: (s) => s.property("staffNeeded").minus(s.property("staffOnShift")),
    shortTubs: { function: "weekend_cover", output: "short" },
  })
  .where({ staffGap: { $gt: 0 } })
  .orderBy({ shortTubs: "desc" });

Derived properties are computed from the objects the reader can see. Two people can get different values for the same shop's deliveriesThisWeek if one of them cannot see some deliveries, and that is correct: a derived value never reveals more than its inputs

Aggregations

An aggregation groups a set and computes metrics per group, in one request, without loading objects. On request, a group can also be numeric ranges, fixed-width buckets or a date histogram in a named time zone

POST /api/v2/query/aggregate

In the platform service, group lists property or derived names and each measure names its op and property

{
  "query": {"from": "batch", "where": {"start": {"$gte": "2026-10-01T00:00:00-03:00"}}},
  "group": ["line"],
  "measure": {
    "batches": {"op": "count"},
    "litres": {"op": "sum", "property": "litres"},
    "products": {"op": "countDistinct", "property": "productId"}
  }
}
{
  "objectType": "batch",
  "groups": [
    { "key": { "line": "Line 1" },
      "metrics": { "batches": 12, "litres": 15370.0, "products": 9 } },
    { "key": { "line": "Line 2" },
      "metrics": { "batches": 6, "litres": 7200.0, "products": 4 } }
  ]
}

On request: group entries as objects with top, ranges, buckets and date histograms, conditional counts, approximate distinct counts, and the exact and snapshot fields in the response, as below

{
  "query": {"from": "batch", "where": {"start": {"$gte": "2026-10-01T00:00:00-03:00"}}},
  "group": [
    {"by": "line", "top": 10},
    {"by": "start", "every": "week", "tz": "America/Halifax"}
  ],
  "measure": {
    "batches": "count",
    "litres": {"sum": "litres"},
    "held": {"count": {"where": {"qaStatus": {"$eq": "On hold"}}}},
    "products": {"distinct": "productId"}
  }
}
{
  "exact": true,
  "snapshot": "ct_0000000004f2a3e0",
  "groups": [
    { "key": { "line": "Line 1", "start": "2026-10-26" },
      "metrics": { "batches": 6, "litres": 7470, "held": 0, "products": 6 } },
    { "key": { "line": "Line 2", "start": "2026-10-26" },
      "metrics": { "batches": 3, "litres": 3680, "held": 2, "products": 3 } }
  ]
}

In the platform service every measure is exact. On request, approximate distinct counts and percentiles for very large groups

Saved and pinned sets

On request, a set you use more than once can be stored as a resource with a name, a description and an owner, such as msrn:ontology:creamery:object-set/weekend-at-risk. There are two kinds, and the difference matters

Saved setPinned set
StoresThe definitionThe primary keys the definition resolved to
MembershipRe-evaluated on every readFixed at the moment of pinning
ValuesLiveLive by default, or as of the pin within version retention
Typical useScreens, automations, agent toolsRecall lists, audit samples, the exact set an approval covered

Both kinds respect the reader's permissions at read time. A pinned set records keys, not values, and someone without access to an object in it sees a smaller set, not a redacted row. Saved sets are versioned in the Ontology registry like any other resource, and a change on a branch shows in the proposal with the objects it adds and removes

Pushdown and scan

On request, a planner runs as much of a query as it can in the index, and explain shows the plan

Filter stored properties first

A filter on a derived property is cheap over 14 shops and expensive over 14 million sales lines. When a screen is slow, check that a stored filter narrows the set before any derived property runs. If the derived value is needed on large sets every day, compute it in a pipeline and store it as a property

Pagination and limits

Pagination and ordering

Loads return pages of 100 objects by default and 1,000 at most, with a nextPageToken for the next page. On request, a page token pins the snapshot of the first page, so paging through a set gives a consistent view even while objects change. Ordering takes up to three properties, and ties break on primary key, so the order is total and stable. Text searches can order by $relevance

POST /api/v2/query
Content-Type: application/json

{
  "query": {"from": "shop", "where": {"status": {"$ne": "Closed"}}},
  "select": ["shopId", "name", "stkStr"],
  "orderBy": [{"property": "name", "direction": "asc"}],
  "pageSize": 500,
  "pageToken": "pt_01JD7R2K5Q8M3W6T"
}

On request, a saved set can stand in for from, as {"query": {"saved": "msrn:ontology:creamery:object-set/weekend-at-risk"}}. Use select to return only the properties a screen shows. Responses for wide types are often ten times smaller, and properties the reader cannot see are left out either way

Limits

LimitDefault
Link hops per query3
Objects per page100, maximum 1,000
Vertices in an $inArea geometry10,000

Other limits are set per implementation. The limits page lists every limit the platform service enforces today

Limitations

  • follow is limited to 3 hops per query. Deeper paths need a direct link type or a second query
  • Comparisons never match null. A filter and its opposite can both exclude the same object, so missing values must be asked for with $missing
  • Set algebra works only on sets of the same object type or interface. A union of shops and deliveries is not an object set
  • A derived property cannot depend on another derived property, and a linked value works only across to-one links
  • A saved set re-evaluates on every read, so its membership can change between two reads. Use a pinned set when the exact membership must be kept
  • Results always reflect the reader's permissions. Two readers can get different counts and derived values for the same set, and there is no way to ask for an unfiltered count

Related