Search code examples
c#elasticsearchnest

Multiple Must in elasticsearch query using Elastic.Clients.Elasticsearch


I'm trying to query data using the new c# api. I do know the field values and would simply like to retrieve the correct record(s). E.g.

// client is an instance of ElasticsearchClient

var response = await client.SearchAsync<EffectSerie>(s => s
    .Index(_indexName)
    .Query(q => q
        .Bool(b => b
            .Must(sd => sd
                .Term(t => t.startDate, "2023-11-01")
                .Term(t => t.endDate, "2023-11-02")
                .Term(t => t.periodType, 4)
            )
        )
    )
);

This will however get all records with the matching periodType. I'm using the newest version of Elastic.Clients.Elasticsearch and not Nest.


Solution

  • Managed to solve this, it turns out that the params on the Must selector could also be an array. So the proper way to do this was to segment the lambda a bit.

    var response = await client.SearchAsync<EffectSerie>(s => s
        .Index(_indexName)
        .Query(q => q
            .Bool(b => b
                .Must(
                    mu1 => mu1
                    .Range(r => r
                        .DateRange(dr => dr
                            .Field("startDate").Gte(startDate).TimeZone("-01:00:00")
                            .Field("endDate").Lt(endDate).TimeZone("-01:00:00")
                            )
                    ),
                    mu2 => mu2
                    .Term(t => t.periodType, periodType)
                )
            )
        )
    );
    

    This will form a working query

    {
      "query": {
        "bool": {
          "must": [
            {
              "range": {
                "endDate": {
                  "gte": "2023-11-05",
                  "lt": "2023-11-06",
                  "time_zone": "-01:00:00"
                }
              }
            },
            {
              "term": {
                "periodType": {
                  "value": 4
                }
              }
            }
          ]
        }
      }
    }