Say I have a doc in Elasticsearch Index like below
{
"data": [
{
"color": "RED",
"qty": 3
},
{
"color": "BLACK",
"qty": 1
}, {
"color": "BLUE",
"qty": 0
}
]
}
I just need color BLACK. Is there any way to get just enough data back like below.
{
"data": [
{
"color": "BLACK",
"qty": 1
}
]
}
CodePudding user response:
Elasticsearch returns whole document if there is any match to any field. If you want to find matched nested document, you can make data
array nested in your index mapping, write a nested query that filters data.color
by its value, which is BLACK in your case and use inner_hits to find the matched nested documents.
You can use source filtering to retrieve only fields you want but it will only filter by fields, not by field values.
CodePudding user response:
You can use script field to generate new field which have only specific value from array. Below is sample query:
{
"_source": {
"excludes": "data"
},
"query": {
"match_all": {}
},
"script_fields": {
"address": {
"script": {
"lang": "painless",
"source": """
List li = new ArrayList();
if(params['_source']['data'] != null)
{
for(p in params['_source']['data'])
{
if( p.color == 'BLACK')
li.add(p);
}
}
return li;
"""
}
}
}
}
Response:
"hits" : [
{
"_index" : "sample1",
"_type" : "_doc",
"_id" : "tUc6338BMCbs63yKTqj_",
"_score" : 1.0,
"_source" : { },
"fields" : {
"address" : [
{
"color" : "BLACK",
"qty" : 1
}
]
}
}
]