只带年份的Elasticsearch范围过滤器


Elasticsearch Range filter with year only

我需要只使用弹性搜索过滤年份的数据。我使用PHP来获取和显示结果。这是我的JSON格式数据

 {    loc_cityname: "New York",
    location_countryname: "US",
    location_primary: "North America"
    admitted_date  : "1994-12-10"
 },
     {    loc_cityname: "New York",
    location_countryname: "US",
    location_primary: "North America"
    admitted_date  : "1995-12-10"
 },

我使用下面的代码按年过滤值。

$options='{
    "query": {
        "range" : {
            "admitted_date" : {
                "gte" : 1994,
                "lte" : 2000
            }
        }
    }, 
    "aggs" : {
    "citycount" : {
        "cardinality" : {
            "field" : "loc_cityname",
            "precision_threshold": 100
    }
   }
  }
}';

如何只过滤年份的结果?谁来帮我修一下这个

提前致谢

您只需将format参数添加到range查询中,如下所示:

$options='{
    "query": {
        "range" : {
            "admitted_date" : {
                "gte" : 1994,
                "lte" : 2000,
                "format": "yyyy"         <--- add this line
            }
        }
    }, 
    "aggs" : {
    "citycount" : {
        "cardinality" : {
            "field" : "loc_cityname",
            "precision_threshold": 100
    }
   }
  }
}';

请注意,上述解决方案仅适用于ES 1.5及以上版本。对于以前版本的ES,您可以使用script过滤器:

$options='{
  "query": {
    "filtered": {
      "filter": {
        "script": {
          "script": "(min..max).contains(doc.admitted_date.date.year)",
          "params": {
            "min": 1994,
            "max": 2000
          }
        }
      }
    }
  },
  "aggs": {
    "citycount": {
      "cardinality": {
        "field": "loc_cityname",
        "precision_threshold": 100
      }
    }
  }
}';

为了能够运行这个script过滤器,您需要确保您已经启用了elasticsearch.yml中的脚本:

script.disable_dynamic: false