elasticsearch如何使用数据范围查询两个不同的字段

时间:2016-05-11 04:25:38

标签: elasticsearch elasticsearch-plugin

我正在使用elasticsearch,我在doc中有以下字段。

sale_start

sale_end

SALE_PRICE

selling_price

我想查询应该是这样的数据:

如果" sale_start"日期和" sale_end"日期在当前日期之间

然后它应该与price_price

匹配价格范围条件

如果" sale_start"日期和" sale_end"日期不在当前日期之间

然后它应该与price_price

匹配价格范围条件

我搜索了很多,但找不到像这样写条件的方法。我也是弹性搜索的新手。提前致谢

1 个答案:

答案 0 :(得分:1)

如果我的要求正确,可以这样表达:

  • bool/should包含两个主要案例:
    1. 当前日期now位于[sale_startsale_end]区间内,sale_price位于价格范围之间。请注意,我已经任意选择了区间[1,1000],但您可以自由地更改它。
    2. 当前日期now位于sale_start之前或sale_end之后且selling_price位于[1,1000]价格范围内。

查询:

{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "range": {
                  "sale_start": {
                    "lt": "now"
                  }
                }
              },
              {
                "range": {
                  "sale_end": {
                    "gt": "now"
                  }
                }
              },
              {
                "range": {
                  "sale_price": {
                    "gt": 1,
                    "lt": 1000
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "should": [
              {
                "range": {
                  "sale_start": {
                    "gt": "now"
                  }
                }
              },
              {
                "range": {
                  "sale_end": {
                    "lt": "now"
                  }
                }
              }
            ],
            "must": [
              {
                "range": {
                  "selling_price": {
                    "gt": 1,
                    "lt": 1000
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}