【问题标题】:OR and AND Operators in Elasticsearch queryElasticsearch 查询中的 OR 和 AND 运算符
【发布时间】:2014-10-22 12:34:05
【问题描述】:

我有几个格式如下的 json 文档:-

    _source: {
            userId: "A1A1",
            customerId: "C1",
            component: "comp_1",
            timestamp: 1408986553,
     }

我想根据以下内容查询文档:-

(( userId == currentUserId) OR ( customerId== currentCustomerId) OR (currentRole ==ADMIN) )  AND component= currentComponent)

我尝试使用 SearchSourceBuilder 和 QueryBuilders.matchQuery,但无法使用 AND 和 OR 运算符放置多个子查询。

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("userId",userId)).sort("timestamp", SortOrder.DESC).size(count);

我们如何使用 OR 和 AND 运算符查询 elasticsearch?

【问题讨论】:

    标签: java elasticsearch elasticsearch-jest


    【解决方案1】:

    我认为在这种情况下Bool query 是最好的选择。

    类似:

    {
        "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)
    

    must 部分是ANDs,should 部分或多或少是ORs,除了您可以指定要匹配的shoulds 的最小数量(使用minimum_should_match),我认为这个最小值默认为 1(但您可以将其设置为 0,这意味着也会返回不匹配 should 条件的文档)。

    如果您想要执行涉及嵌套ANDs 和ORs 的更复杂的查询,只需将其他布尔查询嵌套在mustshould 部分内即可。

    此外,当您正在寻找确切的值(id 等)时,也许您可​​以使用 term queries instead of match queries,这样可以节省您的分析阶段(如果完全分析了这些字段,这不一定有意义对于身份证)。如果对它们进行分析,您仍然可以这样做,但前提是您确切知道术语的存储方式 (standard analyzer stores them lower cased for instance)。

    【讨论】:

    • .minimumShouldMatch 仅将字符串作为参数,对吧?
    • @malte 你是对的。在这种情况下,它应该是带有intminimumNumberShouldMatch,或者带有stringminimumShouldMatch。已更正。
    【解决方案2】:

    如果您使用 query_string query,您的 AND 和 OR 将被 Lucene 库解释为这样。

    这允许您搜索

    (currentUserId OR currentCustomerId) AND currentComponent
    

    例如。默认情况下,将在所有字段中搜索值。

    【讨论】:

    • 但是像QueryBuilders.queryString("(userId: "+currentUserId+" OR customerId: "+currentCustomerId+" OR currentRole: "+ADMIN+") AND component: "+currentComponent+")") 这样的东西应该按照预期的方式工作。
    • 来自 ElasticSearch 文档的链接页面:“如果没有指定前缀字段,则查询词的默认字段。默认为 index.query.default_field 索引设置,而默认为 _all。”显然,ElasticSearch 在索引时添加了 _all 字段,然后我们可以对其应用 Lucene 语法。
    猜你喜欢
    • 2021-12-04
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    相关资源
    最近更新 更多