--- title: Use context mappings slug: q3bc0472 canonical_url: https://docs.coveo.com/en/q3bc0472/ collection: coveo-for-commerce source_format: adoc --- # Use context mappings Commerce API query-time requests include a `context` object for behavioral signals such as the current URL, cart contents, and user information. With _context mappings_, you can extend this context with custom fields that your implementation sends at query time. Using the Context Mappings API, you define a key, a data type, and one or more destinations for each mapping. At query time, you include the custom field values in your Commerce API requests. The Commerce API validates each value against its configured type and routes it to the specified destinations automatically, such as the [query pipeline](https://docs.coveo.com/en/180/) context, [Coveo Machine Learning](https://docs.coveo.com/en/188/) context, or [field aliases](https://docs.coveo.com/en/q1q94008/). Context mappings are useful for commerce use cases such as: * Filtering or ranking products based on data that isn't part of your [catalog data](https://docs.coveo.com/en/obcf0333/) (for example, fitment lists or customer entitlements). * Resolving dynamic pricing using [field aliases](https://docs.coveo.com/en/q1q94008/) based on a store identifier or customer group. * Influencing [Coveo ML](https://docs.coveo.com/en/188/) models with session-level signals, such as a shopper's declared intent. Context mappings are scoped to a [tracking ID](https://docs.coveo.com/en/o8rb0139/) and can be used in the following Commerce API requests: * [Search](https://docs.coveo.com/en/103#tag/Search/operation/search) * [Product suggestions](https://docs.coveo.com/en/103#tag/Search/operation/productSuggest) * [Query suggestions](https://docs.coveo.com/en/103#tag/Search/operation/querySuggest) * [Listings](https://docs.coveo.com/en/103#tag/Listings/operation/getListing) * [Recommendations](https://docs.coveo.com/en/103#tag/Recommendations/operation/recommendations) ## Prerequisites To use context mappings, you need: * An active [Coveo organization](https://docs.coveo.com/en/185/) with the Commerce extension. * A [tracking ID](https://docs.coveo.com/en/o8rb0139/) configured through a [storefront](https://docs.coveo.com/en/p33g0410/) association. * The following [privileges](https://docs.coveo.com/en/228/) in your [Coveo organization](https://docs.coveo.com/en/185/): [cols="3",options="header"] |=== |Action |Service - Domain |Required access level |View context mappings |Commerce - Merchandising Hub |View |Create, update, or delete context mappings |Commerce - Merchandising Hub |Edit |=== > **Note** > > Commerce API Context mappings is currently in open beta. ## How context mappings work The context mapping workflow has two phases: configuration and query time. ### Phase 1: Configuration phase > **Important** > > Context mappings are configured through the Commerce API. > They aren't currently manageable in the [Coveo Merchandising Hub (CMH)](https://docs.coveo.com/en/o5290573/). You use the Context Mappings API to define the custom fields you want to accept at query time. Each context mapping specifies: * A **key**, which is the name of the custom field (such as `storeId`, `fitmentProducts`, or `shoppingIntent`). * A **type**, which defines the data type the field accepts. Accepted types are: [cols="2",options="header"] |=== |Type |Description |`STRING` |A single string value. |`NUMBER` |A single numeric value. |`BOOLEAN` |A Boolean value (`true` or `false`). |`PRODUCT_LIST` |An array of product identifiers (strings) available in your [catalog entity](https://docs.coveo.com/en/3143/). Use this type to represent a list of products, such as fitment parts or a wish list. |=== * One or more **destinations**, which specify where the Commerce API routes the data at query time. Supported destinations are: [cols="1,2",options="header"] |=== |Destination |Description |`QUERY_PIPELINE_CONTEXT` |Routes the value into the [query pipeline](https://docs.coveo.com/en/180/) context, where it becomes available through the `$context` [query pipeline language (QPL)](https://docs.coveo.com/en/235/) object. You can then reference the value in [query pipeline rules](https://docs.coveo.com/en/236/) such as filter rules, ranking expressions, and pipeline [conditions](https://docs.coveo.com/en/2793/). Use this destination when you need deterministic, rule-based control over query behavior. |`FIELD_ALIASES` a|Routes the value to a [field alias](https://docs.coveo.com/en/q1q94008/), enabling dynamic resolution of [dictionary field](https://docs.coveo.com/en/2036/) keys at query time. Use this destination for use cases like store-specific or customer-group-specific pricing, where the value to display depends on a runtime parameter. The Commerce API resolves the appropriate dictionary field entry based on the context value and returns it in the query results. > **Note** > > This destination can't be used for the [Query suggestions](https://docs.coveo.com/en/103#tag/Search/operation/querySuggest) endpoint. |`ML_CONTEXT` |Routes the value to the [Coveo ML](https://docs.coveo.com/en/188/) context, where ML models factor it into their outputs automatically. ML models use context values like intelligent [query ranking expressions (QREs)](https://docs.coveo.com/en/1472/): they learn from usage analytics data to boost results that match both the query and the context. The models don't filter results based on context; they adjust relevance scores. Use this destination for signals like shopping intent or customer segment, where the relationship between context and relevance is best learned from behavioral data rather than hardcoded in rules. |=== ### Phase 2: Query-time phase At query time, you pass the custom field values in the `context.custom` object of your Commerce API request body (search, listing, or recommendation). The Commerce API validates the payload against the configured mappings and routes each value to its destinations. See [Sending custom context at query time](#send-custom-context-at-query-time) for details on how to format the `context.custom` object in your requests. ## Create a context mapping To create a context mapping, use the following endpoint: ```http POST /rest/organizations//commerce/v2/tracking-ids//context-mappings HTTP/1.1 ``` Where: * `` is the base URL of the [Coveo Platform](https://docs.coveo.com/en/186/) instance that hosts your organization (for example, `https://platform.cloud.coveo.com`). * `` is the unique identifier of your [Coveo organization](https://docs.coveo.com/en/185/). To find your organization ID, see [Find your organization ID](https://docs.coveo.com/en/n1ce5273/). * `` is the unique identifier of the target [tracking ID](https://docs.coveo.com/en/o8rb0139/). Example request body: ```json { "key": "", // <1> "type": "", // <2> "destinations": [ { "attribute": "", // <3> "fieldAlias": "", // <4> "fieldSource": "" // <5> } ] } ``` <1> The name of the custom context field. This is the key you'll use in the `context.custom` object when sending Commerce API requests. <2> The data type of the value the field accepts (`STRING`, `NUMBER`, `BOOLEAN`, or `PRODUCT_LIST`). <3> The destination where the Commerce API routes the data at query time (`QUERY_PIPELINE_CONTEXT`, `ML_CONTEXT`, or `FIELD_ALIASES`). <4> (For the `FIELD_ALIASES` destination only). The alias under which the resolved field value becomes accessible in query results. This can be a static name (for example, `price_dict`) or include the `{% raw %}{{contextValue}}{% endraw %}` placeholder to make the alias name dynamic (for example, `{% raw %}price_store_{{contextValue}}{% endraw %}`). A dynamic alias is useful when you want the UI or a query function to identify which specific key was resolved. <5> (For the `FIELD_ALIASES` destination only). A template that tells the Commerce API which indexed field entry to resolve. Use the `{% raw %}{{contextValue}}{% endraw %}` placeholder where you want the Commerce API to insert the value the shopper sends at query time. For example, if `fieldSource` is `{% raw %}price_dict.{{contextValue}}{% endraw %}` and the shopper sends `storeId: "10010"`, the Commerce API resolves the dictionary field entry `price_dict.10010` and returns the value stored there. Response The response to a successful creation request (`201 Created`) mirrors the context mapping definition, including its key, type, and destinations. ### Destination examples **Route data to the query pipeline context**
Details The following example creates a context mapping that routes data into the [query pipeline](https://docs.coveo.com/en/180/) context, where it can be referenced in [query pipeline rules](https://docs.coveo.com/en/236/). ```json { "key": "fitmentProducts", "type": "PRODUCT_LIST", "destinations": [ { "attribute": "QUERY_PIPELINE_CONTEXT" } ] } ``` Once a value is routed to the [query pipeline](https://docs.coveo.com/en/180/) context, you can reference it in [query pipeline language (QPL)](https://docs.coveo.com/en/235/) statements using the `$context` [object](https://docs.coveo.com/en/1449#qpl-objects). Depending on the statement type, use either dot notation or bracket notation: * In query expressions: `$context.KEY` (for example, `$qre(expression: @audience==$context.customerSegment, modifier: 100)`) * In pipeline conditions and statements: `$context[KEY]` (for example, `$context[loyaltyMember] is true`) [example] **Product fitment filtering (`PRODUCT_LIST`)**
A parts retailer wants to filter search and listing results to only show parts that are compatible with a shopper's selected vehicle. The implementer: . Creates a `fitmentProducts` context mapping with a `PRODUCT_LIST` type and a `QUERY_PIPELINE_CONTEXT` destination. . Adds a filter rule in the [query pipeline](https://docs.coveo.com/en/180/): `@ec_product_id==$context.fitmentProducts`. . Sends the list of compatible product IDs in the `context.custom.fitmentProducts` field [at query time](#send-custom-context-at-query-time): ```json { "context": { "custom": { "fitmentProducts": ["SKU-001", "SKU-002", "SKU-003"] } } } ``` ##### **Pipeline routing by contract status (`BOOLEAN`)** A B2B distributor uses a single storefront for all customers, but some customers have negotiated contracts that entitle them to exclusive products and pricing rules. The distributor wants to route contract customers to a dedicated [query pipeline](https://docs.coveo.com/en/180/) that applies contract-specific ranking and filtering rules. This distinction comes from the customer's login session, which Coveo doesn't have access to. A context mapping supplies this flag so a pipeline condition can act on it. The implementer: . Creates a `contractCustomer` context mapping with a `BOOLEAN` type and a `QUERY_PIPELINE_CONTEXT` destination. . Defines a pipeline condition on the contract [query pipeline](https://docs.coveo.com/en/180/): `$context[contractCustomer] is true`. . Sends the flag in the `context.custom.contractCustomer` field [at query time](#send-custom-context-at-query-time), based on the customer's login session: ```json { "context": { "custom": { "contractCustomer": true } } } ``` #### .Route data to field aliases
Details [NOTE] **Note**
This destination can't be used for the [Query suggestions](https://docs.coveo.com/en/103#tag/Search/operation/querySuggest) endpoint. ##### The following example creates a context mapping that resolves a [field alias](https://docs.coveo.com/en/q1q94008/) dynamically based on a store identifier. A [field alias](https://docs.coveo.com/en/q1q94008/) maps a custom name to a specific key within a [dictionary field](https://docs.coveo.com/en/2036/) in the index. Dictionary fields store multiple key-value pairs under a single [field](https://docs.coveo.com/en/200/). For example, a `price_dict` dictionary field might contain keys like `10010`, `10020`, and `10030`, each holding the price for a different store. With the `FIELD_ALIASES` destination, the Commerce API resolves the correct dictionary field entry at query time based on a context value the shopper provides (such as a store identifier or customer group code). ```json { "key": "storeId", "type": "STRING", "destinations": [ { "attribute": "FIELD_ALIASES", // <1> "fieldAlias": "price_dict", // <2> "fieldSource": "price_dict.{% raw %}{{contextValue}}{% endraw %}" // <3> } ] } ``` <1> The `FIELD_ALIASES` destination enables dynamic field resolution. <2> `fieldAlias` is the field name under which the resolved value appears in query results. You can also use the `{% raw %}{{contextValue}}{% endraw %}` placeholder in `fieldAlias` to make the alias name dynamic (for example, `{% raw %}price_store_{{contextValue}}{% endraw %}`). This is useful when you want the UI or a [query function](https://docs.coveo.com/en/232/) to identify which specific dictionary key was resolved. <3> `fieldSource` tells the Commerce API which indexed dictionary field entry to resolve. It must follow the `field.subkey` pattern, where `{% raw %}{{contextValue}}{% endraw %}` is a placeholder that the Commerce API replaces with the value the shopper sends at query time. In this example, if the shopper sends `storeId: "10010"` at query time, the Commerce API resolves `price_dict` to the dictionary field entry `price_dict.10010` and returns the price stored there. **Example** A multi-location retailer has store-specific prices indexed as entries in a dictionary field (`price_dict`). The retailer wants to display the correct price based on the shopper's selected store. The implementer: . Creates a `storeId` context mapping with a `STRING` type and a `FIELD_ALIASES` destination. . Sends the store identifier in the `context.custom.storeId` field [at query time](#send-custom-context-at-query-time). The Commerce API resolves the dictionary field entry and returns the value under the `price_dict` field in the query results: ```json { "context": { "custom": { "storeId": "10010" } } } ``` #### .Route data to the ML context
Details The following example creates a context mapping that sends a string value to the [Coveo ML custom context](https://docs.coveo.com/en/3389/). ```json { "key": "shoppingIntent", "type": "STRING", "destinations": [ { "attribute": "ML_CONTEXT" } ] } ``` When a value reaches the ML context, [Coveo ML](https://docs.coveo.com/en/188/) [models](https://docs.coveo.com/en/1012/) automatically factor it into their outputs. The models learn from usage analytics data to boost results that correlate with both the query and the context value. Unlike [query pipeline rules](https://docs.coveo.com/en/236/), ML context doesn't require you to define explicit rules. The models adjust relevance scores based on learned patterns, but they don't filter results out. For best results, keep the number of possible values per key small, and only send your most meaningful signals. High-cardinality data (for example, unique user IDs or session tokens) dilutes the statistical patterns that models rely on and provides little relevance benefit. [example] **Example**
A sporting goods retailer lets shoppers declare their shopping intent (for example, "fishing" or "camping"). The retailer wants ML models to use this signal when learning relevance patterns. The implementer: . Creates a `shoppingIntent` context mapping with a `STRING` type and an `ML_CONTEXT` destination. . Sends the shopper's declared intent in the `context.custom.shoppingIntent` field [at query time](#send-custom-context-at-query-time): ```json { "context": { "custom": { "shoppingIntent": "fishing" } } } ``` Over time, the ML models learn that shoppers with intent "fishing" tend to interact with certain products, and they boost those products accordingly. ##### ==== **Route data to multiple destinations**
Details A single context mapping key can route data to multiple destinations simultaneously. The following example sends a string value to both the [query pipeline](https://docs.coveo.com/en/180/) and [Coveo Machine Learning](https://docs.coveo.com/en/188/) contexts: ```json { "key": "shoppingIntent", "type": "STRING", "destinations": [ { "attribute": "ML_CONTEXT" }, { "attribute": "QUERY_PIPELINE_CONTEXT" } ] } ``` [example] **Segment-specific ML models (`STRING`)**
A marketplace serves both B2B and B2C customers from the same [storefront](https://docs.coveo.com/en/p33g0410/). The two audiences have very different browsing patterns and product preferences, so a single [Coveo ML](https://docs.coveo.com/en/188/) model doesn't produce relevant results for both. The marketplace wants to train separate ML models for each segment and route queries to the right model based on the customer type. > **Note** > > This pattern applies to [ART](https://docs.coveo.com/en/1013/), [QS](https://docs.coveo.com/en/1015/), [PQS](https://docs.coveo.com/en/m1ol5526/), and [DNE](https://docs.coveo.com/en/2907/) models. The implementer: . Creates a `customerSegment` context mapping with a `STRING` type and both `ML_CONTEXT` and `QUERY_PIPELINE_CONTEXT` destinations. ** The ML context is required so that models can use the segment value for training. ** The [query pipeline](https://docs.coveo.com/en/180/) context is required so that pipeline [conditions](https://docs.coveo.com/en/2793/) can route queries to the correct model. . Creates two separate ML models, each with a `searchEventFilter` that restricts training data to one segment (for example, `(c_context_customerSegment=~'b2b')` for the B2B model). . Associates each model with the query pipeline using a [condition](https://docs.coveo.com/en/2793/) that matches the segment value (for example, `$context[customerSegment] is "b2b"` for the B2B model). . Sends the customer segment in the `context.custom.customerSegment` field [at query time](#send-custom-context-at-query-time), based on the customer's account type: ```json { "context": { "custom": { "customerSegment": "b2b" } } } ``` This approach provides maximum isolation between segments, but requires maintaining separate models for each segment value. ##### **Relevance boost with ML learning (`STRING`)** A sporting goods retailer lets shoppers declare their shopping intent (for example, "fishing" or "camping"). The retailer wants [Coveo ML](https://docs.coveo.com/en/188/) models to learn from this signal over time, but also wants an immediate relevance boost while the models are still training. The implementer: . Creates a `shoppingIntent` context mapping with both `ML_CONTEXT` and `QUERY_PIPELINE_CONTEXT` destinations (as shown above). . Adds a ranking expression in the [query pipeline](https://docs.coveo.com/en/180/) that gives an immediate boost when the intent matches a product category: `$qre(expression: @ec_category==$context.shoppingIntent, modifier: 100)`. . Sends the shopper's declared intent in the `context.custom.shoppingIntent` field [at query time](#send-custom-context-at-query-time): ```json { "context": { "custom": { "shoppingIntent": "fishing" } } } ``` #### == List context mappings To list all context mappings for a [tracking ID](https://docs.coveo.com/en/o8rb0139/), use the following endpoint: ```http GET /rest/organizations//commerce/v2/tracking-ids//context-mappings HTTP/1.1 ``` The response to a successful request includes the details of all context mappings configured for the specified [tracking ID](https://docs.coveo.com/en/o8rb0139/). Example response: ```json [ { "key": "fitmentProducts", "type": "PRODUCT_LIST", "destinations": [ { "attribute": "QUERY_PIPELINE_CONTEXT" } ] }, { "key": "shoppingIntent", "type": "STRING", "destinations": [ { "attribute": "ML_CONTEXT" }, { "attribute": "QUERY_PIPELINE_CONTEXT" } ] }, { "key": "storeId", "type": "STRING", "destinations": [ { "attribute": "FIELD_ALIASES", "fieldAlias": "price_dict", "fieldSource": "price_dict.{% raw %}{{contextValue}}{% endraw %}" } ] } ] ``` ## Get a context mapping To retrieve a specific context mapping by key, use the following endpoint: ```http GET /rest/organizations//commerce/v2/tracking-ids//context-mappings/ HTTP/1.1 ``` Where `` is the context mapping key (for example, `storeId`). A successful response (`200 OK`) returns the context mapping definition, including its key, type, and destinations. ## Update a context mapping To update an existing context mapping, use the following endpoint: ```http PUT /rest/organizations//commerce/v2/tracking-ids//context-mappings/ HTTP/1.1 ``` Where `` is the context mapping key to update. For example, to add a `QUERY_PIPELINE_CONTEXT` destination to an existing `shoppingIntent` mapping: Example request body: ```json { "key": "shoppingIntent", "type": "STRING", "destinations": [ { "attribute": "ML_CONTEXT" }, { "attribute": "QUERY_PIPELINE_CONTEXT" } ] } ``` A successful response (`200 OK`) returns the updated context mapping definition. ## Delete a context mapping To delete a context mapping, use the following endpoint: ```http DELETE /rest/organizations//commerce/v2/tracking-ids//context-mappings/ HTTP/1.1 ``` Where `` is the context mapping key to delete. A successful response (`204 No Content`) indicates that the context mapping has been deleted. ## Send custom context at query time Once you've configured your context mappings, include the custom field values in the `context.custom` object of your Commerce API requests. The `context.custom` object is supported in all Commerce API query-time endpoints: * [Search](https://docs.coveo.com/en/103#tag/Search/operation/search) * [Listings](https://docs.coveo.com/en/103#tag/Listings/operation/getListing) * [Recommendations](https://docs.coveo.com/en/103#tag/Recommendations/operation/recommendations) * [Product suggestions](https://docs.coveo.com/en/103#tag/Search/operation/productSuggest) * [Query suggestions](https://docs.coveo.com/en/103#tag/Search/operation/querySuggest) The following example shows a search request that includes custom context fields for each supported type: ```json { "trackingId": "sports", "language": "en", "country": "US", "currency": "USD", "clientId": "58bb4b98-1daa-4767-8c15-90a0ea67645c", "query": "kayak", "context": { "view": { "url": "https://sports.barca.group" }, "custom": { // <1> "fitmentProducts": ["SKU-001", "SKU-002", "SKU-003"], // <2> "shoppingIntent": "fishing", // <3> "storeId": "10010", // <4> "loyaltyTier": 3 // <5> } } } ``` <1> The `custom` object contains the context mapping values. Keys must match the `key` values defined in your context mappings. <2> `fitmentProducts` is a `PRODUCT_LIST` type, so the value is an array of product identifier strings. <3> `shoppingIntent` is a `STRING` type, so the value is a single string. <4> `storeId` is a `STRING` type, so the value is a single string. <5> `loyaltyTier` is a `NUMBER` type, so the value is a numeric value. > **Tip** > > If you're building your commerce interface with the [Coveo Headless library](https://docs.coveo.com/en/lcdf0493/), you can use the `setCustom()` controller in the Commerce Engine to set custom context values. > The controller automatically includes the custom context in all subsequent Commerce API requests. > See [Headless for commerce](https://docs.coveo.com/en/o52e9091/) for details. > **Important** > > The Commerce API validates the data types of the values you send against the configured context mappings. > If a value doesn't match the expected type (for example, you send a string for a `NUMBER` field), the API drops the key and none of its destinations receive the value. > The request itself still succeeds.