我认为在这种情况下布尔查询 https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html是最好的镜头。
就像是 :
{
"bool" : {
"must" : { "term" : { "component" : "comp_1" } },
"should" : [
{ "term" : { "userId" : "A1A1" } },
{ "term" : { "customerId" : "C1" } },
{ "term" : { "currentRole" : "ADMIN" } }
],
"minimum_should_match" : 1
}
}
用 Java 给出:
QueryBuilder qb = QueryBuilders
.boolQuery()
.must(termQuery("component", currentComponent))
.should(termQuery("userId", currentUserId))
.should(termQuery("customerId", currentCustomerId))
.should(termQuery("currentRole", ADMIN))
.minimumNumberShouldMatch(1)
The must
零件是AND
s, the should
零件或多或少OR
s,除了您可以指定最小数量should
s 来匹配(使用minimum_should_match
),我认为这个最小值默认为 1(但你可以将其设置为 0,这意味着没有匹配的文档should
条件也会被返回)。
如果您想做涉及嵌套的更复杂的查询AND
s and OR
s,只需在其中嵌套其他布尔查询must
or should
parts.
另外,当您正在寻找确切的值(id等)时,也许您可以使用术语查询而不是匹配查询 http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/term-vs-full-text.html,这样可以节省分析阶段的时间(如果对这些字段进行了分析,这对于 ids 来说不一定有意义)。如果对它们进行了分析,您仍然可以这样做,但前提是您确切地知道术语是如何存储的(例如,标准分析器将它们存储为小写 https://www.found.no/foundation/beginner-troubleshooting/#why-isnt-my-search-returning-what-i-expect).