Search code examples
elasticsearchlambdanestelasticsearch-plugin

Write bool and aggregate query in C#


Guys i want to write nest query which will fetch distinct result with filter. I want to write below part of Elasticsearch code in c# using Nest.

GET /index/type/_search
{
"query": {
    "bool": {            
        "must": [
           {
              "terms": {
                "ID": [ "5","6" ]          
              }
            },
            {
              "terms": {
                "ProjectID": [ "54"]
              }
            }
        ]
      }
   },
  "aggs": {
  "my_fields": {
  "terms": {
    "field": "ID",
    "size": 0
     }
   }
  }
 }

I'am new to Elasticsearch.Help me to write it in lambda expression. I wrote some code but don't know how to add square brackets in query

var ElasticSearchNetQuery = new { aggs = new { distinctRespId = new { cardinality = new { field = "RespID" }, query = new { @bool = new { must= new { } } } }, size = 10000 } };

Solution

  • var results = client.Search<object>(sd => sd
        .Index("<index name>")
        .Type("<type name>")
        .Query(q => q
            .Bool(b => b
                .Must(
                    m => m.Terms("ID", new[] { "5", "6" }),
                    m => m.Terms("ProjectID", new[] { "54" }))))
        .Aggregations(a => a
            .Terms("my_fields", t => t
                .Field("ID")
                .Size(0)));