在Elasticsearch中

时间:2016-04-20 09:49:51

标签: elasticsearch

有人请帮我在下面的ES查询中添加expires_at IS NULL。我查看了Dealing with Null Values部分的missing过滤器,但我使用它的方式(显示在底部)导致未过期的文档没有出现在结果中,所以显然我在这里做错了。

注意:我不想使用or query,因为它是deprecated in 2.0.0-beta1

QUERY

{
  "query": {
    "filtered": {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "order_id": "123"
              }
            },
            {
              "term": {
                "is_active": 1
              }
            },
            {
              "range": {
                "expires_at": {
                  "gt": "2016-07-01T00:00:00+0000"
                }
              }
            }
          ]
        }
      }
    }
  }
}

这就是我的目标:

SELECT * FROM orders
WHERE
order_id = '123' AND
is_active = '1' AND
(expires_at > '2016-07-01T00:00:00+0000' OR expires_at IS NULL)

这就是我所做的,但未过期的文件在这种情况下不会出现,所以这是错误的。

{
  "query": {
    "filtered": {
      "filter": {
        "missing": {
          "field": "expires_at"
        }
      },
      "query": {
        "bool": {
          "must": [
            ......
            ......
          ]
        }
      }
    }
  }
}

我的ES版本:

{
  "status" : 200,
  "name" : "Fan Boy",
  "version" : {
    "number" : "1.3.4",
    "build_hash" : "a70f3ccb52200f8f2c87e9c370c6597448eb3e45",
    "build_timestamp" : "2014-09-30T09:07:17Z",
    "build_snapshot" : false,
    "lucene_version" : "4.9"
  },
  "tagline" : "You Know, for Search"
}

1 个答案:

答案 0 :(得分:1)

这应该这样做:

{
  "query": {
    "filtered": {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "order_id": "123"
              }
            },
            {
              "term": {
                "is_active": 1
              }
            },
            {
              "bool": {
                "should": [
                  {
                    "range": {
                      "expires_at": {
                        "gt": "20160101000000"
                      }
                    }
                  },
                  {
                    "filtered": {
                      "filter": {
                        "missing": {
                          "field": "expires_at"
                        }
                      }
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}