弹性搜索中两个日期之间的范围

时间:2015-06-17 10:12:07

标签: elasticsearch

我对过滤器,范围和/或弹性搜索有疑问。

我在带有

的elasticSearch中有de文档
    {
      startDate : myDate
      endDate : onOtherDateOr Nothing

    }

我想搜索现在在startDate之后的范围,或者在startDate和endDate之间搜索如果定义了endDate。我怎样才能做到这一点 ?

3 个答案:

答案 0 :(得分:1)

您可以使用包含两个嵌套bool/should过滤器的两个bool/must过滤器执行此操作:

curl -XPOST localhost:9200/_search -d '{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "should": [
            {
              "bool": {
                "must": [            <--- if endDate exists, check both bounds
                  {
                    "exists": {
                      "field": "endDate"
                    }
                  },
                  {
                    "range": {
                      "startDate": {
                        "lte": "now"
                      }
                    }
                  },
                  {
                    "range": {
                      "endDate": {
                        "gte": "now"
                      }
                    }
                  }
                ]
              }
            },
            {
              "bool": {
                "must": [            <--- if endDate missing, only check startDate
                  {
                    "missing": {
                      "field": "endDate"
                    }
                  },
                  {
                    "range": {
                      "startDate": {
                        "lte": "now"
                      }
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}'

答案 1 :(得分:0)

我发现以下查询是最好的方法:

{
  "query": {
    "range": {
      "order.dateCreated": {
        "dateFrom": "2011-01-24",
        "dateTo": "2011-01-24"
      }
    }
  }
}

答案 2 :(得分:0)

尝试下一个查询,至少对我有用。

"query": {
    "range": {
        "date_ field ": {  # this field_name should be the field where your date range 
                                        resides. 
                 "gte": startDate,
                  "lte": endDate,
                   "boost": 2.0
                      }
                    }
                  }`