Skip to main content

Querying and search

Vox makes query behavior explicit in the entity model. A property is filterable, sortable or searchable only when the model says it is, and the same metadata drives storage, the API, permissions and generic clients.

For the team workflow, see Find products.

Query fields​

[VoxFilterable] creates an indexed field for equality and range filters. It supports scalar values and collections of strings, numbers, booleans, dates, GUIDs and enums, including values inside nested objects or collections. A date is a DateTime or DateTimeOffset, which is a moment and is compared in UTC, or a DateOnly, which is a day of the calendar without a time or time zone, eg an order date or the day an invoice is due. Use DateOnly for business dates: a DateTime at midnight UTC is another day in another time zone, so it can show and filter as the wrong day.

[VoxSortable] makes a scalar value available for ordering. [VoxSearchable] sends strings and rich text to the full-text index:

public class Product : IVoxEntity
{
[VoxFilterable]
[VoxSortable]
public required string Sku { get; set; }

[VoxSearchable]
public VoxVarying<IVoxLanguage, string> Name { get; set; } = new();

[VoxFilterable]
public List<string> Tags { get; set; } = [];
}

The same capabilities can be attached to the fields of field sets. Consumers therefore discover what is queryable from the model instead of maintaining a separate list of database columns.

Enums​

An enum is filtered by its name, in any case, never by its number: GET /api/prefix-rules?scheme=thema, ?scheme=Thema and the typed rule => rule.Scheme == ClassificationScheme.Thema find the same entities, while ?scheme=0 is a bad request. Enums are compared for equality only, and sorted by their names, alphabetically and ignoring case, on every provider: a Status with the members Draft, Scheduled, Active, Ended sorts as Active, Draft, Ended, Scheduled. To get there, query columns, search fields and in-memory sort keys hold the lowercase names, eg thema, while entities and the API keep the declared names, see Enums.

Computed query fields​

A property without a setter that computes a value from the entity's own values can be a query field too. It isn't a field of the entity: nothing writes it, and it has no drafts or ownership of its own. Its value is computed when the entity is written and stored in the query storage:

public class Product : IVoxEntity
{
public required virtual string Name { get; set; }

[VoxFilterable]
[VoxSortable]
public virtual string NamePrefix => Name.Length <= 3 ? Name : Name[..3];
}

Adding one to an entity type with stored entities computes it for them, a page at a time, as when a property becomes filterable. Vox can't see when the code that computes it changes, so declare that with a new revision, eg [VoxComputed(Revision = 2)] after changing Name[..3] to Name[..2], and the values are computed again in a new generation of the query storage. Without the attribute the revision is 1. A computed query field can only use the entity's own values, since it's computed while the entity is written; a value that depends on other entities is a calculated field.

Don't skip the new revision. When the calculated values of an entity are published, Vox only rewrites the query storage whose values the save changes: it computes the value of the published entity and of the saved one with the current code, and leaves the stored value as it is when the two are equal. So after changing Name[..3] to Name[..2] without a new revision, a product whose price is recalculated keeps its old three-letter NamePrefix in the query storage, until its Name changes or a new revision computes every value again.

Filters, sorting and paging​

Filters support equality and the usual greater-than and less-than comparisons. They can be combined with AND, OR and NOT in application code. The HTTP API expresses common filters through query parameters, for example:

GET /api/products?tags=outdoor&price[lt]=100&sort=-updatedAtUtc,sku&skip=0&take=50

A DateOnly value is written as an ISO date, eg GET /api/orders?orderedOn[gte]=2026-11-01&sort=-orderedOn, and an empty value, eg orderedOn=, matches entities without one.

A collection matches when it contains a matching value. Reference properties are queried by their referenced IDs, so relations participate without loading the target entities. Property paths such as pim.categories and variants.sizes address fields inside owned structures.

Any relation of an entity type filters a list through the relation index, also one that isn't a filterable field, eg an index-backed IVoxRelationReferences<T> relation, which isn't in the entity's JSON, or the inverse of a relation of another entity type:

GET /api/products?relation.categories=jackets,shoes
GET /api/categories?relation.products=p1

An entity matches when it's related to one of the IDs, which are separated by commas or repeated. Relation filters combine with the other filters, search and selection, and are answered by the database rather than the search index.

Vox applies a stable created-time and ID order after explicit sorts, so the order is total even when several entities have the same sort value. Nulls sort first in ascending order and last in descending order with every storage.

Pages, continuations and budgets​

