How to use a loop to keep adding terms to a boolQuery in JAVA


(Nisam Ponery) #1

Hi,
i am trying to see if whether i can use a for loop to to construct a boolQuery in order to dynamically add as many terms i want

for example i have some Java code like this :

          QueryBuilder qb = QueryBuilder.boolQuery()
                                            .should(termQuery("name","joe"))
                                            .should(termQuery("age","j23"))
                                             .should(termQuery("ID","12345"))  ;

the thing is with this i have to manually add all the terms, so i was wondering if could use a loop to add all the terms and i am not sure exactly about the syntax

Here is what i want to achieve ideally :
// assume "fields" is an array with a lot of strings
//assume "fields2: is another array with a lot of strings

                                   QueryBuilder qb;
                                  for(int i =0 ; i < fields.length; i++) {
                                             
                                               QueryBuilder.boolQuery()
                                    .should( termQuery( field[i],  field2[i] ) ) ;

                                            }

// so by doing this i am hoping to append all the term queries dynamically without me hard coding it

I know the syntax for what i am trying to do is wrong but that is what i am trying to achieve and i am not exactly sure on the syntax for doing it

So if you can please Help


(David Pilato) #2

Try something like:

BoolQueryBuilder qb = QueryBuilders.boolQuery();
for(int i =0 ; i < fields.length; i++) {
     qb.should( termQuery( field[i],  field2[i] ) ) ;
}

(Nisam Ponery) #3

thank you that helped


(system) #4

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.