Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do search on elasticsearch using java api with a list as parameter

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();
like image 491
Eddard Stark Avatar asked Nov 17 '25 22:11

Eddard Stark


2 Answers

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();
like image 87
Hemed Avatar answered Nov 19 '25 12:11

Hemed


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.

like image 24
Stanislav Milev Avatar answered Nov 19 '25 12:11

Stanislav Milev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!