3

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();

3 Answers 3

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

2 Comments

here, the field 'tags' is not an array, its a simple string field and I want to list all documents which have 'grails', 'elasticsearch' or 'java' in the field; any one of them. thanks
Have you tried what was suggested in the answer? It looks good given your requirements...just use a terms query (supports multiple values) instead of a field query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.