简体   繁体   English

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

[英]auto complete in elastic search using python

i have index company_prod2 which gives back hits in kibana with following query:我有索引 company_prod2,它通过以下查询返回 kibana 中的点击:

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

but when i try to search using python elastic search dsl library with following code:但是当我尝试使用具有以下代码的 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'])

i am not getting any results.i also tried with using native python library:我没有得到任何结果。我也尝试使用本机 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"])

but this also gives 0 hits.但这也给出了 0 次点击。

if i try with curl using below command:如果我使用以下命令尝试使用 curl:

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" }}}}'

i happily get results.我很高兴得到结果。 i need to use python library to do same query in elastic search.我需要使用 python 库在弹性搜索中执行相同的查询。

after going through APIs documentation, found actually response has separate fields suggest for autocomplete suggestion retrival:在浏览 APIs 文档后,发现实际上响应有单独的字段建议自动完成建议检索:

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"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM