首页 > 解决方案 > 如何重写弹性搜索的查询

问题描述

我有 SQL 查询

SELECT * FROM requests WHERE order_type = 'buyer' AND (plantations_id = 402 OR plantations_id = 460)

我对弹性的查询是

GET /requests/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "order_type": "buyer"
          }
        },
        {
          "bool": {
            "should": [
              {
                "terms": {
                  "plantations_id": [402, 460]
                }
              }
            ]
          }
        }
      ]
    }
  }
}

但是结果集中只有“plantations_id”:“460”的项目。我有点困惑如何正确地重写我的原始查询。

提前致谢。

标签: elasticsearch

解决方案


您不需要该bool/should子句,正确的查询是这个:

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "order_type": "buyer"
          }
        },
        {
          "terms": {
            "plantations_id": [
              402,
              460
            ]
          }
        }
      ]
    }
  }
}

或者更好的是,将terms过滤器移至bool/filter,因为它不会参与评分:

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "order_type": "buyer"
          }
        }
      ],
      "filter": [
        {
          "terms": {
            "plantations_id": [
              402,
              460
            ]
          }
        }
      ]
    }
  }
}

推荐阅读