Skip to content

Promoted Results

As you can see in many search engines, sometimes you want to highlight some results upon certain keywords in a query. Using CERN as an example, if the query contains the keyword CERN you want home.cern to appear first as a highlighted result.

The Elasticsearch property that we will use fot this purposes is called boost, which basically will multiply for an specified value the impact of a field in the results' relevance.

Step 1 - Add an array of keywords to the mapping

We will add an array of keywords to the Elasticsearch mapping. We will call it promoted_keywords.

Elasticsearch mapping:

[...]
    "promoted": {
        "type": "boolean",
    },
    "promoted_keywords": {
        "type": "keyword",
    }

[...]

JSONschema:

[...]
    "promoted": {
        "type": "boolean",
    },
    "promoted_keywords": {
        "type": "array",
        "items": {
            "type": "string"
        }
    }
[...]

Step 2 - Boost the field in the query

When querying the RESTful API we can specify fields upon which to perform them. Moreover, we can specify properties such as boosting. A normal query would look as follows ?q=CERN+query+test. In this case we just need to add the operator ^ and the field specific query: ?q=CERN+query+test+OR+promoted_results:CERN^100.

Note that we have boosted the query on the promoted_results field by 100, but this number and field name are completely customizable. Moreover, we have only place CERN in the field seach but you can implement your custom logic to place more than one keyword of the query.

Indexing time boosting is deprected

Elasticsearch versions previous to 6.0.0 support boosting fields at indexing time. However, since this generated several problems when editing mappings and other operations, it is only supported at query time. As an example of the problem, to undo or change the boosting the whole index has to be reindexed.

Step 3 - Make it look beautiful

How to highlight it is up to each ones UX/UI abilities. You can identify which are this results because of the promoted field with value true, plus they will appear always first (assuming an appropriate boosting).

Extra - Handpick promoted results

You might have an automatic method to insert the promoted results' documents. Nonetheless, you can always perform a PATCH operation on an existing document. For example:

$ curl -k -X PATCH -H 'Content-Type: application/json-patch+json' -H 'Accept: application/json' -H "Authorization:Bearer $TOKEN" -i 'https://<host>:<port>/api/record/<record_id>' --data '[
        {
            "op": "replace",
            "path": "/promoted",
            "value": true
        },
        {
            "op": "replace",
            "path": "/promoted_keywords",
            "value": ["CERN"]
        }
    ]'