【问题标题】:auto complete in elastic search using python使用python在弹性搜索中自动完成
【发布时间】:2020-08-14 04:04:53
【问题描述】:

我有索引 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'])

我没有得到任何结果。我也尝试使用本机 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:

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 库在弹性搜索中进行相同的查询。

【问题讨论】:

    标签: python elasticsearch autocomplete elasticsearch-dsl elasticsearch-dsl-py


    【解决方案1】:

    在浏览 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"])
    

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 2018-12-07
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      相关资源
      最近更新 更多