Filter nested objects in elasticsearch query based on query -
i have doc multiple nested documents. nested queries work fine still return nested objects (i.e. whole document) though search query match few nested objects. filter documents whole.
here example:
put /demo { "mappings": { "company": { "properties": { "employees": { "type": "nested" } } } } } put /demo/company/1 { "id": 1, "name": "google", "emp_count": 3, "employees": [{ "id": 1, "name": "john", "address": { "city": "mountain view", "state": "california", "country": "united states" } }] } put /demo/company/2 { "id": 1, "name": "facebook", "emp_count": 3, "employees": [{ "id": 1, "name": "amber", "address": { "city": "bangalore", "state": "karnataka", "country": "india" } }, { "id": 1, "name": "adrian", "address": { "city": "palo alto", "state": "california", "country": "united states" } }] } put /demo/company/3 { "id": 1, "name": "microsoft", "emp_count": 3, "employees": [{ "id": 1, "name": "aman", "address": { "city": "new york", "state": "new york", "country": "united states" } }] }
when searching india
in address, should ideally facebook
1 nested object, nested objects. how can filter nested objects returned?
example query:
{ "query": { "function_score":{ "query":{ "nested":{ "path":"employees", "score_mode":"max", "query": { "multi_match":{ "query":"india", "type":"cross_fields", "fields":[ "employees.address.city", "employees.address.country", "employees.address.state" ] } } } } } } }
output of query facebook
employees while want amber
.
you can use inner_hits
obtain desired result.use below query:
get /demo/company/_search { "query" : { "nested" : { "path" : "employees", "query" : { "match" : {"employees.address.country" : "india"} }, "inner_hits" : {} } } }
output be:
"hits": { "total": 1, "max_score": 1.4054651, "hits": [ { "_index": "demo", "_type": "company", "_id": "2", "_score": 1.4054651, "_source": { "id": 1, "name": "facebook", "emp_count": 3, "employees": [ { "id": 1, "name": "amber", "address": { "city": "bangalore", "state": "karnataka", "country": "india" } }, { "id": 1, "name": "adrian", "address": { "city": "palo alto", "state": "california", "country": "united states" } } ] }, "inner_hits": { "employees": { "hits": { "total": 1, "max_score": 1.4054651, "hits": [ { "_index": "demo", "_type": "company", "_id": "2", "_nested": { "field": "employees", "offset": 0 }, "_score": 1.4054651, "_source": { "id": 1, "name": "amber", "address": { "city": "bangalore", "state": "karnataka", "country": "india" } } } ] } } } } ] }
you can see, inner_hits
section has employees match criteria. inner_hits
introduced in elasticsearch 1.5.0. version should greater elasticsearch 1.5.0. can refer here more information.
Comments
Post a Comment