bfw
bfw

Reputation: 157

Elasticsearch, sorting by exact string match

I want to sort results, such that if one specific field (let's say 'first_name') is equal to an exact value (let's say 'Bob'), then those documents are returned first.

That would result in all documents where first_name is exactly 'Bob', would be returned first, and then all the other documents afterwards. Note that I don't intend to exclude documents where first_name is not 'Bob', merely sort them such that they're returned after all the Bobs.

I understand how numeric or alphabetical sorting works in Elasticsearch, but I can't find any part of the documentation covering this type of sorting.

Is this possible, and if so, how?

Upvotes: 3

Views: 1847

Answers (1)

fabiim
fabiim

Reputation: 943

One solution is to manipulate the score of the results that contain the Bob in the first name field.

For example:

POST /test/users
{
  "name": "Bob"
}

POST /test/users
{
  "name": "Alice"
}

GET /test/users/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "name": {
              "query": "Bob", 
              "boost" : 2
            }
          }
        }, 
        {
          "match_all": {}
        }
      ]
    }
  }
}

Would return both Bob and Alice in that order (with approximate scores of 1 and 0.2 respectively).

From the book:

Query-time boosting is the main tool that you can use to tune relevance. Any type of query accepts a boost parameter. Setting a boost of 2 doesn’t simply double the final _score; the actual boost value that is applied goes through normalization and some internal optimization. However, it does imply that a clause with a boost of 2 is twice as important as a clause with a boost of 1.

Meaning that if you also wanted "Fred" to come ahead of Bob you could just boost it with a 3 factor in the example above.

Upvotes: 3

Related Questions