phpelasticsearchelasticsearch-jdbc-river

Elasticsearch Range filter with year only


I need to filter my data with year only using elastic search. I am using PHP to fetch and show the results. Here is my JSON Format data

 {    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"
 },

I am using below codes to filter the values by year.

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

How can i filter the results with year only. Please somebody help me to fix this.

Thanks in advance,


Solution

  • You simply need to add the format parameter to your range query like this:

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

    UPDATE Note that the above solution only works for ES 1.5 and above. With previous versions of ES, you could use a script filter instead:

    $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
          }
        }
      }
    }';
    

    In order to be able to run this script filter, you need to make sure that you have enabled scripting in elasticsearch.yml:

    script.disable_dynamic: false