Skip to content

vector-ranking

Terminal window
npx skills add https://github.com/crystallizeapi/ai --skill vector-ranking

Crystallize Vector Ranking

Discovery ranks the whole catalogue for the person in front of it, inside the same query you already use for search and browse. You describe products in a vocabulary of your own — roast, flavour, fit, finish, use case, margin band. A shopper is described in that same vocabulary. The index scores every item by cosine similarity and sorts. Then you put your own weighted rules on top, and every position can come back with an explanation.

These are sparse, author-supplied, named vectors — not dense ML embeddings, and not a trained model. Nothing is learned; the vocabulary is the model. There is nothing to train and nothing to sync.

Verified on 2026-09-15 against the live Core API (upsertVocabulary, vocabulary, setItemTaste, igniteDiscoApi) and against a ranking-enabled Discovery tenant by introspection, and reconciled with the Discovery vector-search documentation as of the same day. Where the public docs and the served schema disagree, this skill follows the schema and says so. Ranking is a capability that is enabled per tenant — how it is served is an implementation detail and is deliberately not documented here. Window, paging and indexing behaviour was reviewed again on 2026-10-29.

Detect the capability before you write a query

This is the failure mode that catches agents. Ranking is enabled per tenant. Until it is, rankBy, context and nearestTo are absent from that tenant’s Discovery schema — referencing them is a GraphQL validation error, not a query that quietly returns unranked results. A tenant is served for ranking once an ignition with stacks: opensearch has completed. The surface can also disappear again if ranking is disabled for a tenant.

# Probe once, cache the answer. Non-null => this tenant is served for ranking.
{
__type(name: "RankByInput") {
name
}
}

An un-ignited tenant does not even serve the schema:

{ "success": false, "message": "There is no ignited Tenant for <tenant>." }

A tenant that has ranking enabled but still refuses a vector argument answers with an error stating that ranking is not available for this tenant. Do not match on the message text — treat the presence of the argument in the schema as the capability check.

Three enums are generated per tenant, so they are never hardcodable:

Enum Built from Gotcha
TenantVocabularyIdentifier your vocabularies, names normalized for GraphQL a new vocabulary is only a valid value after the next index run; until a tenant has one, the argument is a String
TenantRankByField NUMBER and DATE sortable attributes, facet fields excluded it is not “any numeric field”: sortable: false on a component drops it — introspect it
TenantRankByTieBreaker sortable fields (token, number, date) tieBreaker is required on every rankBy

Introspect all three rather than guessing:

{
v: __type(name: "TenantVocabularyIdentifier") {
enumValues {
name
}
}
f: __type(name: "TenantRankByField") {
enumValues {
name
}
}
tb: __type(name: "TenantRankByTieBreaker") {
enumValues {
name
}
}
}

Two APIs

API Endpoint Auth Used for
Core https://api.crystallize.com/@<tenant>/core access token pair vocabularies, taste entries, publishing, indexing
Discovery https://api.crystallize.com/<tenant>/discovery none by default querying

Core takes @tenant with an at-sign; Discovery takes the bare tenant. Vocabulary and index mutations live on Core, not on the PIM API, and never run in a storefront request. Everything before Discovery is authenticated and server-side; the queries themselves need no credentials, so a browser can build a vector from sliders or session state and call Discovery directly. A vector built from the shopper’s orders or identity is built on the server, from the Shop API (see references/personalization.md). A tenant that protects search answers 401 until each request carries its static token in X-Crystallize-Static-Auth-Token.

Five concepts

Concept What it is
Vocabulary A named set of dimensions, each carrying a weight list. A tenant can have several; each is scored on its own.
Dimension One axis inside a vocabulary — roast, flavor, region. Carries a weight list.
Entry A dimensionId:value key attached to one item, in a meaningful order.
Item vector Built at index time. Every entry becomes a key with the weight its dimension and position give it.
Shopper vector The same shape, sent with the query as context.userTaste.

Two properties fall out of this and drive every design decision:

  • Shoppers and products share the keys. A shopper who likes flavor:chocolate at 1.0 is compared to products carrying flavor:chocolate. Nothing has to be learned.
  • Vocabularies are summed. One shopper vector per vocabulary; the index adds the per-vocabulary cosines. A product matching two vocabularies outranks a product matching one.

The pipeline

Core upsertVocabulary once per vocabulary — FULL REPLACE, not a patch
Core setItemTaste per item, vocabulary, language — DRAFT; ONE AT A TIME per item
Core publishItem per item and language — the step that is easy to miss
Core igniteDiscoApi(stacks: opensearch) LAST; poll bulkTask until "complete" ("error" is blocking)
Discovery { __typename } probe before reporting success
Discovery search(rankBy:) your rules: margin, stock, velocity, recency
Discovery search(context:) ranked for this shopper
Discovery search(rankBy: + context:) your rules, plus this shopper
Discovery search(nearestTo:) ranked by a reference item

Ignite the first time, and again after any upsertVocabulary. Vectors are built with the vocabulary’s weights, so a vocabulary change has no effect until the next index run and raises no error. A taste change needs no ignition on a tenant already served for ranking: publishing the item re-indexes it, vectors included. stacks: opensearch is required for ranking to be served; see step 5 in the authoring reference.

Authoring detail — vocabulary design, positional weights, key validation, publishing and indexing — is in references/vocabulary-authoring.md.

Choosing the query path

