Write genric search query using nest C# client

The question being asked is really a C# design question and not specific to the client.

If a generic method over some T performs strongly typed access to members of T as in the case of field

then those members need to exist on T. The parts of the search request that perform access to members of T could be pulled out of the generic method and passed to it. As an example

public class Document
{
    public int Id { get; set; }
	public int LocalityId { get; set; }
    public IGeoShape LocationShape { get; set; }
}

public static class ElasticClientExtensions
{
	public static ISearchResponse<T> SearchWithMatch<T>(this IElasticClient client, Expression<Func<T, object>> field)
		where T : class =>
		client.Search<T>(s => s
			.From(0)
			.Size(10)
			.Index("sales*")
			.Query(q => q
				.Match(m => m
					.Field(field)
					.Query("salesinvoice")
				)
			)
		);
}

static void Main()
{
	var client = new ElasticClient();
	var response = client.SearchWithMatch<Document>(f => f.LocalityId);
}

the field for the match query is provided to the generic SearchWithMatch<T>() extension method.

1 Like