How to consult with Elasticsearch-dsl?

Asked

Viewed 83 times

1

I’m starting to make queries with elasticsearch_dsl and I’m getting lost to returns my object by product name.

from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search, connections, Q

client = Elasticsearch([{'host': 'elk-site.kalunga.com.br', 'port': 80, 'use_ssl': False}])


res=client.get(index='produto', id='217928')
print(res['_source'])

Json exit made by id.

{
   "produto":[
      {
         "CD_PRODUTO":"217928",        
         "DS_Classificacao":"Notebooks, Tablets & PCs",
         "DS_Grupo":"Computadores",
         "DS_Subgrupo":"Computadores PCs",
         "NM_Fabricante_Fantasia":"HP",
         "NM_Produto":"Computador Pav.A6510BR AMD X2 4050E 2.1ghz 1gb 160gb Dvd-rw HP CX 1 UN"
      }
   ]
}

When I try to make the query using the search of Elasticsearch-dsl I get no return. What would be missing in the query ?

    produto = 'Computador Pav.A6510BR AMD X2 4050E 2.1ghz 1gb 160gb Dvd-rw HP CX 1 UN'
    
    s = Search(using=client)
    
    result = s.query("match", query='Computador Pav.A6510BR AMD X2 4050E 2.1ghz 1gb 160gb Dvd-rw HP CX 1 UN', fields=['NM_Produto', 'body'])

    print(result ['_source'])

2 answers

2


I believe the use of the method query be mistaken. The ideal would be to use Multimatch.

Try to use

from elasticsearch_dsl import MultiMatch

(...)

result = s.MultiMatch("match", query='Computador Pav.A6510BR AMD X2 4050E 2.1ghz 1gb 160gb Dvd-rw HP CX 1 UN', fields=['NM_Produto', 'body'])

More details on documentation

I hope I’ve helped

2

If your search is only in 1 field, you can do as follows:

es = Elasticsearch([{'host': es_settings.ELASTICSEARCH_HOST, 'port': es_settings.ELASTICSEARCH_PORT}])
s = Search(using=es, index="produto")
s = s.query(Q("match", NM_Produto='Computador Pav.A6510BR AMD X2 4050E 2.1ghz 1gb 160gb Dvd-rw HP CX 1 UN'))

print("Query Elastic: ")
print(s.to_dict())

# Executa a query
response = s.execute()

for hit in s:
    print(hit.to_dict())

If you need to search in more than one field the correct is to use Multimatch, in this case the query would be like this:

    es = Elasticsearch([{'host': es_settings.ELASTICSEARCH_HOST, 'port': es_settings.ELASTICSEARCH_PORT}])
    s = Search(using=es, index="produto")
s = s.query(MultiMatch(query='Computador Pav.A6510BR AMD X2 4050E 2.1ghz 1gb 160gb Dvd-rw HP CX 1 UN', fields=['NM_Produto', 'body']))

    print("Query Elastic: ")
    print(s.to_dict())
    
    # Executa a query
    response = s.execute()
    
    for hit in s:
        print(hit.to_dict())

More details on documentation

I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.