Sending Custom Context Information

Coveo JavaScript Search Framework (September 2016)

The Coveo™ JavaScript Search Framework allows you to include custom context information along with each search request and usage analytics event.

You can use this information to create custom dimensions, which you can then leverage in usage analytics reports. Coveo Machine Learning (Coveo ML) models can also take advantage of custom context information to promote relevant content. Finally, you can reference custom context information in query ranking expressions (QREs) and query pipeline conditions.

If you want custom context information to be accessible in usage analytics reports and by Coveo ML, you must include an Analytics component in your search interface.

The JavaScript Search Framework offers three ways to send custom context information:

  • Before coding to pass custom context information, ensure that you have selected and planned your custom context key-value pairs (see Leveraging Custom Contexts in Coveo Machine Learning Features).
  • While you can successfully pass any valid JSON as custom context, be aware that Coveo ML converts each non-array value to an array containing a single string (the converted value), and each element in an array to a string.

    You pass the following JSON as custom context information:

     {
       "ageGroup": "30-45",
       "interests": ["sports", "camping", "electronics"],
       "isPremiumUser": true,
       "latestBrowsedProductCategories": [1, 9],
       "latestPurchase": {"productCategory": 1, "paidPriceRange": "0-100$"}
     }
    

    Coveo ML converts this data as follows:

     {
       "ageGroup": ["30-45"],
       "interests": ["sports", "camping", "electronics"],
       "isPremium": ["true"],
       "latestBrowsedProductCategories": ["1", "9"],
       "latestPurchase": ["{\"productCategory\": 1, \"paidPriceRange\": \"0-100$\"}"]
     }
    

    As you can see, the latestPurchase object loses some of its meaning as a result of this conversion. A better approach would be to pass the same context information as two distinct key-value pairs rather than as the properties of a single object (e.g., "latestPurchaseCategory": 1 and latestPurchasePaidPriceRange": "0-100$").

Using the PipelineContext Component Statically

The PipelineContext component allows you to statically specify the custom context information you want to send. Input values can be either strings or string arrays.

<!--  ...  -->
<body id="search" class="CoveoSearchInterface">
  <!--  ...  -->
  <script class='CoveoPipelineContext' type='text/context'>
    {
      "ageGroup": "30-45",
      "interests": ["sports", "camping", "electronics"]
    }
  </script>
  <!--  ...  -->
</body>

Using the PipelineContext Component Dynamically

Coveo JavaScript Search Framework (December 2017)

The PipelineContext component allows you to set custom context information dynamically. This can be done by setting one key-value pair at a time, using the setContextValue method, or by setting the whole context at once, using the setContext method. Both methods accept input values of type string or string array. Additionally, setContext also accepts stringified JSON as input.

Suppose that you want to send custom context information regarding the age and interests of your end user.

You could do so by implementing getUserAgeGroup and getUserInterests functions, and using the setContextValue method to set one key-value pair at a time, as in the following example:

/**
 * Gets the age group of the currently authenticated user.
 *
 * @returns {string} The user age group (e.g., "30-45").
 */
getUserAgeGroup = function() {
  // Implementation ...
};
  
/**
 * Gets the interests of the currently authenticated user.
 *
 * @returns {string[]} The user interests (e.g., ["sports", "camping", "electronics"])
 */
getUserInterests = function() {
  // Implementation ...
};
  
document.addEventListener("DOMContentLoaded", function () {
  Coveo.SearchEndpoint.configureSampleEndpointV2();
  Coveo.init(document.body);
  var currentUserAgeGroup = getUserAgeGroup(); // E.g., "30-45"
  var currentUserInterests = getUserInterests(); // E.g., ["sports", "camping", "electronics"]
  context = Coveo.get(Coveo.$$(document).find(".CoveoPipelineContext"));
  context.setContextValue("userAgeGroup", currentUserAgeGroup);
  context.setContextValue("userInterests", currentUserInterests);
  // E.g., context: {"userAgeGroup": "30-45", "userInterests":["sports", "camping", "electronics"]}
};
  
// ...

Alternatively, you could use the setContext method of the PipelineContext component to set both key-value pairs at once, as follows:

// ...
  
document.addEventListener("DOMContentLoaded", function () {
  Coveo.SearchEndpoint.configureSampleEndpointV2();
  Coveo.init(document.body);
  var currentUserAgeGroup = getUserAgeGroup(); // E.g., "30-45"
  var currentUserInterests = getUserInterests(); // E.g., ["sports", "camping", "electronics"]
  context = Coveo.get(Coveo.$$(document).find(".CoveoPipelineContext"));
  context.setContext({"userAgeGroup": currentUserAgeGroup, "userInterests": currentUserInterests});
  // E.g., context: {"userAgeGroup": "30-45", "userInterests":["sports", "camping", "electronics"]}
};
  
// ...

Suppose you now want to reset your custom context. You can easily do so by passing an empty JSON to the setContext method.

// ...
  
context.setContext({});
// ... context: {}

Suppose you have a function which returns user age and interest under stringified JSON format. You can pass its results directly to the setContext method.

/**
 * Gets the age and interests of the currently authenticated user.
 *
 * @returns {string} The user age and interests (e.g., '{"userAgeGroup":"18-30","userInterests":["reading","cinema"]}')
 */
getStringifiedUserAgeAndInterest = function() {
  // Implementation ...
};
  
stringifiedContext = getStringifiedUserAgeAndInterest();
context.setContext(stringifiedContext);
// E.g., context: {"userAgeGroup":"18-30","userInterests":["reading","cinema"]}

Using a buildingQuery Event Handler

Coveo JavaScript Search Framework (December 2017)

It is recommended to use the PipelineContext component to dynamically set context information, rather than using a buildingQuery event handler (see Using the PipelineContext Component Dynamically).

You can use a buildingQuery event handler to dynamically set context information (see JavaScript Search Framework Events). Input values can be either strings or string arrays.

var root = Coveo.$$(document).find("#search");
  
Coveo.$$(root).on("buildingQuery", function(e, args) {
  var currentUserAgeGroup = getUserAgeGroup();
  var currentUserInterests = getUserInterests();
  args.queryBuilder.addContext({
    'userAgeGroup': currentUserAgeGroup,
    'userInterests': currentUserInterests
  });
});
  
// ...
  
Coveo.init(root);

What’s Next?

Leverage custom context information in: