Search code examples
elasticsearchelasticsearch-6

How do I prioritize results that I pass in?


I have the following bool query:

POST _search
{
  "query": {
    "bool" : {
      "must" : {
        "term" : { "title" : "technology" }
      },
      "should" : [
        { "term" : { "text" : "companies that produce hardware" } }
      ]
    }
  }
}

Suppose this returns the following document id's (in order):

1. netflix
2. google
3. microsoft
4. dell
5. intel

Before this query happens I query a separate database and get the following results (in order):

1. intel
2. amazon
3. dell

I'd like to prioritize the results of my database over those of elasticsearch so that I get the following results:

1. intel
2. dell
3. netflix
4. google
5. microsoft

(Notice that amazon doesn't show up since we're not trying to create an elasticsearch document out of thin air).


Solution

  • You can use script based sorting, which allows you to sort your data based on a custom script.

    Use a script that assigns a priority value for each result. Could be something like:

    {
      "query": {
        "bool" : {
          "must" : {
            "term" : { "title" : "technology" }
          },
          "should" : [
            { "term" : { "text" : "companies that produce hardware" } }
          ]
        }
      },
      "sort": {
        "_script": {
          "type": "number",
          "order": "asc",
          "script": {
            "lang": "painless",
            "source": "if (doc['company'].value.equals('intel')) return 0;
                       else if (doc['company'].value.equals('amazon')) return 1;                          
                       else if (doc['company'].value.equals('dell')) return 2;                          
                       else return 3;
          }
        }
      }
    }
    

    I used company field since sorting on the '_id' field is discouraged, even though it's possible. Check out this link.

    For more infomation, check Sorting, Scripting and Painless.

    Hope it helps!