Search code examples
elasticsearchelasticsearch-pluginelasticsearch-5

How to filter items in ElasticSearch based on country and item expiry date


In our elastic search, we have products from different countries and each product is associated with inventoryDate (the date when its added to ES). My aim is to filter out all the product based on country and their inventoryDate, If the user will query the es, for last 1 year, then based on the product country will be filtered out, lets say if the country is India then get all the product not older then 1 year, and if product country is Singapore then get all the product which is not older then 6 month

[{
 "productId": "01",
 "productName": "product 01",
 "productCountry": "India",
 "inventoryDate": "2017-08-17T02:29:03.617Z"
},{
 "productId": "02",
 "productName": "product 02",
 "productCountry": "India",
 "inventoryDate": "2017-02-20T02:29:03.617Z"
},{
 "productId": "03",
 "productName": "product 03",
 "productCountry": "Singapore",
 "inventoryDate": "2018-01-17T02:29:03.617Z"
},{
 "productId": "04",
 "productName": "product 04",
 "productCountry": "Singapore",
 "inventoryDate": "2017-08-17T02:29:03.617Z"
},{
 "productId": "05",
 "productName": "product 05",
 "productCountry": "China",
 "inventoryDate": "2018-01-01T02:29:03.617Z"
},{
 "productId": "06",
 "productName": "product 06",
 "productCountry": "China",
 "inventoryDate": "2017-12-10T02:29:03.617Z"
}]

In this case, the query will return me, ProductId 01, 03 and 05,


Solution

  • {
       "query": {
          "bool": {
             "should": [
                {
                   "bool": {
                      "must": [
                         {
                            "term": {
                               "productCountry": "India"
                            }
                         },
                         {
                            "range": {
                               "inventoryDate": {
                                  "gte": "now-1y/d"
                               }
                            }
                         }
                      ]
                   }
                },
                {
                   "bool": {
                      "must": [
                         {
                            "term": {
                               "productCountry": "Singapore"
                            }
                         },
                         {
                            "range": {
                               "inventoryDate": {
                                  "gte": "now-6M/d"
                               }
                            }
                         }
                      ]
                   }
                }
             ]
          }
       }
    

    }