You want Use Notes
A house order for everyone (margin, stock, velocity, newness) rankBy alone The baseline every personalized result builds on
Results ordered for this shopper context.userTaste alone Ranks the whole result set; no terms, so rankExplain is null
Your rules and this shopper, weighted independently rankBy + context, with a tasteCosine term The only way to weight vocabularies separately
“Similar products”, basket pairings nearestTo k replaces pagination.limit; anchor is excluded
Neighbours that also respect stock/margin nearestTo + rankBy with tasteCosine, from: nearestTo nearestTo alone ignores context.userTaste

Signals, normalization, rankScore/rankExplain and the rerank window are in references/ranking-signals.md. Shopper vectors, magnitude, where the vector comes from and nearestTo are in references/personalization.md.

Where the vector arguments are accepted

Verified by introspection on a ranking-enabled tenant — rankBy, context and nearestTo are on:

  • search and autocomplete
  • every shape field under browse (browse { product(...) }, browse { category(...) }, …)
  • Folder.children and Topic.items

They are not on Topic.children, which takes language only. Note the naming: the public docs say “the children queries on topics and folders”, but the field on Topic is items.

Folder.children and Topic.items default to sorting: { position: asc }, which keeps them on the windowed path — see references/ranking-signals.md.

Failure modes

Several of these produce no error at all — they are the reason this skill exists.

Symptom Cause Fix
Order unrelated to taste, no errors Taste is on the draft only publishItem, wait until it is published, retest
Order unchanged after upsertVocabulary No index run since the change igniteDiscoApi(stacks: opensearch), wait for complete
Ignition complete, no ranking args igniteDiscoApi run without stacks: opensearch, or with both Re-run with stacks: opensearch
Ignition task ends in error e.g. ignited before any shape existed, or stacks left out on a tenant already served for ranking Read bulkTask.info.traces, fix what it names, then ignite again. Never re-run it unchanged
{ __typename } fails after complete Discovery cannot build the tenant’s schema Do not re-ignite in a loop. Report it with the tenant identifier and the response body
Rankings subtly wrong, no errors magnitude miscomputed client-side Assert sqrt(Σ w²) against a known case
Ranked list misses obvious matches The window is the first N by sorting, itemId descending when none Send sorting: { score: desc } with a term, or raise options.rerankWindow
rankScore comes back null No rerank ran — no rankBy, context or nearestTo, or every rankBy term had weight: 0 Give at least one term a non-zero weight
Vocabulary “does not exist in enum” No index run since it was created igniteDiscoApi(stacks: opensearch), wait for complete
Vocabulary <name> not found No vocabulary indexed yet; the argument is still a String igniteDiscoApi(stacks: opensearch), wait for complete, then pass the enum value unquoted
context / rankBy unknown in schema Ranking not enabled for the tenant, or not indexed igniteDiscoApi(stacks: opensearch), wait for complete plus propagation. Detect the capability, don’t assume it
Items missing whole vocabularies Concurrent setItemTaste calls on one item: last write wins, no error Write one item’s calls in sequence, items in parallel; read back with ... on Item { taste }
Vocabulary <name> not found after complete Propagation: lasted about 5 minutes on one tenant although the enum listed it Probe a real context query per vocabulary before reporting success
Everything scores 0 with context userTaste sent as a map keyed by vocabulary Send a list: [{ vocabulary, weights, magnitude }]
A term search ranks off-topic items high rankBy replaces text relevance Add a relevance term whenever there is a term
Every shopper sees nearly the same order Equal weights on many entries: tastes collapse Positional weights ([1.0, 0.5, 0.35]) on the dimension
A test vocabulary will not go away There is no deleteVocabulary Do not create throwaway vocabularies on a real tenant
Malformed taste entry key Key has no colon Use dimensionId:value
Unknown dimension Prefix is not a declared dimension Add it to the vocabulary, or fix the key
tieBreaker validation error Required field missing Add a tieBreaker
Field <name> not found recency on a number, or fieldBoost / inStockBoost on a date Point the term at a field of the right kind
Page 2 empty under ranking skip ran past the rerank window Raise options.rerankWindow (default 500, cap 2000)

How ranking composes with the rest of the query

  • filters, facets and term apply as usual. Ranking decides the order inside the filtered set; it does not change which items match.
  • Items without a vector are still returned. They score 0 on taste and sort after the ones that match, rather than disappearing. tasteCosine contributes 0 for them, so unmapped products fall back to your other rules. 0 is the middle of the range, not the bottom: they outrank anything scoring negative, and under a negative tasteCosine weight they float to the top.
  • rankBy ranks inside a bounded window, and it is not the top matches: it is the first N documents under the query’s sorting, or itemId descending when you sent none. context or nearestTo with no rankBy and no sorting rank the whole result set. See references/ranking-signals.md.
  • sorting selects the window, never the returned order. The rerank owns the order that comes back. sorting: { score: desc } is how you ask for relevance-selected candidates, and any sorting you send puts the query on the windowed path.
  • Cursors depend on the path. On the whole-set path after/before page the ranked set as usual, with summary.endToken. On a windowed path they move the window, not the page — page with skip and limit, and size the window for the depth you intend to page.

Use [[query]] for the rest of the Discovery API — filters, facets, pagination, browse vs search. Use [[storefront]] for where the ranked reads sit in the request path and how they are cached, and [[agentic-commerce]] for ranking every MCP or assistant tool result by the shopper’s taste. Use [[mutation]] for the Core API mutations these sit next to, and [[js-api-client]] to call either from JS/TS. Vocabularies overlap conceptually with topic maps: [[taxonomy]] designs the classification, and a taste entry can be derived from a topic assignment — see “Keep one source of truth” in references/vocabulary-authoring.md. [[content-model]] covers the shapes whose numeric components become TenantRankByField values.


