Aerus
Aerus

Reputation: 4380

Sort order elasticsearch equal relevance

I have the following documents:
GET /books

[{
    "title": "a book",
    "certified": true,
    "publisherId": 1
},
{   
    "title": "book a",
    "certified": false
    "publisherId": 2
}]

When I do a simple query string query on title I would like the results to be ordered on _score.
If the _score is equal, books that are certified should appear first.
If the _score is equal and books are certified, books that have publisherId 1 should appear first.

How can I implement these types of tiebreaker rules/sorting rules in ES?

I would like to do something like this, but obviously it doesn't work:

{
    "query": {},
    "sort": [
        {"_score": {"order": "desc"},
        {"term": {"certified": true}},
        {"term": {"publisherId": "1"}}
    ]
}

Upvotes: 0

Views: 1227

Answers (1)

Val
Val

Reputation: 217274

You can simply use bool/should queries to boost your documents according to your certified and publisherId constraints.

If you remove the bool/should in the following query, then all documents will be scored the same way. Adding the bool/should will boost the documents which are certified and those with publisherId: 1

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "title": {
              "query": "book",
              "boost": 3
            }
          }
        }
      ],
      "should": [
        {
          "term": {
            "certified": true
          }
        },
        {
          "term": {
            "publisherId": 1
          }
        }
      ]
    }
  },
  "sort": [
    {
      "_score": {
        "order": "desc"
      }
    }
  ]
}

Upvotes: 2

Related Questions