How to handle sorting of search results in Elasticsearch using Python?

Published on Aug. 22, 2023, 12:19 p.m.

To handle sorting of search results in Elasticsearch using Python, you can use the sort parameter in the search query. Here’s an example code snippet:

from elasticsearch import Elasticsearch

# create an Elasticsearch client instance
es = Elasticsearch(['http://localhost:9200'])

# define the search query with a sort
query = {
    "query": {
        "match": {
            "description": "python"
        }
    },
    "sort": [
        {"price": {"order": "asc"}}
    ]
}

# perform the search and get the results
results = es.search(index="my_index", body=query)

# print the results
for result in results['hits']['hits']:
    print(result['_source'])

In this example, we’re searching the my_index index for documents containing the word “python” in their “description” field, and sorting the results in ascending order based on the “price” field. The sort parameter is used to specify the sorting criteria.

You can also sort on multiple fields, use different sort orders (ascending or descending), and even specify custom sorting rules based on custom scoring functions.