How to Use Elasticsearch Search Templates for Batch Terms Queries
This article explains why a terms query with an array fails inside an Elasticsearch search template, demonstrates the correct Mustache‑based template syntax, and provides step‑by‑step code examples for defining the index, inserting data, creating the template, and executing the query.
The article starts with a practical question about why a terms query that receives an array inside an Elasticsearch search template fails, and it originates from the "死磕Elasticsearch" knowledge community.
It first shows how to define an index with date and long fields and how to bulk‑insert sample documents using the PUT uint-2020-08-17 and PUT uint-2020-08-17/_bulk APIs.
Next, a full search‑template script is presented. The script is written in Mustache and includes _source , size , a bool filter that combines a terms clause (using the {{#toJson}}statuses{{/toJson}} helper) and a range clause on the clock field, followed by aggregations that compute average and maximum value per itemid .
The concept of a search template is then explained: it is similar to a stored procedure, allowing reusable DSL fragments to be stored on the server and invoked with runtime parameters, thus separating query logic from application code. The Mustache engine is used for templating, and a link to its documentation is provided.
A minimal example that only contains the terms part is given to illustrate two common mistakes: forgetting to escape the JSON string inside source and placing the statuses parameter in the wrong location.
Step‑by‑step, the article shows how to create a correct script ( POST _scripts/test_script_01 ), register it as a template, and then call it with proper parameters ( statuses containing itemid array, startTime , and endTime ). It also advises using a text editor to replace characters globally to avoid syntax errors.
Finally, the complete, working template definition is provided, showing the fully escaped JSON string for source and the correct parameter structure. The article concludes that once the template is understood and correctly built, Elasticsearch queries become much simpler and more maintainable.
References to official Elasticsearch documentation and two external articles are listed for further reading.
DevOps Cloud Academy
Exploring industry DevOps practices and technical expertise.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.