Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate multiple fields in a terms query

I have some code already written (java/spring) which allows users to select check boxes and then builds an elasticSearch query. Up to now this has been working well as the requirement has been that terms in different categories should be AND queries and so it has been possible to loop through the tiered selection boxes building a terms match (OR queries) then combine them to and build a boolean terms query along these lines

{
 "bool" : {
   "must" : [ {
     "terms" : {
       "field1" : [ "term1", "term2" ]
     }
   }, {
     "terms" : {
       "field2" : [ "term3" ]
     }
   } ]
 }

There has been a new requirement to make some of the top level boxes OR queries so in these cases I would need something along the lines of

{
 "query": {
   "bool" : {
     "must" : {
       "terms" : { "field1" : ["term1"] , "field1" : ["term2"] } 
    }
   }
 }

}

This is not possible I assume (elasticSearch 2.4.1) as I get an error

"type": "query_parsing_exception",
"reason": "[terms] query does not support multiple fields",...

I'm guessing I should move this to a filter query but I wondered if anyone could confirm that this is the simplest most effective change (at this stage I'm looking for the path of least change) ?

like image 926
gringogordo Avatar asked Apr 26 '17 11:04

gringogordo


2 Answers

The solution is simply to use a should instead of a must in your first query:

{
 "bool" : {
   "should" : [ {                    <---- change this
     "terms" : {
       "field1" : [ "term1", "term2" ]
     }
   }, {
     "terms" : {
       "field2" : [ "term3" ]
     }
   } ]
 }
like image 92
Val Avatar answered Oct 11 '22 17:10

Val


Try with this :-

{
    "query": {
        "bool": {
            "must": [{
                    "term": {
                        "field1": "1"
                    }
                },
                {
                    "term": {
                        "field12": "1"
                    }
                }
            ]
        }
    }
}
like image 36
Vijay Avatar answered Oct 11 '22 16:10

Vijay