Search code examples
c#elasticsearchnest

How to search by DateTimeOffset in C# Nest Elasticsearch?


I want to know how to use DateTimeOffset in the DateRangeQuery class in C# Nest Elasticsearch. In my index, I am storing the date data including TimeZone as shown below. "2023-05-19T02:07:36.602171+00:00"

The DateMath class I use in this class seems to be compatible with just DateTime. I would like to be able to retrieve it along with the TimeZone.

This is my C# code.

 new SearchRequest<MyLog>("my_index")
        {
            Query = new QueryContainer(
                new BoolQuery
                {
                    Must = new QueryContainer[]
                    {
                        
                        new DateRangeQuery
                        {
                            GreaterThanOrEqualTo = DateTimeOffset.UtcNow
                            LessThanOrEqualTo =    DateTimeOffset.UtcNow.addHour(4)
                        }
                    }
                })
        };

Solution

  • The NEST client for Elasticsearch in C# does not directly support DateTimeOffset in the DateRangeQuery. You can convert your DateTimeOffset to ISO 8601 format.

    new SearchRequest<MyLog>("my_index")
    {
        Query = new QueryContainer(
            new BoolQuery
            {
                Must = new QueryContainer[]
                {
                    new DateRangeQuery
                    {
                        GreaterThanOrEqualTo = DateTimeOffset.UtcNow.ToString("o"),
                        LessThanOrEqualTo = DateTimeOffset.UtcNow.AddHours(4).ToString("o")
                    }
                }
            })
    };
    

    In this code, the "o" format specifier represents a round-trip
    date/time pattern; when this standard format specifier is used with a DateTimeOffset value, it includes the minute and second of the offset in the result string.

    enter image description here

    push the test data

    POST _bulk
    { "index" : { "_index" : "my_index", "_id" : "1" } }
    { "date" : "2023-08-07T12:07:36.602171+00:00" }
    { "index" : { "_index" : "my_index", "_id" : "2" } }
    { "date" : "2023-08-07T11:07:36.602171+00:00" }
    { "index" : { "_index" : "my_index", "_id" : "3" } }
    { "date" : "2023-05-19T04:07:36.602171+00:00" }
    

    test with an example query

    GET my_index/_search
    {
      "query": {
        "range": {
          "date": {
            "gte": "now",
            "lte": "now+4h"
          }
        }
      }
    }