Step 2: Add a Query Rule

The second thing you would need to do is add a query rule. This happens in the Search configuration (server-side) but is included here for clarity. When using context in query rules, you can either add it to the criteria or the action.

Review the Query Rules training unit for more information about query rules and the Add Query Rules to a Search Experience help article for step-by-step instructions on adding query rules.

Use the Context in Criteria

When using context in the criteria of query rules, you have two options: context contains and context matches. You’ll want to decide this based on if the context should just contain a specific key or should match the key exactly.

Using the example from our previous step, we decide to set a rule for the swift-fan user segment. If someone is in this user segment (so context matches exactly), we want to boost the Product entity for Swift Running Sneakers to the top of the results.

You will want to add this to your backend Search Configuration like so:

{
  "criteria": {
    "contextMatches": {
      "$.segment": {
        "$eq": "swift-fan"
      }
    }
  },
  "actions": [
    {
      "actionType": "BOOST_ENTITIES",
      "entityIds": ["384349499730115454"],
      "verticalKey": "products"
    }
  ]
}

Use the Context in Actions

Once you set the context in criteria, you can also use the value of a property in your context object in the subsequent action. You can reference the value using bracket notation and JSONPath. The action types that accept filters are boost entities, bury entities, and add filter.

Updating the example above, let’s say rather than just targeting the swift-fan user segment, we want to boost the relevant set of Product entities for any user segment. We can use a custom Content field on the Product entity c_segment that is filled in with the segment that product is meant to target. Then we could set up the query rule to:

  • Use contextContainsKey to check if the key $.segment is present in the context object (we recommend including the context contains criteria as a null check so that you don’t get no results returned).
  • Boost the Product entity results where the c_segment field matches the $.segment value in the context object (specify the key using double brackets such as {{$.segment}})

    {
      "criteria": {
        "contextContainsKey": "$.segment"
      },
      "actions": [
        {
          "actionType": "BOOST_ENTITIES",
          "filter": {
            "c_segment": {
              "$eq": "{{$.segment}}"
            }
          },
          "verticalKey": "products"
        }
      ]
    }