Every page says whether more entities match after it (HasMore, hasMore in the API) without counting them, and gives a continuation of the next page (Continuation, continuationToken). A page read with a continuation seeks to the position of the last entity of the previous page in the query's order, its sort values, creation time and ID, rather than skipping, so it doesn't read the pages before it again, and an entity that's deleted before it doesn't shift it. The storage compares the position as it sorts, with its collation. Offsets (skip) remain for interactive paging up to VoxReadBudgets.MaxSkip (10,000); deeper pages are read with continuations.

A continuation is opaque and bound to the query it came from: the entity type and its query fields, the filters, sorts, scope, contexts and the principal's read scope. Another query, a changed token, or a token from before an incompatible change of the model is rejected with a 400 rather than read from another position.

A query reads either way:

  • Live browsing (the default) continues in what exists when each page is read, so new entities can appear in later pages.
  • A scan (VoxQuery.Scan) reads the entities created up to when its first page was read, so it ends rather than chasing what's inserted while it runs. Elasticsearch reads a point in time, which the continuation keeps alive for VoxReadBudgets.ScanLifetime, after which the continuation expires; the last page of a scan closes it. A durable consumer catches up on what changed behind the scan from its boundary.

The total count is optional (IncludeTotalCount, includeTotalCount=true), since it counts every match. Lists show a page at once, and count apart.

Reads have budgets, VoxOptions.ReadBudgets, which are checked before what's read is hydrated: at most MaxItems (10,000) entities in one read, MaxRelationLinks (10,000) links in a complete read of one relation, MaxPreloadLinks (100,000) links for the includes of one page, ids in requests of MaxBatchIds (1,000), at most MaxConcurrentRequests (32) requests at a time and MaxResponseCharacters of stored entities. A query without a take reads every match up to the budget, and one that matches more fails with a VoxReadBudgetExceededException rather than returning a part of them; it never pretends that a partial result is complete. Read larger sets a page at a time, or count or filter them in the storage.

What each storage supports​

Entity FrameworkElasticsearchRedis
Filters and sortsAll query fields, in SQLThe indexed query fieldsOne condition or sort, from one index of a filterable or sortable field, ordinal
ContinuationKeyset on the sort valuessearch_after on the sort valuesSeek in the index it reads, after the last entry of the previous page
ScanCreation-time boundaryPoint in timeCreation-time boundary
Relation, assessment and draft filtersYesForward relations in its documentsOne relation declared InverseIndexed, ordered by ID; no assessments or drafts
Total countCOUNTtrack_total_hitsThe size of the part of the index read

Redis stores only transient entity types, and answers each query from one index, read only as far as its page, or from the entities it names by ID, merged with what a transaction staged. A filterable or sortable field of a transient entity type, and UpdatedAtUtc, has an index of its own, and so has the inverse direction of a relation declared InverseIndexed. A query never scans: one with two conditions, eg carts?sessionId=abc&status=active, a sort by another field than the filtered one, or an or filter fails at once with a VoxQueryCapabilityException that says what to do instead. The same rules apply to a transient entity type in Entity Framework storage, so a query that works without Redis works with it, with two differences: a query filtered by a relation is ordered by ID in Redis and by creation in Entity Framework storage, and strings compare ordinally in Redis and with the database's collation in Entity Framework storage, eg case-insensitively on SQL Server. See Queries for the shapes that are answered and the errors of those that aren't.

A light entity type is queried in memory over its current entities, which it keeps whole, with strings equal in any case and sorted in a configured culture. Its relation filters are answered by the relation index, and filters by draft status or assessments fail with a VoxQueryCapabilityException.

Typed queries and included relations​

Application code builds the same queries with expressions through store.Query(), whose builder is immutable:

using var cache = readCacheScopes.Begin();

var products = await productStore.Query()
.Where(product => product.Status == ProductStatus.Active)
.WhereRelated(product => product.Categories, ["jackets"])
.ExistsIn<Market>("se")
.InContexts(selection)
.OrderBy(product => product.Name)
.Take(100)
.Include(product => product.Variants)
.ThenInclude(variant => variant.Product)
.Include(product => product.Merchandising.Brand)
.ToListAsync(cancellationToken);

foreach (var product in products)
{
// Read from the scope, without another read of the storage
var variants = await product.Variants.LoadAsync(cancellationToken);
}

Include and ThenInclude select a relation by its lazy navigation, its reference properties, its indexed references, or its name, eg Include("variants.product"). The query gets its page of entities first, then reads every related entity of those entities, relation by relation in batches rather than one entity at a time, into the read cache scope that's active. It returns the entities themselves: their navigations, the entity stores, the relation loader and evaluation contexts read what was included from the scope. An include is the complete relation, without the limit of an API expansion. Reference properties keep their references, and their targets are read in the order the properties have them.

