Home > Back-end >  Outsource parts in queries
Outsource parts in queries

Time:03-14

So let's say I have the following code in C# using NEST:

    private ISearchResponse<Country> GetFilteredResultsByIds(ElasticClient client,
        Query query)
    {
        return client.Search<Country>(s => s
            .From(0)
            .Size(10)
            .Query(q => q
                .Nested(n => n
                    .Path(p => p.Customer)
                    .Query(q => q
                        .Term(t => t
                            .Field(f => f.Customer.CustomerId).Value(query.CustomerId)))
                ) && q
                .Nested(n => n
                    .Path(p => p.Person)
                    .Query(q => q
                        .Term(t => t
                            .Field(f => f.Person.ServiceId).Value(query.ServiceId))))));
    }

is it possible to outsource parts of the search query to external classes/parameters? For example the Customer and Person part to be able to reuse this in another query.

CodePudding user response:

You can extract those parts to static class and use as follow

client.Search<Country>(s => s
    .From(0)
    .Size(10)
    .Query(q => q.SearchCustomerId(customerId) && q.SearchServiceId(serviceId)));

Class with extracted parts

public static class Helpers
{
    public static QueryContainer SearchServiceId(this QueryContainerDescriptor<Country> container, string serviceId)
    {
        return container
            .Nested(n => n
                .Path(p => p.Person)
                .Query(q => q
                    .Term(t => t
                        .Field(f => f.Person.First().ServiceId).Value(serviceId))));
    }

    public static QueryContainer SearchCustomerId(this QueryContainerDescriptor<Country> container, string customerId)
    {
        return container
            .Nested(n => n
                .Path(p => p.Customer)
                .Query(q => q
                    .Term(t => t
                        .Field(f => f.Customer.First().CustomerId).Value(customerId))));
    }
}
  • Related