深度阅读

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

作者
作者
2023年08月22日
更新时间
10.96 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。