Reference Details

Personalization & Similarity (context.userTaste, nearestTo)

Discovery API, https://api.crystallize.com/<tenant>/discovery, no auth unless the tenant requires a static token. Nothing about the shopper is stored in Crystallize — you send the vector with each query.

context.userTaste

UserTasteInput { vocabulary: TenantVocabularyIdentifier! # enum, generated per tenant
weights: JSON! # { "dimensionId:value": number }
magnitude: Float! } # L2 norm of weights
ContextInput { userTaste: [UserTasteInput!]! } # one entry per vocabulary

userTaste is a list, one entry per vocabulary. A map keyed by vocabulary is not rejected: every item then scores 0, silently. It must be non-empty, and a vocabulary may appear at most once. weights maps dimensionId:value to a number — positive means likes, negative means dislikes. A negative weight puts the query on the windowed path; see the rerank window.

Weight keys contain a colon, which is not a valid GraphQL name, so pass the context as a variable, never inline in the query document.

query SearchWithTaste($context: ContextInput!) {
search(context: $context, pagination: { limit: 24 }) {
summary {
totalHits
}
hits {
... on product {
itemId
name
rankScore
topicPaths(leafOnly: true)
defaultVariant {
sku
defaultPrice
firstImage {
url
}
}
}
}
}
}
{
"context": {
"userTaste": [
{
"vocabulary": "taste",
"weights": { "flavor:berry": 1.0, "roast:light": 1.0 },
"magnitude": 1.4142135623730951
},
{
"vocabulary": "origin",
"weights": { "region:kenya": 1.0 },
"magnitude": 1.0
}
]
}
}

The two entries are scored separately and added, so Kenyan light-roast berry coffees rise above coffees that satisfy only one of them.

Supplied without rankBy, results are ranked toward that taste automatically, over the whole result set unless a windowed case applies. rankScore carries the summed cosine. There are no terms on this path, so rankExplain is null.

You supply the magnitude

magnitude is the length of the shopper vector — one number that lets the index compare direction (what they like) without being fooled by size (how much they like it). It is sqrt(Σ w²): square every weight, add them up, take the square root. For { "flavor:berry": 1.0, "roast:light": 1.0 } that is sqrt(1 + 1) = 1.414.

A miscomputed magnitude raises no error. The server divides by the number you send and never recomputes it, so a wrong value rescales that vocabulary’s contribution. That is harmless with a single vocabulary and no rankBy, and a ranking bug as soon as you sum vocabularies or blend with other signals: the results look plausible and are wrong. magnitude: 0 is not “let the server work it out”: it zeroes that vocabulary for every item. Compute it in exactly one place and unit test it against a known case.

type SparseVector = Record<string, number>;
const magnitude = (w: SparseVector) => Math.sqrt(Object.values(w).reduce((sum, x) => sum + x * x, 0));
const toUserTaste = (vocabulary: string, weights: SparseVector) => ({
vocabulary,
weights,
magnitude: magnitude(weights),
});

Prune near-zero weights before sending, and compute magnitude after pruning. They cost payload and contribute nothing beyond rounding, and past about 800 weights the query takes the windowed path.

Where the shopper vector comes from

The vector is UI state or session state, whichever you have. All of these are one query each:

  • Sliders and chips. A slider from light to dark spread over roast:light, roast:medium, roast:dark; a chip that sets flavor:chocolate to 1.
  • Cold start from picks. Let a new visitor pick two or three products, read what they are made of, rebuild the vectors with the same positional rule, and sum them. No history needed. Item taste is not exposed on Discovery hits — read topicPaths from the hit if your taste keys are derived from topics, or read item { ... on Item { taste { ... } } } from Core server-side.
  • Decayed session behaviour. Add a little weight for every product a shopper opens or adds, decay it over time, and send the result. The profile lives in the browser or your session store.
  • Order history, rebuilt per request. Read the shopper’s orders from the Shop API (orders(customerIdentifier)) on the server, take the keys of what they bought (the topic paths in each order line’s meta), weight them with the same positional rule as the items, and send the result. Nothing is stored per person, and in one build a joiner, an electrician and a carpenter got clearly different home grids, category orders and menu images. Cache the vector per customer for a short while; the order listing lags new orders by seconds to minutes anyway.
  • Agents. An MCP server or an on-site assistant ranks every tool result for the shopper behind the call: when its access token or session identifies the shopper, rebuild context.userTaste from Shop API order history per call, as above (no stored profile), and send it with every search, similar-products and recommendation tool. A signed-out call falls back to the house ranking (rankBy without tasteCosine). Add relevance to the terms whenever the tool passes a term. See [[agentic-commerce]].

Order history and the agent’s identity are server-side, so this vector is built on the server even when the rest of the page could call Discovery from the browser.

Blending taste with your rules

context alone ranks purely by taste. To put the shopper on top of the catalogue rules, add one tasteCosine term to a rankBy and pass both — taste terms read the shopper vector from context. Neither half errors without the other: a tasteCosine term with no context entry for its vocabulary scores 0, and a context with no tasteCosine term in the rankBy is ignored.

