Search code examples
c#elasticsearchnest

How can i get always last 2 hours logs by Elasticsearch Nest query C#?


My question is related to writing query by using Nest DSL.I want to get my logs only last 2 hours. I developed a console application and I registered it as windows task. it will work per 2 hours but it should take always 2 hours logs My code is below:

            var searchResponse = EsClient().Search<Source>(sd => sd
                              .Index(IndexName)
                              .Type(TypeName)
                              .Query(q => q
                                  .Match(m => m.Field(config.GetSection("Criterias")["SearchField"]).Query(config.GetSection("Criterias")["SearchValue"])
                    )));

My time stamp:@timestamp:September 29th 2017, 14:56:37.903


Solution

  • You can use a bool/filter query in order to include another range query on your timestamp field:

    var searchResponse = EsClient().Search<Source>(sd => sd
                              .Index(IndexName)
                              .Type(TypeName)
                              .Query(q => q
                                .Bool(b => b
                                   .Filter(
                                      bf => bf.Match(m => m.Field(config.GetSection("Criterias")["SearchField"]).Query(config.GetSection("Criterias")["SearchValue"])),
                                      bf => bf.DateRange(dr => dr
                                          .OnField("@timestamp")
                                          .GreaterThan(DateMath.Now.Subtract("2h"))
                                      )
                                  )
                              )