Search code examples
elasticsearchrelevance

Elastic search - change the relevance according to an external factor


My use-case is a bit complicated so I'm simplifying it by using products and purchases:

The application has a big database with varies tables, among them - products and purchases (many to many: user_id:product_id). Elastic has an index for the products only, as this is the only entity needed an advanced/high scale search.

What I'm trying to achieve is as following: The more times the current user bought a product, the more relevant I want it to be.

The tricky part is the fact that Elastic has an index of the products only, not the purchases. I can execute a query in the DB and get the info of how many times a user bought a product, and pass the results to Elastic, the question is how to do it.

Thanks.


Solution

  • If you can produce a reasonably-bounded purchase history for each searcher, you could implement this inside a bool query using a list of optional should block term queries

    E.g.

    "bool": {
      "must": [ <existing query logic> ],
      "should": [
        {
           "term": { "product_id": 654321 },
           "boost": 3 <e.g. Purchased 3 times>
        },
        {
           ...
        }
      ]
    }
    

    As a heads-up, evaluating large numbers of these optional Boolean clauses will degrade your query performance, so you might also consider using a rescore request to apply your boosting logic to only, say, the top 100 unboosted search hits, if that would satisfy your requirement.