query Blended($context: ContextInput!, $rankBy: RankByInput!) {
search(term: "espresso", context: $context, rankBy: $rankBy, sorting: { score: desc }, pagination: { limit: 24 }) {
hits {
... on product {
name
rankScore
rankExplain {
signal
index
contribution
}
}
}
}
}
{
"rankBy": {
"terms": [
{ "signal": "relevance", "weight": 1.0 },
{ "signal": "fieldBoost", "weight": 0.6, "field": "margin_number", "normalize": true },
{ "signal": "inStockBoost", "weight": 0.4, "field": "stock_default" },
{ "signal": "recency", "weight": 0.3, "field": "publishedAt", "halfLifeDays": 60 },
{ "signal": "tasteCosine", "weight": 1.2, "vocabulary": "taste", "from": "userTaste" }
],
"tieBreaker": "sku",
"explain": true
}
}
rankScore = 1.0·relevance + 0.6·margin + 0.4·inStock + 0.3·recency + 1.2·cos(taste)

The split is explicit: the first four terms are your rules and apply to everyone, the last is this shopper. Raise the taste weight and the shelf becomes more personal; lower it and your rules take over.

One tasteCosine term per vocabulary lets you weight vocabularies independently — taste at 1.2, origin at 0.3 — which plain context cannot do. This is the main reason to reach for the blended path.

tasteCosine contributes 0 for items with no vector in that vocabulary, so unmapped products fall back to your other rules rather than disappearing.

A dial on one vocabulary needs that vocabulary’s term weighted up. A slider that adds keys to one vocabulary only moves that term’s cosine, so a shopper with a strong taste in another vocabulary keeps the same top items whatever the slider says. Weight the dialled term up (3 against 0.8 worked in one build) while the dial is set.

Rank once, reuse everywhere. One rankBy over the catalogue per request (limit: 250, explain: true) can feed every rail on a page — “For you”, the home rows, the hero. Discovery reads are cached on query + variables, and the taste is part of the variables, so each shopper’s ranking is computed once per cache lifetime.

Let Discovery filter, rank and page in one query for interactive surfaces. Ranking 250 cached cards in code cost about 0.5 s and 255 KB per slider move; one browse.<shape>(filters, rankBy, context, pagination: { limit: 12 }) query per move, plus a cached limit: 0 query for counts and facets, brought it to about 0.2 s and half the payload. Skip the shared cache for reads that are almost never repeated, such as every slider position.

nearestTo — “more like this”

Ranks by similarity to a reference item’s own stored vector instead of a hand-built one. Use it for “similar products” on a product page, or pairing suggestions from a basket.

NearestToInput { vocabulary: TenantVocabularyIdentifier!, like: NearestToLikeInput!, k: Int! }
NearestToLikeInput { sku: String, itemId: String } # pass exactly one
{
search(nearestTo: { vocabulary: taste, like: { sku: "ET-006" }, k: 12 }) {
hits {
... on product {
itemId
name
rankScore
}
}
}
}

Four things to know:

  • The anchor item is excluded from the results.
  • An anchor with no vector for that vocabulary yields an empty result — not a fallback to relevance. So does an anchor not found in the query’s language and publication state. Check the anchor before rendering an empty shelf.
  • k replaces pagination.limit when nearestTo is set, and is itself capped by the rerank window.
  • nearestTo alone does not combine context.userTaste. It scores from the anchor vector only, in one vocabulary: on a mood vocabulary alone, a film’s neighbours shared its mood and nothing else. For a “more like this” that spans vocabularies and follows the shopper, use rankBy with a userTaste built from the item’s own keys blended with the shopper’s (the item’s keys at 0.8 kept it in the lead; 1.2 let the shopper take over).

Observed on single tenants and not resolved, so verify on yours: nearestTo answered no hits for one vocabulary while ranking by a userTaste in that same vocabulary worked, and on another tenant a tasteCosine term from: nearestTo contributed 0 to every hit, while nearestTo alone (with filters) returned the right neighbours. Read rankExplain before you ship the blended path.

To blend neighbours with stock, margin or the shopper’s own taste, add a tasteCosine term with from: nearestTo to a rankBy, and keep nearestTo in the query: the term reads the anchor from it and scores 0 without it. A rankBy is windowed, so neighbours outside the window are never considered; narrow the set with filters, or raise options.rerankWindow, on a catalogue larger than the window.

{
"rankBy": {
"terms": [
{ "signal": "tasteCosine", "weight": 1.0, "vocabulary": "taste", "from": "nearestTo" },
{ "signal": "inStockBoost", "weight": 0.5, "field": "stock_default" },
{ "signal": "fieldBoost", "weight": 0.3, "field": "margin_number", "normalize": true }
],
"tieBreaker": "sku"
}
}

Verifying personalization actually works

Run the same query with and without context and compare the order. If the two match, no vectors reached the index — the items were never published after setItemTaste, or the index was never re-run. See steps 4–6 in vocabulary-authoring.md.

Ranking Signals (rankBy)

Discovery API, https://api.crystallize.com/<tenant>/discovery, no auth unless the tenant requires a static token.

On a tenant served for ranking, a query with no sorting is not in relevance order: hits come back by itemId descending, even with a term. sorting: { score: desc } gives relevance order. rankBy blends several weighted signals into one score instead:

rankScore = Σ (weight × signal)

Positive weights boost, negative weights penalize — a high return rate can legitimately push a product down. Different surfaces carry different rules: a category page may lean on margin, a search page on relevance, a clearance page on stock.

Schema

