0

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']
Naresh MG
  • 633
  • 2
  • 11
  • 19

1 Answers1

2

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
Honza Král
  • 2,982
  • 14
  • 11
  • Good to know did not know that I could skip the execute. If I were to not use a for loop and cared only about the 1st hit I would have >>> es_response = s.execute() >>> print es_response[0].policyNumber >>> print es_response[0].party[0].fullName >>> print es_response[0].party[0].phoneList[0].phoneNumber without a for loop and without calling execute() how do I do this please ? >>> print s[0].policyNumber does not work – Naresh MG Mar 29 '17 at 21:56
  • That one you have to execute because slicing over the `Search` object just introduces `from`/`size` limits. – Honza Král Mar 30 '17 at 23:07