pythonelasticsearchautocompleteelasticsearch-dslelasticsearch-dsl-py

auto complete in elastic search using python


i have index company_prod2 which gives back hits in kibana with following query :

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 :

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 :

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 .

if i try with curl using below command :

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 .


Solution

  • after going through APIs documentation, found actually response has separate fields suggest for autocomplete suggestion retrival :

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