Search code examples
elasticsearchelasticsearch-dslelasticsearch-dsl-py

access individual fields using elastic search dsl in python


Is the below accurate or should it be something else ?

I am getting the expected results just checking if this is the most efficient way to access individual (nested) fields.

from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search, Q

import json
client = Elasticsearch('my_server')

policy_number = 'POLICY1234'
s = Search(using=client, index = "my_index").query("term",policyNumber=policy_number.lower())
es_response = s.execute()

for hits in es_response:
   print hits['policyNumber']
   print hits.party[0]['fullName']
   print hits.party[0].partyAddress[0]['address1']
   print hits.party[0].partyAddress[0]['city']
   print hits.party[0].phoneList[0]['phoneNumber']

Solution

  • You don't need to call execute manually and you don't have to use [] to access fields by name, you can just use the attribute access:

    for hit in s:
       print hit.policyNumber
       print hit.party[0].fullName
       print hit.party[0].partyAddress[0].address1
       print hit.party[0].partyAddress[0].city
       print hit.party[0].phoneList[0].phoneNumber