RankByInput { terms: [RankByTermInput!]!, tieBreaker: TenantRankByTieBreaker!, explain: Boolean }
RankByTermInput { signal: RankBySignal! # required
weight: Float! # required
field: TenantRankByField # fieldBoost | inStockBoost | recency
halfLifeDays: Float # recency
vocabulary: TenantVocabularyIdentifier # tasteCosine
from: TasteCosineFrom # tasteCosine
normalize: Boolean }
RankBySignal = relevance | fieldBoost | inStockBoost | recency | tasteCosine
TasteCosineFrom = userTaste | nearestTo

terms must hold at least one term. tieBreaker is required — it settles ties deterministically so the order stays stable across pages.

The five signals

Signal Required Optional What it scores
relevance — — Text match against term. Contributes 0 when there is no term.
fieldBoost field normalize A rankable number on the item, used directly as a boost.
inStockBoost field — Binary: contributes 1 when the named numeric field is > 0. Ignores quantity.
recency field, halfLifeDays — Exponential time-decay on the age of a date field: 0.5 ^ (ageInDays / halfLifeDays).
tasteCosine vocabulary, from — Cosine to the shopper vector (from: userTaste) or to an anchor item (from: nearestTo). See personalization.md.

With a term, put relevance in the terms. A rankBy replaces the text score: a search for “angle grinder” ranked only by fieldBoost and tasteCosine put cutting discs that mention angle grinders above the grinders. Add { signal: "relevance", weight: 2 } (or whatever weight wins on your catalogue) whenever the query has a term; without one it contributes 0 and can stay in the terms harmlessly.

recency needs a date field; fieldBoost and inStockBoost need a number field. TenantRankByField holds both kinds, so the wrong one passes schema validation and the query fails with Field <name> not found.

An item without the value scores 0 on all three. That is the worst value under a positive weight and the best under a negative one, so a penalty on, say, return rate lifts every item that has no return rate.

The field enums are per tenant

field and tieBreaker are not free-form strings — they are enums generated from the tenant’s index settings. Introspect them; do not guess.

Enum Built from
TenantRankByField NUMBER and DATE sortable attributes, with facet fields excluded
TenantRankByTieBreaker sortable fields (token, number and date)
TenantVocabularyIdentifier the tenant’s vocabularies, only after the next index run

Following sortable is the trap: a number you can filter or facet on drops out of both enums when its component sets sortable: false, so it is not necessarily a number you can boost on.

{
f: __type(name: "TenantRankByField") {
enumValues {
name
}
}
tb: __type(name: "TenantRankByTieBreaker") {
enumValues {
name
}
}
}

Typical values on a commerce tenant: price_default, price_sales, defaultVariantPrice_default, lowestVariantPrice_default, highestVariantPrice_default, stock_default, stock_oslo, publishedAt, createdAt, updatedAt, position, depth, and any numeric component (dimensions_weight_number, sold_30d_number, margin_number, rating_number, …). A numeric component is always <id>_number, never the bare <id>.

Example

query Catalogue($rankBy: RankByInput!) {
search(term: "espresso", rankBy: $rankBy, sorting: { score: desc }, pagination: { limit: 24 }) {
hits {
... on product {
name
score
rankScore
rankExplain {
signal
index
contribution
}
}
}
}
}
{
"rankBy": {
"terms": [
{ "signal": "relevance", "weight": 1.0 },
{ "signal": "fieldBoost", "weight": 0.6, "field": "margin_number", "normalize": true },
{ "signal": "fieldBoost", "weight": 0.5, "field": "sold_30d_number", "normalize": true },
{ "signal": "inStockBoost", "weight": 0.4, "field": "stock_default" },
{ "signal": "recency", "weight": 0.3, "field": "publishedAt", "halfLifeDays": 60 }
],
"tieBreaker": "sku",
"explain": true
}
}
rankScore = 1.0·relevance + 0.6·margin + 0.5·sold_30d + 0.4·inStock + 0.3·recency

Zero weights are dropped

A term with weight: 0 is removed before scoring. If every term is 0, the query runs unranked and skips the rerank window entirely — no rerank runs, rankScore comes back null, and a context or nearestTo sent beside it no longer ranks either. Turning a signal off by zeroing it is fine; zeroing all of them silently disables ranking.

Normalization

normalize applies min–max normalization across the rerank window, so signals on wildly different scales can share a weight. A term whose value is the same across the window normalizes to 0. The default depends on the signal — set normalize explicitly to override.

Signal normalize default Why
relevance on unbounded magnitude
fieldBoost on unbounded magnitude
tasteCosine off already roughly 0–1
recency off already roughly 0–1
inStockBoost off already roughly 0–1

Because normalization is computed over the window, the same item can score differently under different rerankWindow sizes. That is expected, not a bug.

Multi-valued fields are collapsed

Anything with several values per item — fields under variants (such as price_* / stock_*), fields under shortcuts, or a repeatable component — is collapsed to one value before scoring. The direction is fixed and cannot be overridden:

Signal Collapses to Rationale
fieldBoost lowest the “from” price a shopper is shown
inStockBoost highest buyable in any variant counts as in stock
recency highest the most recent date wins

To boost on another end of a product’s prices, use the single-valued defaultVariantPrice_<id>, lowestVariantPrice_<id> or highestVariantPrice_<id> fields.

rankScore and rankExplain

rankScore on each hit is the raw, un-normalized value the hits were ordered by — Σ weight × term under rankBy, the summed per-vocabulary cosine under context or nearestTo. It is the actual sort key, which score is not guaranteed to be. rankScore is null whenever no rerank ran: no rankBy, context or nearestTo, or every rankBy term dropped.

