DateRange search using Elastic.Clients.Elasticsearch nuget package

I would like to convert the following into c# using the Elastic.Clients.Elasticsearch nuget package (version 8.15.4), but I cannot find an example. I was able to do a search for an exact match by following the documentation on (CRUD usage examples | Elasticsearch .NET Client [8.9] | Elastic)

GET /IndexName/_search
{
  "query": {
    "range": {
      "@timestamp": {
        "gte": "2024-09-03T15:12:52.2301336+00:00",
        "lte": "2024-09-03T15:12:54.2301336+00:00"
      }
    }
  }
}

I figured it out

public class Searcher
    {
        private static readonly string ElasticSearchUri
            = "https://Redacted.azure.elastic-cloud.com";
        private ElasticsearchClient client = new ElasticsearchClient(
            "Redacted"
            , new ApiKey("Redacted"));
        private const string logIndexId = "Redacted";
        private const string indexName = "Redacted";

        public async Task SearchTimeInterval()
        {

            // Define the timestamp and calculate the range
            var timestamp = new DateTime(2024, 9, 3, 15, 12, 53, 230, DateTimeKind.Utc);
            var startTime = timestamp.AddSeconds(-1);
            var endTime = timestamp.AddSeconds(1);

            // Create the range query
            var rangeQuery = new DateRangeQuery (new Field("@timestamp"))
            {
                Gt = startTime,
                Lt = endTime
            };

            var request = new SearchRequest(indexName)
            {
                From = 0,
                Size = 10,
                Query = rangeQuery
            };

            var response = await client.SearchAsync<object>(request);

            if (response.IsValidResponse)
            {
                foreach (var doc in response.Documents)
                {
                    Console.WriteLine(doc);
                    Console.WriteLine();
                }
            }
        }
    }

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.