在不同字段上将 elasticsearch 中的文档与 AND 和 OR 匹配

Match documents in elasticsearch with AND and OR on different fields

我是弹性搜索的新手,我正在使用 MySQL 和 MongoDB。我想写一个查询,它给出了活跃的产品,它的名称或 brand_name 或 model_number 或类别包含一个特定的词。

这里是MySQL查询。 SELECT * 来自产品,其中 active=0 AND (name LIKE '%car%' OR brand_name LIKE '%car%' OR model_number LIKE '%car%' OR category LIKE '%车%');

我已经在弹性搜索中尝试使用以下查询,但它只是 AND 运算符。

"query": {
        "bool": {
            "must": [
                {"match": {"active": "1"}},
                {"regexp": {"name": "cars.*"}},
                {"regexp": {"brand_data.brand_name": "cars.*"}},
                {"regexp": {"model_number": "cars.*"}},
            ]
        }
    }

谁能帮我在 elasticsearch 中写这个查询。

简短回答 - 对于 OR,您可以使用 should 布尔查询的出现。

带示例的长答案: 可以通过多种方式完成,但我想指出一个细节。如果您只需要搜索 active=1active=0 结果,最好在查询中使用 filter 出现。它将为您提供更好的性能和缓存。

The clause (query) must appear in matching documents. However unlike must the score of the query will be ignored. Filter clauses are executed in filter context, meaning that scoring is ignored and clauses are considered for caching.

所以我可以向您提出这个查询:

{
  "query": {
    "bool": {
      "filter": {
        "term": {
          "active": "1"
        }
      },
      "should": [
        {
          "regexp": {
            "name": "cars.*"
          }
        },
        {
          "regexp": {
            "brand_data.brand_name": "cars.*"
          }
        },
        {
          "regexp": {
            "model_number": "cars.*"
          }
        }
      ]
    }
  }
}

您正在查找嵌套在 'and' 子句中的 'or'。这是正确的格式:

"query": {
        "bool": {
            "must": [
                {"match": {"active": "1"}},
                {"bool":{"should":[
                {"regexp": {"name": "cars.*"}},
                {"regexp": {"brand_data.brand_name": "cars.*"}},
                {"regexp": {"model_number": "cars.*"}}]}}
            ]
        }
    }