David Vann
David Vann

Reputation: 82

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

I am getting results from following Elastic Search query:

"query": {
    "bool": {
        "should": [
            {"match_phrase_prefix": {"title": keyword}},
            {"match_phrase_prefix": {"second_title": keyword}}
        ]
    }
}

The result is good, but I want to change the order of the result so that the results with matching title comes top.

Any help would be appreciated!!!

Upvotes: 2

Views: 853

Answers (1)

Amit
Amit

Reputation: 32376

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.

Upvotes: 1

Related Questions