With explain: true each hit carries one rankExplain entry per scored term, in rankBy.terms order. A weight: 0 term has no entry, so join on index, never on an entry’s position in the list:

RankExplainEntry { signal: RankBySignal, index: Int, contribution: Float }

index is the term’s position in the terms you sent. It disambiguates a repeated signal — two fieldBoost terms, say — and the contributions sum to rankScore by construction, which makes it a usable self-check.

{
"name": "Cobán Dark",
"rankScore": 1.71,
"rankExplain": [
{ "signal": "relevance", "index": 0, "contribution": 0.42 },
{ "signal": "fieldBoost", "index": 1, "contribution": 0.51 },
{ "signal": "fieldBoost", "index": 2, "contribution": 0.3 },
{ "signal": "inStockBoost", "index": 3, "contribution": 0.4 },
{ "signal": "recency", "index": 4, "contribution": 0.08 }
]
}

rankExplain is populated only with explain: true, and is null on the userTaste-only and nearestTo-only paths, which have no terms.

Ship explain: true behind a merchandiser flag, not in the hot storefront path — it is a tuning tool.

The rerank window

options.rerankWindow sets how many documents a windowed query reranks: the first N under the query’s effective sort — the sorting you sent, or itemId descending when you sent none. Those N are scored and re-sorted among themselves. That is not the N best matches unless you ask for it: sorting: { score: desc } selects candidates by relevance. On a catalogue larger than the window, a rankBy with no sorting never sees the rest.

  • default 500
  • hard server cap 2000; a larger value is clamped
  • rerank cost is per candidate, so a larger window costs more
search(
term: "espresso",
rankBy: $rankBy,
sorting: { score: desc },
options: { rerankWindow: 1000 }
) { hits { ... on product { name rankScore } } }

Which queries are windowed. context.userTaste or nearestTo with no rankBy and no sorting are ranked over the whole result set: no window applies, skip and after/before page the ranked set as usual (summary.endToken is the cursor for the next page), and rerankWindow only caps nearestTo.k. Every other ranked query takes the window:

  • any query with a rankBy
  • any query with a sorting, including Folder.children and Topic.items, which default to sorting: { position: asc } — pass sorting: {} to clear it
  • autocomplete
  • a userTaste weight below zero, or an anchor vector holding one
  • more than about 800 weights across the vocabularies
  • an item in scope whose taste holds a negative weight
  • an index from an older ignition; igniteDiscoApi(stacks: opensearch) rebuilds it for the whole-set path

Paging happens inside the window. On a windowed query skip offsets into the reranked window. A skip past the window returns no hits, while totalHits still counts every match and summary.hasMoreHits reports false. Size the window for the depth you intend to page, not just for the first page.

after/before move the window, not the page. A hit’s token is its position under the effective sort, not its reranked rank, so a cursor taken from a reranked page selects the next N documents past that position and reranks those. Items the page pulled up from later positions come back again, and items from earlier positions that missed the page are never reached. Use skip + limit on windowed queries.

Vocabulary & Taste Authoring (Core API)

Everything on this page runs against the Core API at https://api.crystallize.com/@<tenant>/core with an access token pair. Vocabulary and index mutations are not on the PIM API.

1. Design the vocabulary

Decide what a person could plausibly have a preference about. That is your dimension list. Two tests:

  • Could a shopper move a slider for it? Roast level, yes. SKU prefix, no. Dimensions nobody has taste about add noise to every score.
  • Does assignment order mean anything? If the first flavour listed is the signature note, give the dimension a positional weight list. If not, one weight is enough.

Keep genuinely different concerns in separate vocabularies. What a coffee tastes like and where it comes from are questions a shopper may weigh differently, so they are two vocabularies rather than five dimensions in one. Vocabularies are scored independently and summed, so splitting a concern out is what lets a shopper — and you, via a per-vocabulary tasteCosine term — weight it on its own.

taste roast [1.0] one roast level, order meaningless
flavor [1.0, 0.6, 0.3] ordered: the signature note dominates
body [0.8] matters, but less than roast
origin region [1.0]
process [1.0, 0.5]

Values become the second half of every key, so keep them slug-shaped and stable: flavor:blackcurrant, not flavor:Black Currant. Renaming a value later means rewriting every item that used it and re-indexing.

Business dimensions are welcome

A vocabulary does not have to be about taste in the narrow sense. Margin band, stock depth, seasonality, audience or tier all work as dimensions when you want them inside a similarity score. Use rankBy instead when they should stay separate and be weighted on their own — that is usually the better default for anything you already hold as a number on the product.

Weights are positional

A dimension’s weight is a list. One element means every entry in that dimension weighs the same. More than one means entry i takes weight[min(i, length - 1)], clamping to the last element once you run past the end.

weight: [1.0, 0.6, 0.3] 1st entry 1.0
2nd entry 0.6
3rd entry 0.3
4th entry 0.3 (clamped to last)

Use the positions, or tastes collapse. When every item carries several entries of one dimension at weight 1, every shopper matches every item about equally and the house boosts decide the order. In one build, decaying the secondary entries ([1.0, 0.5, 0.35]) made all 16 profile × category listings differ from the unpersonalised one.

Broad entries dilute the cosine. A spare part that fits 200 machines carries 200 machine: keys, so its cosine to a shopper with one machine is about 1/√200, while an item with one key scores about 0.8. Ranking inside such a category still works (everything is diluted alike), but a mixed rail needs its own query for those items, with a filter instead of a taste.

2. Create the vocabulary

