Sending Custom Context Information

Coveo JavaScript Search Framework - September 2016

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

You can use custom context information to create user defined dimensions, which you can then leverage in usage analytics reports (see Managing Dimensions on Custom Metadata). Coveo Machine Learning (Coveo ML) models can also take advantage of custom context information to promote contextually relevant content (see Leveraging Custom Contexts in Coveo Machine Learning Features). Finally, you can reference custom context information in query expressions and in query pipeline conditions (see Managing Query Pipeline Conditions).

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

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 the Coveo ML service 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 wish 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 also allows you to leverage custom context information dynamically. This can be done by setting one key-value pair at a time, using the setContextValue function, or by setting the whole context at once, using the setContext function. Both functions 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 function 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 function 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 function.

// ...
 
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 function.

/**
 * 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

Prior to the December 2017 Release release, the recommended way to dynamically set some custom context information was to use a buildingQuery event handler (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

Take advantage of the custom context information in: