如何否定"存在"在弹性5.x过滤查询?

时间:2017-08-16 10:52:59

标签: elasticsearch filtering

我必须聚合过滤后的数据,过滤器应该像这样的SQL条件:

WHERE currency = "USD" AND (
    project in (151515, 161616) 
  OR
    project IS NULL
  )

在弹性5.5中,没有missing查询,只有exists,但我不能否定它。怎么做?

GET /myindex/mytype/_search?size=0
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "currency": "USD"
          }
        }
        {
          "terms": {
            "project": [151515, 161616]
          }
        },
        {
          "exists": { //need to negate `exists` here, how?
              "field": "project"
          }
        }
      ]
    }
  },
  "aggs": {
    "by_month": {
      //... some aggs here
    }
  }
}

1 个答案:

答案 0 :(得分:2)

您可以通过在exists查询中包装bool/should/bool/must_not查询来轻松完成此操作,如下所示:

GET /myindex/mytype/_search?size=0
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "currency": "USD"
          }
        },
        {
          "bool": {
            "minimum_should_match": 1,
            "should": [
              {
                "bool": {
                  "must_not": {
                    "exists": {
                      "field": "project"
                    }
                  }
                }
              },
              {
                "terms": {
                  "project": [
                    151515,
                    161616
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  },
  "aggs": {
    "by_month": {}
  }
}