upsertVocabulary creates or replaces a vocabulary in full. It is a full replace, not a patch — send the whole dimension list every time. Any dimension you omit is gone, and the entries items still hold for it are skipped, without error, the next time their vectors are built.

A vocabulary needs at least one dimension, dimension ids must be unique, and every weight must be positive.

There is no deleteVocabulary, and no query lists vocabularies. upsertVocabulary with an empty dimension list fails (“Cannot return null for non-nullable field GraphqlVocabulary.name”) and deletes nothing, so every vocabulary you create stays a value of the tenant’s enum for good. Do not test with throwaway vocabularies on a real tenant.

mutation UpsertVocabulary($input: UpsertVocabularyInput!) {
upsertVocabulary(input: $input) {
name
dimensions {
id
weight
}
lastUpdated
}
}
{
"input": {
"name": "taste",
"dimensions": [
{ "id": "roast", "weight": [1.0] },
{ "id": "flavor", "weight": [1.0, 0.6, 0.3] },
{ "id": "body", "weight": [0.8] }
]
}
}

Schema:

UpsertVocabularyInput { name: String!, dimensions: [GraphqlInputVocabularyDimension!]! }
GraphqlInputVocabularyDimension { id: String!, weight: [Float!]! }
GraphqlVocabulary { name: String!, dimensions: [GraphqlVocabularyDimension!]!, lastUpdated: Date }

Discovery exposes the name normalized for GraphQL (coffee-taste becomes the enum value coffeeTaste), and upsertVocabulary refuses a new name that normalizes to the same value as an existing one. Core keeps taking the name as you wrote it.

Read it back with the vocabulary query — useful as an idempotency check before a bulk re-author:

query {
vocabulary(name: "taste") {
name
lastUpdated
dimensions {
id
weight
}
}
}

3. Attach taste to items

setItemTaste writes the ordered entries for one item, one language, one vocabulary, replacing what that vocabulary held on the item. Two vocabularies means two calls per item.

Write one item’s vocabularies and languages one after another. Concurrent setItemTaste calls on the same item lose writes with no error: each call reads, changes and writes the item’s draft, and the last write wins. With three vocabularies × two languages in parallel, one item kept a single vocabulary; another build found 34 (item, language) pairs missing a whole vocabulary after eight writes at once. Seen on three tenants. Run items in parallel, never the calls for one item, and read the taste back afterwards (below).

mutation SetItemTaste($input: SetItemTasteInput!) {
setItemTaste(input: $input) {
__typename
... on Product {
id
}
... on Folder {
id
}
... on Document {
id
}
... on BasicError {
errorName
message
}
}
}

Every error member of the union implements the BasicError interface, so one fragment covers all of them — errorName tells you which one you got. Spelling out individual error types is only worth it when you branch on a field the interface does not carry.

{
"input": {
"itemId": "<ITEM_ID>",
"language": "en",
"vocabulary": "taste",
"entries": [
{ "key": "roast:light" },
{ "key": "flavor:berry" },
{ "key": "flavor:blackcurrant" },
{ "key": "flavor:caramel" },
{ "key": "body:light", "weight": 1.2 }
]
}
}

Schema:

SetItemTasteInput { itemId: String!, language: String!, vocabulary: String!,
entries: [GraphqlInputItemTasteEntry!]! }
GraphqlInputItemTasteEntry { key: String!, weight: Float }
SetItemTasteResult (union) Product | Folder | Document
| ItemNotFoundError | ExperimentalFeaturesNotAvailableError
| UnauthorizedError | UnknownError

Documents and folders take taste too, and rank like products: banner documents with taste derived from their topics, filtered by itemId and ranked with tasteCosine and a context, came back in a different order per shopper after one ignition. A numeric priority on the document shape became a TenantRankByField and works as a small fieldBoost tie-break.

ExperimentalFeaturesNotAvailableError is a standard member of Core result unions, not a signal about vectors: nothing in vocabulary or taste authoring raises it, and ranking is switched on by the ignition in step 5. The validation rejections below come back as UnknownError, with the reason in message.

Order is the input to positional weights

Entries are read in array order, per dimension. Above, flavor:berry takes 1.0, flavor:blackcurrant 0.6 and flavor:caramel 0.3. The optional per-entry weight overrides the vocabulary weight for that entry only — and still consumes its positional slot, so it does not shift the entries that follow. Overrides are not range-checked: keep them positive, because a negative one puts every query that reaches the item on the windowed path.

The key format is validated

Every key is <dimensionId>:<value>. Everything before the first colon must be a declared dimension in that vocabulary, and the vocabulary must exist. Any of these mistakes rejects the whole call, so there are no partial writes — fix it and resend the full set of entries.

Bad entry Rejection message
{ key: "chocolate" } Malformed taste entry key "chocolate": expected "<dimensionId>:<value>"
{ key: "mood:cozy" } Unknown dimension "mood" in vocabulary "taste". Known dimensions: roast, flavor, body
vocabulary: "nope" Vocabulary "nope" not found for this tenant

Read taste back

Core exposes taste on the item, which is the reliable way to verify a bulk author before indexing. It is not exposed on Discovery hits. taste is on Item, not on GetItemResult, so the inline fragment is required; without it the query fails validation.

query {
item(id: "<ITEM_ID>", language: "en") {
... on Item {
taste {
vocabulary
entries {
key
weight
}
}
}
}
}
GraphqlItemTaste { vocabulary: String!, entries: [GraphqlItemTasteEntry!]! }
GraphqlItemTasteEntry { key: String!, weight: Float }

