I have multi value fields like field A can have data like ("x", "y" ),("x"),("y", "z") and ("x","z"). Suppose client want to query ElasticSearch to fetch those values of A where A = "x", in such case I wanted to return only 1 record where A = ["x"], but TermQueryBuilder would return wherever it found "x" i.e ["x", "y" ],["x"], ["x","z"]
final BoolQueryBuilder termQueryBuilder = new BoolQueryBuilder();
termQueryBuilder.must(new TermQueryBuilder(filter.getDimension(), filter.getValue()));
return termQueryBuilder;
Please let me know how can I ensure it would return only 1 record, only the exact match data should get returned
You can use a script query, along with the term query, to filter documents based on the provided script.
{
"query": {
"bool": {
"filter": {
"script": {
"script": {
"source": "doc['A.keyword'].length == 1",
"lang": "painless"
}
}
},
"must": {
"term": {
"A": "x"
}
}
}
}
}
Search Result will be
"hits": [
{
"_index": "70343831",
"_type": "_doc",
"_id": "2",
"_score": 0.15965708,
"_source": {
"A": [
"x"
]
}
}
]