ElasticSearch date range

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-21 00:12:13

问题


I have the following query:

{
   "query": {
     "query_string": {
       "query": "searchTerm",
        "default_operator": "AND"
       }
     },
    "facets": {
      "counts": {
        "date_histogram": {
         "field": "firstdate",
         "interval": "hour"
         }
    }
}

and I would like to add a date range to it, so as to retrieve values for the field firstdate which are within a specific from/to interval. Any suggestions on how to do it? Many thanks!


回答1:


you just need to add a range filter to your query:

{
"query":{
  "filtered": {
     "query": {
       "query_string": {"query": "searchTerm", "default_operator": "AND" }
     },
      "filter" : {
         "range": {"firstdate": {"gte": "2014-10-21T20:03:12.963","lte": "2014-11-24T20:03:12.963"}}
    }
  }
},
"facets": {
 "counts": {
    "date_histogram": {
       "field": "firstdate",
       "interval": "hour"
      }
    }
  }
}



回答2:


Boolean query will work too,

 {
   "query" :{
      "bool" : {             
          "must" : {
              "range": {"firstdate": {"gte": "2014-10-21T20:03:12.963","lte": "2014-11-24T20:03:12.963"}}
          },

          "must" : {
            "query_string": {
              "query": "searchTerm",
              "default_operator": "AND"
            }
          }

      }
    },

   "facets": {
       "counts": {
          "date_histogram": {
             "field": "firstdate",
             "interval": "hour"
           }
        }
    }

 }



回答3:


This query displays the results which appears in the given date range. "date_field_name" is the field name on which you want to set date range filters.

GET index_name/_search
{
  "query": {
    "bool": {
      "must":[ 
              {
                "range": {
                  "date_field_name": {
                    "gte": "2019-09-23 18:30:00",
                    "lte": "2019-09-24 18:30:00"
                  }
                }
              }
      ]
    }
  },
  "size": 10
}




回答4:


https://your_elasticsearch/your_index PUT

     {
        "mappings": {
            "properties": {
                "created_at": {
                    "type": "date",
                    "format": "yyyy-MM-dd HH:mm:ss"
                }
            }
        }
    }

https://your_elasticsearch/your_index/_search POST

  {
    "query": {
        "bool": {
            "filter": [
                {
                    "range": {
                        "created_at": {
                            "gte": "2020-04-01 08:03:12",
                            "lte": "2020-04-01 20:03:12"
                        }
                    }
                }
            ]
        }
    }
}


来源:https://stackoverflow.com/questions/26791412/elasticsearch-date-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!