0

Python 3.9.5/Elasticsearch Python client 7.14

I'm using the Python Elasticsearch library to run queries against an Elasticsearch 7.10 cluster.

I'm trying to return fields from within a nested field, whereas I can only figure out the syntax to return the values from the entire nested field.

Example:

The ES document I'm returning:

"hits" : [
      {
        "_index" : "main",
        "_type" : "_doc",
        "_id" : "123",
        "_score" : 1.0,
        "_source" : {
          "id" : 1000123,
          "org_name" : {
            "data" : "Acme Inc",
            "entityType" : "ORGANIZATION"
          }
        }
      }
     ] 

Right now my Python code looks like this:

from elasticsearch import Elasticsearch
client = Elasticsearch()

response = client.search(
    index="main",
    body={
          "the ES query"
          }
)
for hit in response['hits']['hits']:
    print(hit['_source']['id'], hit['_source']['org_name'])

which returns:

1000123 {'data': 'Acme Inc', 'entityType': 'ORGANIZATION'}

But what I need to return is:

Either:

 1000123 'data': 'Acme Inc'

which I can't figure out the syntax for to modify ['org_name'] in the print line of the Python code.

Or even better, if possible:

1000123 'org_name': 'Acme Inc'

The single quotes around org_name are of no significance, so it doesn't matter if they are there or not in the response, whichever is achievable the most efficiently is fine with me.

I have reviewed all the examples in the docs for this ES library, and none of them seem to address this.

2
  • Wat ? print(hit['_source']['id'], {'org_name': hit['_source']['org_name']['data']}) ?? Commented Sep 15, 2021 at 14:47
  • A-ha, yes that does work! I couldn't get it to work with the variations I tried! Please add as an answer and I will mark as answer! :) Commented Sep 15, 2021 at 15:48

1 Answer 1

1

I am not sure, if this would work for you: Can you try printing this and tell me what's the result:

print(hit['_source']['id'], {'org_name': hit['_source']['org_name']['data']})
Sign up to request clarification or add additional context in comments.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.