Skip to content

Latest commit

 

History

History
66 lines (57 loc) · 1.96 KB

File metadata and controls

66 lines (57 loc) · 1.96 KB
endpoint render_search_template
lang go
es_version 9.3
client github.com/elastic/go-elasticsearch/v9

Elasticsearch 9.3 render_search_template endpoint (Go example)

Use client.RenderSearchTemplate() to preview the query that a Mustache template produces without executing it. This is invaluable for debugging templates:

response, err := client.RenderSearchTemplate().
    Request(&rendersearchtemplate.Request{
        Source: strPtr(`{"query": {"match": {"{{field}}": "{{value}}"}}, "size": {{size}}}`),
        Params: map[string]json.RawMessage{
            "field": toRawMessage("category"),
            "value": toRawMessage("electronics"),
            "size":  toRawMessage(10),
        },
    }).
    Do(context.Background())
if err != nil {
    log.Fatalf("Error: %s", err)
}

fmt.Println(string(response.TemplateOutput))

Conditional sections

Use Mustache conditionals to build optional query clauses. Render the template to verify the output with and without the parameter:

template := `{"query": {"bool": {"must": [{"match": {"category": "{{category}}"}}{{#min_price}}, {"range": {"price": {"gte": {{min_price}}}}}{{/min_price}}]}}}`

withFilter, err := client.RenderSearchTemplate().
    Request(&rendersearchtemplate.Request{
        Source: &template,
        Params: map[string]json.RawMessage{
            "category":  toRawMessage("electronics"),
            "min_price": toRawMessage(100),
        },
    }).
    Do(context.Background())
if err != nil {
    log.Fatalf("Error: %s", err)
}
fmt.Println("With filter:", string(withFilter.TemplateOutput))

withoutFilter, err := client.RenderSearchTemplate().
    Request(&rendersearchtemplate.Request{
        Source: &template,
        Params: map[string]json.RawMessage{
            "category": toRawMessage("electronics"),
        },
    }).
    Do(context.Background())
if err != nil {
    log.Fatalf("Error: %s", err)
}
fmt.Println("Without filter:", string(withoutFilter.TemplateOutput))