Elasticsearch 7.3 Percolate查询在Python中无法匹配问题求助
解决Elasticsearch Python客户端Percolate查询无结果的问题
根据你的描述,官方curl命令可以正常匹配,但Python代码返回hits为0,我遇到过类似问题,大概率是以下两个原因之一:
1. 文档未被实时刷新到索引
Elasticsearch默认是近实时搜索,新创建的文档不会立即被搜索到,需要等待默认的1秒刷新间隔,或者手动触发刷新。你的Python代码在创建percolate查询文档后立即执行搜索,此时文档还未被纳入可搜索的索引,所以返回0结果。
解决方法:
在创建percolate文档后,手动调用索引刷新接口:
res = es.create(index=elasticIndex, id=1, body={ "query" : { "match" : { "message" : "bonsai tree" } } }) # 添加这行代码,手动刷新索引 es.indices.refresh(index=elasticIndex)
2. Python客户端与Elasticsearch版本不兼容
Elasticsearch对客户端版本的兼容性要求较高,如果你使用的elasticsearch pip包版本(比如8.x)与服务器的7.3版本不匹配,可能会导致请求结构或内部处理逻辑出错,进而无法正确执行percolate查询。
解决方法:
安装与Elasticsearch服务器版本完全一致的客户端:
pip install elasticsearch==7.3.0
验证修改后的代码
把上述修改加入你的代码后,完整的测试代码如下:
from elasticsearch import Elasticsearch elasticHost = "localhost" elasticPort = "9200" elasticIndex = "inverse-index" if __name__ == "__main__": es = Elasticsearch(elasticHost + ":" + elasticPort) if es.indices.exists(elasticIndex): print("deleting '%s' index..." % elasticIndex) res = es.indices.delete(index=elasticIndex) print(" response: '%s'" % res) request_body = { "mappings": { "properties": { "message": { "type": "text" }, "query": { "type": "percolator" } } } } print("creating '%s' index..." % elasticIndex) print(" response: '%s'" % (es.indices.create(index=elasticIndex, body=request_body))) res = es.create(index=elasticIndex, id=1, body={ "query" : { "match" : { "message" : "bonsai tree" } } }) # 手动刷新索引,确保新文档可被搜索 es.indices.refresh(index=elasticIndex) doc = { "query": { "percolate": { "field": "query", "document": { "message": "A new bonsai tree in the office" } } } } res = es.search(index=elasticIndex, body=doc) print(str(res))
运行这段代码后,你应该能看到返回的hits中包含你创建的percolate文档了。
内容的提问来源于stack exchange,提问作者cyruz
相关产品推荐
相关产品推荐