A query with includes needs an active scope, which keeps what's included for the reads that follow, and it checks its includes against the model before it reads anything. A query that fails to include its relations fails. CountAsync counts in the query's contexts and scope with its relation filters, and includes nothing. Entities that were read before are included with cache.PreloadAsync(entities, preload => preload.Include(...)).

ForEachPageAsync processes every entity of a query a page at a time, each page in a scope of its own, so memory follows the page rather than every entity. It's a scan: each page continues from where the previous one ended, so a deletion meanwhile doesn't make it skip or repeat an entity, and it reads what was created up to when it started. ToPageAsync(continuation) reads one page after another, eg for an endpoint of its own.

Inside a calculation, projection or assessment, context.Query<TEntity>() builds the same queries as tracked queries, which read the authoritative storage rather than a search index, and whose consumers are calculated again when a change can alter their results, see Calculations.

Context-aware queries​

For a varying property, a filter or sort can name a stored context explicitly or use the contexts selected for the request. This lets the same product query sort by the Swedish product name in one request and the English name in another.

Context membership also constrains which entities belong in a selected market, channel or other dimension. Read permissions are applied before counting and paging, including :My ownership and allowed context scopes, so a client cannot infer inaccessible entities from totals.

Queries can select published, draft or release content. Editors can additionally filter by draft state, such as changed, scheduled, conflicting or failed publication.

Selectors​

For what editors do with rules, see Pick products by a rule.

A selector is a filter saved on an entity, eg the rule of a product list: "brand is Northpeak and categories is Rain jackets and in stock is yes". Editors build it in the admin, and your code runs it like any other query. See Entities and relations for how to declare one.

Run a selector with the same query builders as an expression:

var products = await productStore.Query()
.Where(list.Rule!)
.OrderBy(product => product.Name)
.Take(20)
.ToListAsync(cancellationToken);

In a calculation or projection, context.Query<Product>().Where(block.Rule) is a tracked query: the block is projected again when a product starts or stops matching. The selector holds no sort, maximum or paging; those belong to the entity that uses it. VoxSelector.From<Product>(product => product.Price < 300) creates one from an expression.

What a selector can say​

A selector compares the target type's filterable query fields and combines the comparisons with and, or and not. In JSON it's the filter itself:

{
"kind": "and",
"filters": [
{ "kind": "field", "field": "merchandising.brand", "operator": "Equal", "values": ["northpeak"] },
{ "kind": "field", "field": "commerce.isInStock", "operator": "Equal", "values": [true] },
{ "kind": "not", "filter": { "kind": "field", "field": "merchandising.categories", "operator": "Equal", "values": ["outlet"] } }
]
}
  • Equal matches any of its values. A reference is compared by the id of the entity it refers to.
  • GreaterThan, GreaterThanOrEqual, LessThan and LessThanOrEqual take one value and compare numbers and dates. Text, yes-or-no values, enums and ids are only compared for equality.
  • not is two-valued: a product without a brand matches "brand is not Northpeak".
  • A varying field without a context, eg price, is compared in the contexts the selector is run in. With one, eg price.se, it's compared in that context. A number is compared as stored, so a rule "price is less than 300" means 300 in each market's own currency. The admin's rule editor picks a context only for a field that varies on one context type; a condition on a field that varies on two, eg language and channel, is compared in the contexts the rule is run in.

Saving an entity validates its selectors against the target type. A condition on a field that isn't filterable, a value that isn't valid for its field, eg text for a number, a range on text, or an empty group is refused with an error that names the condition, eg rule.filters[1]: The condition price < cheap compares with cheap, which isn't a valid value of Product.price, which is a number. Values are stored in their field's JSON form, so "300" is saved as 300. A condition on a classified field needs the same permission as filtering by that field. Writes through the storage writers, eg of imports and calculations, aren't validated, like other entity validation. Their selectors' fields aren't added to the fields that saves capture either, so a tracked query over such a selector can only compare fields that a tracked query in code or a saved selector already uses, or it fails with an error that names the field. Their selectors do keep the fields they compare captured once something else added them.

A field stops being captured a few minutes after the last saved selector that compares it changes or is removed, and up to an hour later when the target type's fields were recounted shortly before, see Dependency and change tracking. Two cases to be aware of:

  • An import, sync or calculation that writes a selector comparing a field while the fields are being recounted, when only a selector that an editor just changed compared that field, can't keep the field. Running the written selector as a tracked query then fails with an error that names the field until an editor saves the selector.
  • A calculation running at the moment a field is dropped, with a selector it read just before an editor changed it, can fail once. The editor's change has already queued the calculation again, and that run uses the new selector.

