Elasticsearch的多种查询方式
Elasticsearch支持多种查询方式,包括:
- 查询字符串(Query String Search)
- 简单查询(Simple Query String)
- 复合查询(Bool Query)
- 聚合查询(Aggregations)
- 函数查询(Function Score)
以下是这些查询方式的示例代码:
from elasticsearch import Elasticsearch
# 初始化Elasticsearch客户端
es = Elasticsearch()
# 查询字符串查询
query = {
"query": {
"query_string": {
"query": "John Smith"
}
}
}
response = es.search(index="your_index", body=query)
# 简单查询
query = {
"query": {
"simple_query_string": {
"query": "John Smith",
"fields": ["first_name^10", "last_name^5"]
}
}
}
response = es.search(index="your_index", body=query)
# 复合查询
query = {
"query": {
"bool": {
"must": [
{"match": {"title": "Elasticsearch"}}
],
"filter": [
{"term": {"status": "published"}}
],
"should": [
{"match": {"content": "Elasticsearch"}}
],
"must_not": [
{"range": {"age": {"gt": 30}}}
]
}
}
}
response = es.search(index="your_index", body=query)
# 聚合查询
query = {
"aggs": {
"group_by_tags": {
"terms": {
"field": "tags",
"size": 10
}
}
}
}
response = es.search(index="your_index", body=query)
# 函数查询
query = {
"query": {
"function_score": {
"query": {
"match": {
"title": "Elasticsearch"
}
},
"functions": [
{
"filter": {
"match": {
"title": "Elasticsearch"
}
},
"weight": 5
}
],
"boost_mode": "multiply"
}
}
}
response = es.search(index="your_index", body=query)
这些代码展示了如何在Python中使用Elasticsearch Python API执行不同类型的查询。每个查询都有其特定的用途,开发者可以根据需要选择合适的查询方式。
评论已关闭