0

The following query calculates the count of documents in index:

public async Task GetCount(DateTimeOffset? startDate, DateTimeOffset? endDate, string eventName)
{
    var count = await _elasticClient.CountAsync<OemCatalogModel>(c => c.Index(indexName)
                .Query(q => q.DateRange(p => p.Field(t => t.Timestamp).Format("epoch_second")
                             .GreaterThanOrEquals(startDate)
                             .LessThanOrEquals(endDate)
                             ))
                .Query(q => q.Match(m => m.Field(f => f.Event).Query($"{eventName}")))
                );
}

Problem is CountAsync ignore Query with DateRange and return count of all documents in index when eventName is empty.

How to dynamically add the following filter

Query(q => q.Match(m => m.Field(f => f.Event).Query(eventName))

if eventName is not empty string? I think that it can implement using `Func<long, ...> but don't understand how...

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user6408649
  • 1,227
  • 3
  • 16
  • 40
  • You're already adding filters dynamically. `Query` is a function call that returns a new query. If you don't want to apply a filter don't make that call. You don't have to chain all calls together – Panagiotis Kanavos Sep 02 '22 at 12:36
  • @PanagiotisKanavos thanks for answer. I changed question. Please take a look. The `event Name ` is argument in function. I understand that can write: `if(event Name)` here request with two Query `else` request with one Query. But maybe something way to pass Query as argument to method? – user6408649 Sep 02 '22 at 12:51
  • 1
    Why? You're building an expression there. If you don't want a particular `Query` branch, don't add it in the first place. That's what `dynamic` means – Panagiotis Kanavos Sep 02 '22 at 13:27
  • @PanagiotisKanavos Thanks for the answer. You sent me to the right idea, but another question appeared. Please take a look. https://stackoverflow.com/questions/73595492/how-to-declare-a-delegate-with-arguments – user6408649 Sep 03 '22 at 21:32

0 Answers0