9

Does anyone know if it's possible to custom sort in elasticsearch?

I have a sort on the category field. Which groups all of the records together by category. This works great.

However could you then give the sort a list e.g cars, books, food.

It would then show the cars first, then books and finally food?

2
  • can you please show us what kind of data model you have and what types of queries you are running, definitely function_score will solve your issue, but we may get a more performant solution if i can see the models and queries. Commented Aug 30, 2017 at 15:17
  • Please post a sample document for us to understand what cars, books and food are :/ Commented Aug 30, 2017 at 18:40

2 Answers 2

8

You can use a function_score query, something like this:

{
    "query": {
        "function_score": {
          "query": { "match_all": {} },
          "boost": "5", 
          "functions": [
              {
                  "filter": { "match": { "category": "cars" } },
                  "weight": 100
              },
              {
                  "filter": { "match": { "category": "books" } },
                  "weight": 50
              },
              {
                  "filter": { "match": { "category": "food" } },
                  "weight": 1
              }
          ],
          "score_mode": "max",
          "boost_mode": "replace"
        }
    }
}

Where you, of course, put whichever query you are using now instead of the match_all query, and leave off the sort (the default is by score, which is what you want here).

This is replacing the score elasticsearch normally generates, with a custom score for each category. You could experiment with other boost_mode in order to have a reasonable ranking within the categories. In case you need to understand what is happening with the scoring, you can add "explain": true to the query at the top level.

Sign up to request clarification or add additional context in comments.

Comments

3

You can use custom script for your own scoring.

More details at in Script Based Sorting section: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/search-request-sort.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.