After a bulk run, read every item back per language and rewrite only the vocabularies that are missing or differ. Even sequential runs lost the odd write in one build, so make this repair step part of the job.

Observed both ways: verify on your tenant

Claim Seen Not seen
setItemTaste empties variant components once (2026-09): variant chunks and numerics gone from draft four later tenants, variants checked
Item taste is per language one tenant: a taste written in no was absent in en another: written in no, read the same in en

So keep two checks rather than a rule: read the variant components back after the taste step on a catalogue whose variants carry components, and write taste for every language you serve (it costs calls, not correctness). Taste does survive a translation: after translating and publishing in no, a tasteCosine query in no scored the same as in en.

Keep one source of truth

If you also assign topics for the same concepts, derive the taste entries from the topic assignments — for example by storing the key in the topic’s meta — rather than maintaining two parallel lists. See [[taxonomy]] for the topic side.

4. Publish

setItemTaste writes to the draft version. Discovery serves the published version by default. If your items were published before you attached taste, publish them again or the served documents carry no vectors.

mutation Publish($id: ID!, $language: String!) {
publishItem(id: $id, language: $language) {
__typename
... on PublishInfo {
versionId
}
... on BasicError {
errorName
message
}
}
}

Publish per item and per language. publishItem and publishItems both run in the background, so neither return is proof that the items are published yet — index right after them and the index may read the old versions. Wait for item(id:, language:, versionLabel: published) to show the new taste first.

On a tenant already served for ranking, each publish re-indexes that item in the background, vectors included, so a taste change needs no ignition.

Skipping this step produces no error. Queries still return results, and the order may even change — it just has no relation to taste. The check in step 6 is the only thing that catches it.

5. Index

igniteDiscoApi rebuilds the tenant’s Discovery index and materializes the vectors. Run it the first time, and again after any upsertVocabulary: new weights reach existing items only at an index run, and a new vocabulary only joins the Discovery enum then.

Only a tenant admin can ignite, and a tenant runs one ignition at a time. Either refusal comes back as a BasicError. The Discovery page in the app’s settings runs the same mutation, with stacks: opensearch.

Ignite last. Run it once the shapes exist, each with at least one component, and the content is published, not as an early setup step. A tenant with no shapes that Discovery can index is refused: the task ends in error.

Pass stacks: opensearch. The argument is optional in the schema but it selects which index stack is built, and vector ranking is only served from the opensearch stack. Without it, a tenant not yet served gets a working Discovery index, no ranking arguments and no error. both builds the stack but leaves reads where they are, so it does not turn ranking on either. A tenant already served for ranking refuses an ignition that leaves the stack out: the task ends in error.

mutation Index {
igniteDiscoApi(stacks: opensearch) {
__typename
... on BulkTaskIgnition {
id
type
status
createdAt
}
... on BasicError {
errorName
message
}
}
}
igniteDiscoApi(stacks: DiscoIgnitionStacks): IgnitionBulkTaskResult!
DiscoIgnitionStacks = atlasSearch | both | opensearch
IgnitionBulkTaskResult (union) BulkTaskIgnition | ExperimentalFeaturesNotAvailableError
| InvalidIdError | UnauthorizedError | UnknownError

The mutation is asynchronous. Poll the returned task until it reports complete, then allow a few minutes for Discovery to propagate the new index.

query Task($id: ID!) {
bulkTask(id: $id) {
... on BulkTask {
id
status # pending, started, complete, error
info # on error, info.traces says why
}
}
}

error is blocking. Read info.traces, fix what it names and only then ignite again. Re-running an ignition that failed, unchanged, fails the same way. Before reporting success, probe Discovery itself:

{
__typename
}

Anything but {"data":{"__typename":"Query"}} means the tenant is not serving, whatever the task said.

From then on the tenant’s Discovery schema includes context, rankBy and nearestTo, and every vocabulary you created becomes a value of the TenantVocabularyIdentifier enum, under its normalized name. A vocabulary is only a valid enum value after the next index run — until then, queries referencing it fail schema validation.

The enum is not the end of the wait. In one build Vocabulary <name> not found came back for about five minutes after the task said complete, while TenantVocabularyIdentifier already listed the value; in others the enum and lastIndexCompletedAt themselves stayed stale for minutes, and one vocabulary scored 0 for a while as the others ranked. Probe with a real context query per vocabulary, and check rankScore per vocabulary, before concluding that the vectors are wrong.

Before a tenant has any indexed vocabulary, the same arguments (nearestTo.vocabulary, userTaste.vocabulary) are typed String, and a query fails with Vocabulary <name> not found. After the index run they take the enum: vocabulary: taste, not vocabulary: "taste". A query or a typed variable written for one form fails on the other, so check the type with introspection (see SKILL.md) before you hardcode either.

6. Verify

Two checks, in this order. Both are cheap and both catch a silent failure.

# a) Did the index actually rebuild? The timestamp must have moved.
{
search {
summary {
profiling {
lastIndexCompletedAt
}
}
}
}
b) Run the same query with and without `context` and compare the order.
If the two match, no vectors reached the index — go back to step 4 (publish), then step 5 (index).

Authoring at scale

setItemTaste is one call per item per vocabulary, so a full catalogue is a bulk job. Mass operations have no taste intent, so drive it from a script over [[js-api-client]]. The item/publish intent of [[mass-operations]] covers the publish step. Index once at the end rather than per item. Order matters: vocabulary → taste → publish → index.


Crystallize AI