【问题标题】:Combine OR, AND and IN operators in Elasticsearch query在 Elasticsearch 查询中组合 OR、AND 和 IN 运算符
【发布时间】:2021-12-04 20:48:12
【问题描述】:

我对弹性搜索非常陌生,我需要准备结合 OR、AND 和 IN 运算符的查询。 我想要实现的是在 SQL 中有这样的东西:

SELECT * FROM tableWHERE (field_1 = 'foo' AND field_2 IN(1,2,3) ) OR ('field_1 = 'bar' AND field_2 IN(2, 3, 4) );

我在 PHP 中使用 elastic,并开始使用类似这样的东西:

                'query' => [
                    'bool' => [
                        'should' => [
                            [
                                'match' => [
                                    'field_1' => 'foo',
                                ],
                            ],
                            [
                                'match' => [
                                    'field_1' => 'bar',
                                ],
                            ],
                        ],

                    ],
                ],

但是,我无法添加查询参数来获得我想要的结果。你能帮帮我吗?

【问题讨论】:

    标签: php elasticsearch elasticsearch-php


    【解决方案1】:

    您需要组合bool/must/should 查询子句。对于 IN 运算符,您可以在 elasticsearch 中使用 terms query

    试试下面的查询

    {
      "query": {
        "bool": {
          "should": [
            {
              "bool": {
                "must": [
                  {
                    "match": {
                      "field_1": "foo"
                    }
                  },
                  {
                    "terms": {
                      "field_2": [
                        1,
                        2,
                        3
                      ]
                    }
                  }
                ]
              }
            },
            {
              "bool": {
                "must": [
                  {
                    "match": {
                      "field_1": "bar"
                    }
                  },
                  {
                    "terms": {
                      "field_2": [
                        2,
                        3,
                        4
                      ]
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    } 
    

    【讨论】:

    • @mkas 已经有一段时间了,你有没有机会通过答案,期待得到你的反馈;-)
    猜你喜欢
    • 2014-10-22
    • 2018-06-03
    • 2020-07-11
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2015-11-11
    • 2012-06-18
    相关资源
    最近更新 更多