Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create complex query to Elasticsearch with OR logic using Spring Data Elasticsearch?

I'm looking for best approach to make complex query to Elasticsearch with OR logic from java.

I really need something like ((A and B) or (C and D) or (E and F and G)).

Now I using ElasticsearchTemplate and org.springframework.data.elasticsearch.core.query.Criteria.class.

But I cannot implement OR logic in one query and I have to do separate requests to Elasticsearch:

  • one for (A and B),
  • one for (C and D), and so on...
like image 562
dsgr Avatar asked Mar 02 '23 18:03

dsgr


2 Answers

You can model OR and AND Queries with boolean Queries:

In your example it is:

boolQuery().should(boolQuery().must(A).must(B)) .should(boolQuery().must(C).must(D)) .should(boolQuery().must(E).must(F).must(G));

like image 75
MartinSchulze Avatar answered Mar 05 '23 16:03

MartinSchulze


This is currently not possible, there is a Jira issue for that. This is one of the issues that I'd like to fix as soon as possible, but at the moment we are working on getting the 4.0 release ready.

Alas this needs a whole rewrite of the Criteria class to have this functionality, but of course we must not break the existing functionality. So this is not something that can be done with a quick fix (otherwise I'd fixed it already last december).

like image 20
P.J.Meisch Avatar answered Mar 05 '23 15:03

P.J.Meisch