Search Template is a highly valuable feature in Elasticsearch. It allows the pre-definition of the query structure for search requests, with the ability to pass search parameters during the actual request. This not only makes the request body more concise but also helps avoid errors that may occur when concatenating query structures on the client side.
When search optimization is necessary, modifications to search scripts can be made directly on the Elasticsearch server without the need to redeploy the client. This significantly enhances the efficiency of search optimization.
However, the default scripting languages (mustache
/painless
/expression
) supported by Elasticsearch have relatively limited syntax logic, lacking support for any conditional statements. This imposes significant constraints on the use of Search Template.
By introducing Velocity into Elasticsearch, support for any conditional statements is enabled, making the usage of Search Template more flexible. This provides users with greater customization capabilities for powerful and flexible searches.
version =
elasticsearchVersion
-pluginVersion
optional 1 - use elasticsearch-plugin to install
Tip: Replace [version] in the link with your Elasticsearch version
./bin/elasticsearch-plugin install https://github.com/Ahoo-Wang/elasticsearch-script-velocity/releases/download/v[version]/elasticsearch-script-velocity-[version].zip
optional 2 - download pre-build package from here: Releases
- create plugin folder
cd your-es-root/plugins/ && mkdir elasticsearch-script-velocity
- unzip plugin to folder
your-es-root/plugins/elasticsearch-script-velocity
POST _scripts/templateid
{
"script": {
"lang": "velocity",
"source": {
"query": {
"match": {
"title": "$query_string"
}
}
}
}
}
GET _scripts/templateid
Response:
{
"_id" : "templateid",
"found" : true,
"script" : {
"lang" : "velocity",
"source" : """{"query":{"match":{"title":"$query_string"}}}""",
"options" : {
"content_type" : "application/json; charset=UTF-8"
}
}
}
DELETE _scripts/templateid
GET _search/template
{
"id": "templateid",
"params": {
"query_string": "search for these words"
}
}
GET _render/template/templateid
{
"params": {
"query_string": "search for these words"
}
}
Response:
{
"template_output" : {
"query" : {
"match" : {
"title" : "search for these words"
}
}
}
}
Benchmark Mode Cnt Score Error Units
VelocityScriptEngineBenchmark.executeSearchTemplate thrpt 1020003.447 ops/s