问题
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