Search code examples
pythonelasticsearch-dsl

Using Python elastisearch_dsl with nested objects


I want to try and use elasticsearch_dsl with python for the following

import elasticsearch

es_server = 'my_server_name'
es_port = '9200'
es_index_name = 'my_index_name'
es_connection = Elasticsearch([{'host': es_server, 'port': es_port}])

es_query = '{"query":{"bool":{"must":[{"term":{"data.party.fullName":"john do"}}],"must_not":[],"should":[]}},"from":0,"size":1,"sort":[],"facets":{}}'
my_results = es_connection.search(index=es_index_name, body=es_query)
print  my_results

es_query ='{"query": {"nested" : {"filter" : {"term" : {"party.phoneList.phoneFullNumber" : "4081234567"}},"path" : "party.phoneList"}},"from" :0,"size" : 1}';
my_results = es_connection.search(index=es_index_name, body=es_query)
print  my_results

I am able to get the 1st query but am not sure on the second one

from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search, Q

client = Elasticsearch('my_server:9200')
s = Search(using=client, index = "my_index").query("term",fullName="john do ")
response = s.execute()
print response

Not sure how to do the query using DSL for the nested object party.phoneList.phoneFullNumber

New to ES and hence could not figure out how to do the nested objects. I looked at https://github.com/elastic/elasticsearch-dsl-py/issues/28 and could not quite figure out.

Thanks !


Solution

  • Just use __ instead of . to get around python's limitations and the nested query:

    s = Search(using=client, index = "my_index")
    s = s.query("nested",
        path="party.phoneList",
        query=Q("term", party__phoneList__phoneFullNumber="4081234567")
    )