C# NEST 5 Search with template

how can i use the ElasticClient SearchTemplateAsync method with skip, size, aggregations , and so forth..
in the latest c# driver searching with templates is based on the method SearchTemplateAsync rather than SearchAsync. however, it seems that the searchtemplatedescriptor cannot be configured with basic stuff like skip and size. when i try to use the old SearchAsync with .Template, i get an obsolete error.

You can create search templates by serializing searches created through the fluent API or object initializer syntax

var client = new ElasticClient();

var query = new SearchDescriptor<Question>()
    .Query(q => q
        .QueryString(m => m
            .Fields(f => f
                .Field(ff => ff.Title)
                .Field(ff => ff.Body)
            )
            .Query("{{query_string}}")
        )
    )
    .Aggregations(a => a
        .Terms("tags", ta => ta
            .Field(f => f.Tags)
        )
    );
    
var template = client.Serializer.SerializeToString(query);

client.PutSearchTemplate("template-name", ps => ps
    .Template(template)
);

var searchResponse = client.SearchTemplate<Question>(st => st
    .Index("posts")
    .Id("template-name")
    .Params(p => p
        .Add("query_string", "\"Jon Skeet\" AND \"Chuck Norris\"")  
    )
);

There are some methods within the fluent API that are constrained to take specific types e.g. From() and .Size() can only accept an int. You can also parameterize these with something like

var client = new ElasticClient();

var query = new SearchDescriptor<Question>()
    .Query(q => q
        .QueryString(m => m
            .Fields(f => f
                .Field(ff => ff.Title)
                .Field(ff => ff.Body)
            )
            .Query("{{query_string}}")
        )
    )
    .Aggregations(a => a
        .Terms("tags", ta => ta
            .Field(f => f.Tags)
        )
    );
    
var template = client.Serializer.SerializeToString(query);
var search = JObject.Parse(template);
search.Add("from", "{{from}}{{^from}}0{{/from}}");
search.Add("size", "{{size}}{{^size}}10{{/size}}");
template = client.Serializer.SerializeToString(search);

client.PutSearchTemplate("template-name", ps => ps
    .Template(template)
);

client.GetSearchTemplate("template-name");
    
var searchResponse = client.SearchTemplate<Question>(st => st
    .Index("posts")
    .Id("template-name")
    .Params(p => p
        .Add("query_string", "\"Jon Skeet\" AND \"Chuck Norris\"") 
        .Add("size", 50)
    )
);
1 Like

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