i am trying to convert below ES query which is working in console to Java Code
{
"query": {
"bool": {
"must": [
{
"match": {
"ID.keyword": "1234457654"
}
},
{
"bool": {
"should": [
{"match": {
"stepName.keyword": "STEP1"
}},
{"match": {
"stepName.keyword": "STEP2"
}}
]
}
}
]
}
}
}
Java code which i tried
QueryBuilder qb = QueryBuilders.boolQuery().
must(QueryBuilders.matchQuery("ID.keyword", transformedDataDTO.getID()).operator(Operator.AND)).
should(QueryBuilders.matchQuery("stepName.keyword", transformedDataDTO.getStepName()))
.should(QueryBuilders.matchQuery("stepName.keyword", MigrationStatusEnum.getPreviousData(transformedDataDTO.getStepName())));
instead of returning data matching to step1 or step2 it returns all the data
Please suggest what is missing in above java code or how to fix it.
CodePudding user response:
I would suggest a different approach since you're doing an exact match on stepName.keyword
, why not using terms
(which has implicit OR
semantics), and your query simply becomes:
{
"query": {
"bool": {
"filter": [
{
"term": {
"ID.keyword": "1234457654"
}
},
{
"terms": {
"stepName.keyword": [
"STEP1",
"STEP2"
]
}
}
]
}
}
}
Translated to Java:
QueryBuilder qb = QueryBuilders.boolQuery()
.filter(QueryBuilders.termQuery("ID.keyword", transformedDataDTO.getID()))
.filter(QueryBuilders.termsQuery("stepName.keyword", transformedDataDTO.getStepName(), MigrationStatusEnum.getPreviousData(transformedDataDTO.getStepName())));