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

4

5

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...
Nashville answered 27/2, 2020 at 8:2 Comment(0)
P
1

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).

Pagepageant answered 27/2, 2020 at 19:24 Comment(0)
B
6

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

Ballad answered 27/2, 2020 at 8:15 Comment(1)
Thank you. That and the previous message put me in the right path. I just could not get myself to believe there was no way to do nested conditions with Criteria. A real oversight, IMHO.Delamination
P
1

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).

Pagepageant answered 27/2, 2020 at 19:24 Comment(0)
H
0

The AND in elasticSearch is Must the OR is Should, and you got too the MustNot for AND NOT

You can concat them with a bool query, like this example https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

Highcolored answered 27/2, 2020 at 8:14 Comment(0)
L
0

Update: Sorry i had wrong logic, As AND operator has preference over OR operator, simply removing bracket will work

I think the following logic will work

((A and B) or (C and D) or (E and F and G)) = A and B or C and D or E and F and G

Lashonda answered 27/2, 2020 at 8:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.