Using a Terms Query via Elastic.Clients.Elasticsearch 8.1.1 .NET

I am currently trying to write a Terms Query via the Elastic.Clients.Elasticsearch 8.1.1 .NET client. To be more precise, I want to write following query in C#:

GET persons/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "companyId": [
              1, 2, 3
            ]
          }
        }
      ]
    }
  }
}

Note that the persons index already exists and contains a numeric field called companyId. I have tried to write the query in C# like this:

long[] companyIds = new long[] { 1, 2, 3 };
var response = await _elasticsearchClient.SearchAsync<Person>(s => s
    .Index("persons")
    .Query(q => q
        .Bool(b => b
            .Must(m => m
                .Terms(ts => ts
                    .Field("companyId")
                    .Terms(companyIds)
                )
            )
        )
    )
);

Unfortunately, this does not work because the inner Terms method expects a Elastic.Clients.Elasticsearch.QueryDsl.TermsQueryField as parameter instead of a long[]. So my question is: Is there a way to map the long[] (or e.g. a List<long>) to the Elastic.Clients.Elasticsearch.QueryDsl.TermsQueryField or is there another way to write this query in C#?
I am aware that this platform is not intended to be a 'How to write this query in C#'-forum, but I am a little lost with the currently provided documentation, since it only covers the most basic usage of the library. Thanks in advance for any help!

Hi, @felix-stnr.

You raise a great example of where our code generated APIs could be improved. I'll open an issue to track work to make this easier to achieve.

It's quite verbose but you can create it like this for now:

var companyIds = new long[] { 1, 2, 3 };
var response = await client.SearchAsync<Person>(s => s
	.Index("persons")
	.Query(q => q
		.Bool(b => b
			.Must(m => m
				.Terms(ts => ts
					.Field("companyId")
					.Terms(new Elastic.Clients.Elasticsearch.QueryDsl.TermsQueryField(companyIds.Select(id => FieldValue.Long(id)).ToArray()))
				)
			)
		)
	)
);
1 Like

Thank you very much! I am already looking forward to a more comprehensive documentation for the .NET client. :grin:

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.