简体   繁体   English

如何使用 Spring Data Elasticsearch 使用 OR 逻辑创建对 Elasticsearch 的复杂查询?

[英]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.我正在寻找使用 Java 中的 OR 逻辑对 Elasticsearch 进行复杂查询的最佳方法。

I really need something like ((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)) 这样的东西

Now I using ElasticsearchTemplate and org.springframework.data.elasticsearch.core.query.Criteria.class .现在我使用 ElasticsearchTemplate 和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:但是我无法在一个查询中实现 OR 逻辑,我必须向 Elasticsearch 发出单独的请求:

  • one for (A and B),一个用于(A 和 B),
  • one for (C and D), and so on...一个用于(C 和 D),等等......

You can model OR and AND Queries with boolean Queries:您可以使用布尔查询对 OR 和 AND 查询建模:

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

This is currently not possible, there is a Jira issue for that.这目前是不可能的,有一个Jira 问题 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.这是我希望尽快修复的问题之一,但目前我们正在努力准备 4.0 版本。

Alas this needs a whole rewrite of the Criteria class to have this functionality, but of course we must not break the existing functionality.唉,这需要完全重写Criteria类才能拥有此功能,但我们当然不能破坏现有功能。 So this is not something that can be done with a quick fix (otherwise I'd fixed it already last december).所以这不是可以通过快速修复来完成的(否则我已经在去年 12 月修复了它)。

The AND in elasticSearch is Must the OR is Should, and you got too the MustNot for AND NOT elasticSearch 中的 AND 是 Must OR 是应该,你也得到了 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您可以使用 bool 查询连接它们,例如这个示例https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

Update: Sorry i had wrong logic, As AND operator has preference over OR operator, simply removing bracket will work更新:对不起,我有错误的逻辑,因为 AND 运算符优先于 OR 运算符,只需删除括号即可

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM