Reputation: 3595
I am trying to run a query in elasticsearch cluster from java api; I have a list of string values and I would like to get all documents which contains any one of those string values. How can I do it? I tried the following but did not work.
List<String> tagList = new ArrayList<String>();
tagList.add("grails");
tagList.add("elasticSearch");
tagList.add("java");
SearchResponse response = client.prepareSearch("mongoindex")
.setSearchType(SearchType.QUERY_AND_FETCH)
.setQuery(fieldQuery("tags", tagList))
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet();
Upvotes: 3
Views: 5700
Reputation: 61
For youre purpose you need to create the query with separate terms so it will search for at least a single match. Something like this
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
tagList.forEach(tag-> boolQuery.should(QueryBuilders.termQuery("tags", tag));
boolQuery.minimumShouldMatch(1);
And then use it in your search.
"minimumShouldMatch" is to be sure that at least on tag is present in a matched document.
Upvotes: 1
Reputation: 93
It's late but maybe it can help someone else. You can build a terms query
using bool query
with should
clause.
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
.should(QueryBuilders.termsQuery("tags", tagList));
After that continue as usual, assuming there exist a field tags
which holds those values.
SearchResponse response = client.prepareSearch("mongoindex")
.setSearchType(SearchType.QUERY_AND_FETCH)
.setQuery(boolQuery)
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet();
Upvotes: 1
Reputation: 881
Try this one:
List<String> tagList = new ArrayList<String>();
tagList.add("grails");
tagList.add("elasticSearch");
tagList.add("java");
SearchResponse response = client.prepareSearch("mongoindex")
.setSearchType(SearchType.QUERY_AND_FETCH)
.setQuery(QueryBuilders.termsQuery("tags", tagList))
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet();
Check this link to see more details about the terms query.
Upvotes: 0