How to change the order of search results on Elastic Search? How to change the order of search results on Elastic Search? elasticsearch elasticsearch

How to change the order of search results on Elastic Search?


I was able to reproduce the issue with sample data and My solution is using a query time boost, as index time boost is deprecated from the Major version of ES 5.

Also, I've created sample data in such a manner, that without boost both the sample data will have a same score, hence there is no guarantee that one which has match comes first in the search result, this should help you understand it better.

1. Index Mapping

{    "mappings": {        "properties": {            "title": {                "type": "text"            },            "second_title" :{                "type" :"text"            }        }    }}

2. Index Sample docs

a)

{    "title": "opster",    "second_title" : "Dimitry"}

b)

{    "title": "Dimitry",    "second_title" : "opster"}

Search query

{    "query": {        "bool": {            "should": [                {                    "match_phrase_prefix": {                        "title": {                        "query" : "dimitry",                        "boost" : 2.0  <-- Notice the boost in `title` field                        }                    }                },                {                    "match_phrase_prefix": {                        "second_title": {                            "query" : "dimitry"                        }                    }                }            ]        }    }}

Output

"hits": [            {                "_index": "60454337",                "_type": "_doc",                "_id": "1",                "_score": 1.3862944,                "_source": {                    "title": "Dimitry", <-- Dimitry in title field has doube score                    "second_title": "opster"                }            },            {                "_index": "60454337",                "_type": "_doc",                "_id": "2",                "_score": 0.6931472,                "_source": {                    "title": "opster",                    "second_title": "Dimitry"                }            }        ]

Let me know if you have any doubt understanding it.