在 Elasticsearch 查询中组合 OR、AND 和 IN 运算符

Combine OR, AND and IN operators in Elasticsearch query

我是 elasticsearch 的新手,我需要准备结合了 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',
                                ],
                            ],
                        ],

                    ],
                ],

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

你需要在elasticsearch

中结合bool/must/should query clauses. For IN operator you can use 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
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}