Recounting reads every stored selector that selects the target type, page by page, so with selectors on an entity type with millions of entities it reads all of them, at most once an hour.

A field that's renamed or removed later leaves the selectors that named it unchanged. Running such a selector fails with an error that names the field, and the admin shows the condition as broken until an editor fixes it.

Checking one entity in memory​

IVoxSelectorMatcher answers whether an entity you already have matches a selector, without a database round trip, eg for the product a calculation is working on:

var isIncluded = matcher.Matches(campaign.Products!, product);

Compile returns a predicate to use for many entities. The answer agrees with the target type's database: text is compared exactly on SQLite, PostgreSQL and Redis, ignoring case on SQL Server, and by the configured culture for light entity types. On SQL Server with a search index, a list or the admin's preview is answered by the index, which compares text exactly, so "SKU is ABC-1" doesn't count abc-1 there, while the matcher and tracked queries do.

Previewing a selector​

POST /vox/api/{route}/selector-matches, where {route} is the target type's route, takes { "selector": <filter> } and returns the first page of the entities it picks, sorted by sort like a list, with includeTotalCount=true for how many there are. It runs in the request's contexts and scope, checks the same read permissions as a list, and answers 400 with the error of each broken condition at its path, eg selector.filters[1].

Full-text search is separate from structured filtering. Every complete search term must occur in the searchable document, while the final term is treated as a prefix. A query for rain ja can therefore match “Rain jacket.” Rich text is indexed as visible text rather than HTML.

Search results contain relevance scores and plain-text highlight ranges. Supplying an explicit sort replaces relevance ordering. Structured filters, contexts, content modes, relation expansion and authorization continue to apply to search results.

Consistency​

Search indexing is durable and asynchronous. Vox records pending index work in the same transaction as an entity change, so an unavailable search engine delays visibility but does not lose the update.

The dependency graph decides which derived results became stale, while the search outbox makes every resulting document update durable. Only published versions are indexed, and a save publishes an entity with its own calculated values, so search never returns a new purchase price with the old margin. Version checks prevent stale work from replacing a newer document. See Dependency and change tracking.

When the query fields of an entity type change, or a model migration may change their values, eg a transform, a clear of a filterable property or a kind remap, Vox fills a new index with every entity while the old one is still queried, and changes are written to both. The new index is queried only once it's been filled completely; until then, applications' queries and searches match the old values of the entities the fill hasn't reached, while Vox's own processing reads the database. The entities that a query returns are always upgraded to the current model, also from the old index, see model evolution. The fill is Vox background work on one processing host at a time, with the vox_search_index_backfill health check. A fill that fails or is interrupted starts over from the first entity; it keeps no position, and the version checks keep it from replacing a newer document.

The fill checks at every idle check whether an index needs filling, but a processing host asks Elasticsearch only about the indexes it doesn't yet know as filled: once every index is filled, the check makes no requests. A host reads the indexes again when it starts and when a new model is activated. So Vox doesn't notice an index deleted by hand in Elasticsearch while the hosts run; deleting Vox's indexes isn't a supported operation, but if you do, restart the processing hosts so that the index is created and filled again.

The indexing runs in a loop on every processing host (see background work), which reads the search outbox directly: each host claims a batch of entities with a lease, indexes them as they are now and completes their outbox rows. A recalculation that changes the price of 2,000,000 products is indexed by all the processing hosts together, and an entity that changed several times before it was indexed is indexed once. When the search engine is down, every entity of a batch fails, and the loop waits with a growing delay instead of counting it against the entities, then catches up once it's back.

An entity that can't be indexed, eg since the search engine rejects its document or the mapping doesn't fit, doesn't hold back the others. It's tried again with a growing delay, capped at an hour, and never given up, so the index can't silently stay wrong for it; a newer change of the entity starts it over. Meanwhile the vox_search_indexing health check is degraded, with how many entities fail and the errors of a few of them. Once the cause is fixed, eg the mapping, the entity is indexed at its next attempt.

Search is eventually consistent: an entity is indexed in the background after it's published, and a write never waits for it. Only published content is indexed, so search never returns draft values in published results. A search in a draft or release matches and sorts entities by their published values, and returns them as they are in the draft or release.

See API overview, Languages, markets and channels and Users, roles and permissions.