Search code examples
elasticsearchtimerangeaggregate

Is it possible to search by daily time range between dates?


I can use aggregate to make some stats between two timestamps as following:

{
  "size": 0,
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "status": "ok"
          }
        },
        {
          "term": {
            "deviceId": "123456789"
          }
        },
        {
          "range": {
            "time": {
              "gte": 1669852800,
              "lt": 1671062400
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "results": {
      "date_histogram": {
        "field": "time",
        "fixed_interval": "60",
      }
    }
  }
}

Is it possible to query the results contain specific time range daily only? For example, 7am - 9am daily between Dec.1 to Dec.15. How to achieve it?


Solution

  • I found the solution on elasticsearch v7.15.2 as following:

    {
      "size": 0,
      "query": {
        "bool": {
          "filter": [
            {
              "term": {
                "status": "ok"
              }
            },
            {
              "term": {
                "deviceId": "123456789"
              }
            },
            {
              "range": {
                "time": {
                  "gte": 1669852800,
                  "lt": 1671062400
                }
              }
            },
            {
              "script": {
                "script": {
                  "source": "doc.time.value.getHourOfDay() >= params.min && doc.time.value.getHourOfDay() < params.max",
                  "params": {
                    "min": 8,
                    "max": 10
                  }
                }
              }
            }
          ]
        }
      },
      "aggs": {
        "results": {
          "date_histogram": {
            "field": "time",
            "fixed_interval": "60"
          }
        }
      }
    }
    

    The syntax is slightly different from the comment above, but it works.