ElasticSearch - get only matching nested objects with all top-level fields in the search response

let's say I have the following document:

{ id: 1, name: "xyz", users: [{ name: 'abc', surname: 'def' }, { name: 'xyz', surname: 'wef' }, { name: 'defg', surname: 'pqr' }] } 

I want to get only matching nested objects with all the top level fields in the search response. I mean, if I search / filter for users with the name "abc", I want to get below answer

 { id: 1, name: "xyz", users: [{ name: 'abc', surname: 'def' }] } 

How can i do this?

Link: select the appropriate objects from the array in elasticsearch

+6
source share
2 answers

If you are okay with all the root fields except the sub-field, and then only the matching internal hits in the sub-field, then we can reuse the previous answer, like this, by specifying a slightly more used source filter parameter:

 { "_source": { "includes": [ "*" ], "excludes": [ "users" ] }, "query": { "nested": { "path": "users", "inner_hits": { <---- this is where the magic happens "_source": [ "name", "surname" ] }, "query": { "bool": { "must": [ { "term": { "users.name": "abc" } } ] } } } } } 
+6
source

Maybe late, I use nested sorting to restrict an element to my nested relation, here is an example:

 "sort": { "ouverture.periodesOuvertures.dateDebut": { "order": "asc", "mode": "min", "nested_filter": { "range": { "ouverture.periodesOuvertures.dateFin": { "gte": "2017-08-29", "format": "yyyy-MM-dd" } } }, "nested_path": "ouverture.periodesOuvertures" } }, 

Since 5.5 ES (I think), you can use a filter for a subquery. Here is an example of the nested query filter used:

 { "nested": { "path": "ouverture.periodesOuvertures", "query": { "bool": { "must": [ { "range": { "ouverture.periodesOuvertures.dateFin": { "gte": "2017-08-29", "format": "yyyy-MM-dd" } } }, { "range": { "ouverture.periodesOuvertures.dateFin": { "lte": "2017-09-30", "format": "yyyy-MM-dd" } } } ], "filter": [ { "range": { "ouverture.periodesOuvertures.dateFin": { "gte": "2017-08-29", "format": "yyyy-MM-dd" } } }, { "range": { "ouverture.periodesOuvertures.dateFin": { "lte": "2017-09-30", "format": "yyyy-MM-dd" } } } ] } } } } 

Hope this helps;)

Plus, if you are not in the latest version (5.5), inner_hits can slow down your query. Enabling inner hits drastically slows down query results

0
source

Source: https://habr.com/ru/post/1012616/


All Articles