How to sort results based on another field's value or weightage

Hi,

Let's take an example.

Say the index has 2 fields, viz., name and weightage.

Values-

name: Black Bus, weightage: 1
name: Blue Bus, weightage: 2

name: Black Car, weightage: 2
name: Blue Car, weightage: 1

Now, I would like to show the query results based on the _score and the weightage. E.g.,

if the user searches-

black => the results are obviously Black Bus and Black Car. But as Black Car has higher weightage (2), so it will be displayed first (above Black Bus)

Similarly,

blue => Blue Bus (2), Blue Car (1)
bus => Blue Bus (2), Black Bus (1)
car => Black Car (2), Blue Car (1)

Now, I tried to use the below sorting algorithm-

   "sort": [
     {
       "weightage": "desc"
     },
     {
       "_score": "desc"
     }
  ],

But the above has a problem for exact match, say-

if the user searches for Black Car or Blue Bus or Black Bus etc., then I want to show the exact match at the top, which will not work if _score comes second in the sort criteria.

Is there a way to boost a document in the search with the value of another field or is it possible to have this as part of the sort?

Thanks in advance.

Hi,

I have used the below sorting query to get the desired results. So far it looks like this is working.

Does it look correct or is there any fault in this?
Also is there any other way to achieve the same without using script sort, that can have support from node.js?

  "sort": {
    "_script": {
      "type": "number",
      "script": {
        "lang": "painless",
        "source": "doc['weightage'].value + _score"
      },
      "order": "desc"
    }
  },

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.