Search templates

Updated at:

Search templates let you encapsulate frequently used query logic, define it once, and reuse it multiple times. With search templates, application developers and data analysts can run queries simply by passing parameters without modifying code or learning complex domain-specific language (DSL) statements. This significantly improves development efficiency and system security.

Benefits

  • Ease of use: Enables quick generation and reuse of query logic, reducing code redundancy and lowering maintenance costs.

  • Security: Restricts execution to predefined templates, which reduces the risk of query injection and ensures system stability.

  • Convenience: Supports automatic template generation and lets you copy them to Kibana for one-click testing.

Use cases

  • Application developers: Encapsulate common query patterns, such as a reusable template for 'category + brand + price range' searches in e-commerce. To call the template, you only need to pass parameters, which eliminates writing repetitive DSL or modifying service code.

  • New users: Automatically generated templates help new users build effective queries quickly without mastering complex DSL syntax.

Limitations

  • ES Serverless will gradually support all Mustache script types. Currently, input scripts must comply with the ES Serverless query whitelist restrictions.

    Note

    Mustache is a logic-less template engine that supports multiple programming languages, such as Python, Java, and JavaScript. It generates dynamic text through variable substitution and conditional or loop structures, and is commonly used for HTML, configuration files, and API responses.

  • You can create a maximum of 10 search templates (that is, Mustache scripts) in a single application. You can submit a request to increase the mustache_script_quota limit to obtain a larger number of templates.

  • A Mustache script cannot exceed 10,240 characters or contain nested scripts.

Note

If you have special requirements, such as changing script limits, submit a ticket to contact technical support.

Access search templates

  1. Go to the application details page.

    1. Log on to the Elasticsearch Serverless console and switch to the desired region in the top navigation bar.

    2. In the left-side navigation pane, click Application Management. Then, click the name of the application that you created to go to the application details page.

  2. In the left-side navigation pane, go to Search Tuning Center > Query Templates. On this page, you can create a new template, view and use templates, and manage templates.

    Note

    All code examples in this topic can be run in Kibana.

Create a template

On the Search Template tab, click Create Template. You can then select Manual Creation or Smart Generation as needed.

Manual creation

  • Create a template in the console

    In the Create Query Template dialog box, select Manual Creation, enter a template name and the template content, and then follow the on-screen instructions. The template name must be unique within the current application and is used to reference the template.

    The following is an example of the template content:

    {
      "query": {
        "match": {
          "{{my_field}}": "{{my_value}}"
        }
      }
    }
    • {{my_field}}: The name of the field to search.

    • {{my_value}}: The keyword to search for.

  • Create a template using the REST API

    The following example shows how to create a template:

    PUT _scripts/{id}
    {
      "script": {
         "lang": "mustache",
         "source": {
           // Edit your script here. The following is an example.
            "query": {
                "match": {
                    "message": "{{query_string}}"
                 }
             },
         "from": "{{from}}",
         "size": "{{size}}"
        }
      }
    }
    • {id}: The unique name for the template within the application. This name is used to reference the template.

    • {{query_string}}: The custom search query.

Automatic inference

In the Create Query Template > Automatic Inference tab. Select an index to query, and the system uses a built-in large language model (LLM) to automatically generate a search template based on the index structure.

Note

You must create an index before using this feature. Because the generated template depends on the index structure, the output is specific to your configuration.

After selecting an index, click Auto-Generate Search Template. The system automatically generates a template ID (such as my-index_document_search), template code, and template description. Verify the information and click OK.

The following example shows a generated search template. This template performs a full-text search on a document index. It supports text-based relevance search and is suitable for fuzzy matching on titles and descriptions.

{
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "{{query_text}}",
            "fields": [
              "title^1.5",
              "description"
            ],
            "type": "best_fields",
            "operator": "or"
          }
        }
      ],
      "filter": [
        {
          "match_all": {}
        }{{#id_filter}},
        {
          "term": {
            "id": "{{id_filter}}"
          }
        }{{/id_filter}}
      ]
    }
  },
  "highlight": {
    "fields": {
      "title": {},
      "description": {}
    }
  },
  "from": "{{from}}{{^from}}0{{/from}}",
  "size": "{{size}}{{^size}}10{{/size}}"
}

View and use templates

  1. After creating a template, you can view it in the following ways:

    • View in the console

      The Query Templates page lists your created templates. To view a template's details, click Edit in the Actions column.

      The editing interface contains a Query Template ID input field and a Query Template Code editor. The template code is an Elasticsearch query statement in JSON format that supports Mustache variables such as {{my_field}} and {{my_value}} as placeholders.

    • View using the REST API

      The following is an example, where {id} is the name of your template:

      GET _scripts/{id}
  2. Call the template using the REST API to run a query on a specified index. The following is an example:

    GET {your_index}/_search/template
    {
      "id": "{id}",
      "params": {
        "from": "{{from}}",
        "size": "{{size}}",
        "query_string": "{{query_string}}"
      }
    }
    • {your_index}: The name of the index to query.

    • {id}: The name of the search template to use.

    • params: The list of parameters to pass to the template.

      • {from}: The starting position for pagination.

      • {size}: The number of results to return per page.

      • {query_string}: The search keyword. For example, phone.

Manage templates

On the Query Templates page, you can edit, copy, or delete templates.

  • Edit a template

    • Edit in the console: In the Actions column for the target template, click Edit. You can then edit the content and description of the search template.

    • Edit using the REST API: Use the following code to overwrite the template. {id} is the name of the template to edit.

      PUT _scripts/{id}
      {
        "script": {
           "lang": "mustache",
           "source": {
             // Edit the new template
          }
        }
      }
  • Copy a template: In the Actions column for the target template, click Copy Template to copy its content, which you can then paste into Kibana for testing or use.

  • Delete a template:

    Important

    This operation cannot be reversed. Proceed with caution.

    • Delete in the console: In the Actions column for the target template, click Delete and follow the on-screen instructions.

    • Delete using the REST API: Run the following command to delete the target template. {id} is the name of the template to delete.

      DELETE _scripts/{id}