1

Hi I want to perform a nested search using elasticsearch dsl where a document field has nested json data in it so I want specific nested key values from it like -

Below is the document:-

{
  "_index" : "data",
  "_type" : "users",
  "_id" : "15",
  "_version" : 1,
  "found" : true,
  "_source" : {
    "data" : {
      "Gender" : "M",
      "Marks" : "80",
      "name" : "Mayank",
      "Address" : "India"
    },
    "last_updated" : "2017-04-09T01:54:33.764573"
  }
}

I only want field values which are stored in an array.

fields_want = ['name', 'Marks']

Output should be like -> {"name":"Mayank", "Marks":"80"}

Elasticsearch dsl documentation is pretty hard to understandand for me. https://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html#

Dsl code:-

client = Elasticsearch()
s = Search(using=client, index="data") \
    .query("match", _type="users") \
    .query("match", _id=15)
response = s.execute()
for hit in s:
    print(hit.data)

From this code I can get the whole json object under data field.

Can somebody guide me here ?

Mayank Singh
  • 131
  • 4
  • 9
  • what do you mean by "{"name":"Mayank", "Marks":"80"}". You cannot tell elastic rest api to model the response according to you. This violates REST api design. To filter the fields you can use "stored_fields". but the structure of the response is at elastic discretion and follows REST api design. https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-stored-fields.html – user3775217 Apr 09 '17 at 18:35
  • I don't want to structure the response but you can see the nested fields in "data" key. `"_source": { "data" :{...}, "last_updated":""}`. I want to get specific field only from "data" key ex. "name" key value or "Marks" key value my code return whole "data" key value i.e. all fields in "data" key. – Mayank Singh Apr 10 '17 at 17:45

1 Answers1

0

It was solved. I have used source filter to get nested output.

client = Elasticsearch()
s = Search(using=client, index="data") \
    .query("match", _type="users") \
    .query("match", _id=15) \
    .source(['data.Name', 'data.Marks'])
response = s.execute()
print response

Output -

{u'Name': u'Mayank', u'Marks': u'80'}
Anil_M
  • 10,893
  • 6
  • 47
  • 74
Mayank Singh
  • 131
  • 4
  • 9