在布尔查询中使用过滤器和嵌套对象可以更有效地处理复杂的查询需求。以下是一个包含代码示例的解决方法:
from elasticsearch import Elasticsearch
# 创建 Elasticsearch 客户端
es = Elasticsearch()
# 创建索引
es.indices.create(index='my_index', ignore=400)
# 插入数据
es.index(index='my_index', id=1, body={
'name': 'John Smith',
'age': 30,
'address': {
'city': 'New York',
'state': 'NY'
}
})
es.index(index='my_index', id=2, body={
'name': 'Jane Doe',
'age': 25,
'address': {
'city': 'Los Angeles',
'state': 'CA'
}
})
# 使用布尔查询和过滤器进行搜索
query = {
'query': {
'bool': {
'filter': [
{'term': {'age': 30}}
],
'must': [
{'nested': {
'path': 'address',
'query': {
'bool': {
'filter': [
{'term': {'address.city': 'New York'}}
]
}
}
}}
]
}
}
}
res = es.search(index='my_index', body=query)
# 处理搜索结果
for hit in res['hits']['hits']:
print(hit['_source'])
在上面的代码中,首先创建了一个 Elasticsearch 客户端,然后创建了一个名为 my_index
的索引,并插入了两个文档。
接下来,我们使用布尔查询和过滤器进行搜索。布尔查询使用 bool
关键字,并包含了一个 filter
子句和一个 must
子句。filter
子句用于过滤符合特定条件的文档,而 must
子句用于指定必须满足的条件。在本例中,我们使用 term
过滤器和 nested
查询来匹配年龄为 30 岁且所在城市为纽约的文档。
最后,我们通过遍历搜索结果来处理匹配的文档。
请注意,上述代码仅提供了一个基本的示例,您可以根据实际情况进行适当的修改和扩展。
上一篇:布尔查询和过滤器不返回任何文档。
下一篇:布尔查询中的不同评分函数