使用 python 在弹性搜索中自动完成

auto complete in elastic search using python

我有索引 company_prod2,它通过以下查询返回 kibana 中的点击率:

POST company_prod2/_search?pretty
{
    "suggest": {
        "field-suggest" : {
            "prefix" : "cooi",
            "completion" : {
                "field" : "Name_suggest",
                "fuzzy" : {
                    "fuzziness" : 2
                }
            }
        }
    }
}

但是当我尝试使用 python 弹性搜索 dsl 库和以下代码进行搜索时:

from elasticsearch_dsl import Search

 s = Search(using=es_client1, index=indexname)
 s = s.suggest('auto_complete', userinput, completion={'field': "Name_suggest"})
 response = s.execute()
 for hit in response['hits']['hits']:
     print(hit['_score'], hit['_source']['Name'])

我没有得到任何 results.i 也尝试使用原生 python 库 :

from elasticsearch import Elasticsearch
es = Elasticsearch("localhost:9200")
res = es.search(index="company_prod2", body={"suggest": {"Name_suggest" : {"prefix" : "cooi","completion" : {"field" : "Name_suggest","fuzzy" : {"fuzziness" : 2 } }}}})
print("Got %d Hits:" % res['hits']['total']['value'])
for hit in res['hits']['hits']:
    print(hit["_source"])

但这也给出了 0 次点击。

如果我使用以下命令尝试卷曲:

curl -X POST "localhost:9200/company_prod2/_search?pretty&pretty" -H 'Content-Type: application/json' -d'{"suggest": {"song-suggest" : {"prefix" : "co", "completion" : { "field" : "Name_suggest" }}}}'

我很高兴得到结果。我需要使用 python 库在弹性搜索中执行相同的查询。

在查看 API 文档后,发现实际上响应有单独的字段建议自动完成建议检索:

from elasticsearch import Elasticsearch
es = Elasticsearch("54.208.27.149:9200")
res = es.search(index="company_prod2", body={"suggest": {"field-suggest" : {"prefix" : "cooi","completion" : {"field" : "Name_suggest","fuzzy" : {"fuzziness" : 2 } }}}})
print(res["suggest"])
print("Got %d Hits:" % res['hits']['total']['value'])
for hit in res['hits']['hits']:
    print(hit["_source"])