首页 > 解决方案 > ElasticSearch 查询具有给定值或没有值的字段

问题描述

我正在寻找一种方法来查询我的文档以查找符合这些条件的所有文档:

  1. 无论是房产eye.keyword=RIGHT
  2. 或者属性eye.keyword未定义(值缺失/空)

这是我的查询,但我不确定它是否正确并且以最有效的方式编写。我不需要这些结果的分数:

{
  "bool": {
    "should": [
      {
        "terms": {
          "eye.keyword": [
            "RIGHT"
          ],
          "boost": 1
        }
      }
    ],
    "filter": [
      {
        "terms": {
          "indexLocation.keyword": [
            "global",
            "mycompany"
          ],
          "boost": 1
        }
      }
    ],
    "must_not": [
      {
        "exists": {
          "field": "eye.keyword",
          "boost": 1
        }
      }
    ],
    "adjust_pure_negative": true,
    "boost": 1
  }
}

这是一个文档示例:

{
  "_index": "ophthalmiclens",
  "_type": "_doc",
  "_id": "GLOBAL_SP015_0300603412_IT",
  "_version": 3,
  "_score": 1.6931472,
  "_routing": "global",
  "_source": {
    "gradientColor": false,
    "indexLocation": "global",
    "salesPrice": 39.423,
    "description": "MyBrand Addpower 60 1,5 Ø 65 Sph 2,5 Cyl 0 Add 0,75 Dx",
    "range": false,
    "diameterMin": 65,
    "additionMin": 0.75,
    "preset": true,
    "purchasePrice": 8.9,
    "source": "STOCK",
    "type": "DEGRESSIVE",
    "trial": false,
    "manufacturer": "MyBrand",
    "sphereMax": 2.5,
    "lineCode": "ADDPOWER-65",
    "multiCoating": false,
    "cylinderMax": 0,
    "design": "SPHERIC",
    "imageUrl": null,
    "diameterMax": 65,
    "solidColor": false,
    "hardCoating": false,
    "mirroring": false,
    "sku": "0300603412",
    "thumbUrl": null,
    "barcode": "0300603412",
    "prismMax": null,
    "sphereMin": 2.5,
    "coatingCode": "",
    "lineDescription": "Addpower 60",
    "cylinderMin": 0,
    "index": 1.5,
    "photochromic": false,
    "discontinued": false,
    "searchKey": "GLOBAL_SP015_0300603412_IT",
    "prismMin": null,
    "eye": "RIGHT",
    "taxRate": 4,
    "material": "ORGANIC",
    "additionMax": 0.75,
    "polarized": false
  }
}

标签: elasticsearch

解决方案


过滤器块内的任何查询都不会被考虑进行评分。这也称为过滤上下文。所以一切都应该在过滤器块内。查询结构应如下所示

query
  |_ filter
        |_ location = {a, b}
        |_ should
              |_ eye = right
              |_ eye = null (or eye missing)

查询翻译为:

{
  "query": {
    "bool": {
      "filter": [
        {
          "terms": {
            "indexLocation.keyword": [
              "global",
              "mycompany"
            ]
          }
        },
        {
          "bool": {
            "should": [
              {
                "terms": {
                  "eye.keyword": [
                    "RIGHT"
                  ]
                }
              },
              {
                "bool": {
                  "must_not": [
                    {
                      "exists": {
                        "field": "eye"
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}

推荐阅读