Search code examples
c#elasticsearchasp.net-corekibananest

How to write the equivalent query in NEST,C# for the date_histogram by week


I need to convert the following query into c# in using NEST.

"aggs": {
          "number_of_weeks": {
              "date_histogram": {
                    "field": "@timestamp",
                    "interval": "week"
                  }
                }
     }

in Kibana the output is

enter image description here

I wrote the following query but it give me zero bucket while in Kibana it return many result in buckets

var query3 = EsClient.Search<doc>(q => q
                      .Index("SomeIndex")
                      .Size(0)
                      .Aggregations(agg => agg.DateHistogram("group_by_week", e => e.Field(p => p.timestamp) .Interval(DateInterval.Week)
                  )) ;
var resultquery3 = query3.Aggregations.DateHistogram("group_by_week");

in vs studio the output is enter image description here


Solution

  • The problem is likely that

    e => e.Field(p => p.timestamp)
    

    does not serialize to the "@timestamp" field in Elasticsearch. For this to work, you would need to either map it with an attribute on the POCO

    public class Doc
    {
        [Date(Name = "@timestamp")]
        public DateTime timestamp { get; set; }
    }
    

    or map it on ConnectionSettings

    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
    var settings = new ConnectionSettings(pool)
        .DefaultMappingFor<Doc>(m => m
            .PropertyName(e => e.timestamp, "@timestamp")
        );
    
    var client = new ElasticClient(settings);
    

    Alternatively, you can simply pass a string to .Field(), which implicitly converts

    .Field("@timestamp")