ElasticSearch查询具有给定值或没有值的字段

时间:2019-07-24 21:02:03

标签: 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
  }
}

1 个答案:

答案 0 :(得分:0)

过滤器块内的任何查询都不会考虑得分。这也称为过滤器上下文。因此,所有内容都应位于过滤器块内。查询结构应如下所示

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"
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}