Search Template

Allows you to use the mustache language to pre render search requests.

  1. GET _search/template
  2. {
  3. "source" : {
  4. "query": { "match" : { "{{my_field}}" : "{{my_value}}" } },
  5. "size" : "{{my_size}}"
  6. },
  7. "params" : {
  8. "my_field" : "message",
  9. "my_value" : "foo",
  10. "my_size" : 5
  11. }
  12. }

Request

GET _search/template

Description

The /_search/template endpoint allows you to use the mustache language to pre- render search requests, before they are executed and fill existing templates with template parameters.

For more information on how Mustache templating and what kind of templating you can do with it check out the online documentation of the mustache project.

The mustache language is implemented in Elasticsearch as a sandboxed scripting language, hence it obeys settings that may be used to enable or disable scripts per type and context as described in the scripting docs.

Path parameters

<index>

(Optional, string) Comma-separated list or wildcard expression of index names used to limit the request.

Query parameters

allow_no_indices

(Optional, boolean) If true, the request does not return an error if a wildcard expression or _all value retrieves only missing or closed indices.

This parameter also applies to index aliases that point to a missing or closed index.

Defaults to true.

ccs_minimize_roundtrips

(Optional, boolean) If true, network round-trips are minimized for cross-cluster search requests. Defaults to true.

expand_wildcards

(Optional, string) Controls what kind of indices that wildcard expressions can expand to. Multiple values are accepted when separated by a comma, as in open,hidden. Valid values are:

  • all

    Expand to open and closed indices, including hidden indices.

    open

    Expand only to open indices.

    closed

    Expand only to closed indices.

    hidden

    Expansion of wildcards will include hidden indices. Must be combined with open, closed, or both.

    none

    Wildcard expressions are not accepted.

explain

(Optional, boolean) If true, the response includes additional details about score computation as part of a hit. Defaults to false.

ignore_throttled

(Optional, boolean) If true, specified concrete, expanded or aliased indices are not included in the response when throttled. Defaults to true.

ignore_unavailable

(Optional, boolean) If true, missing or closed indices are not included in the response. Defaults to false.

preference

(Optional, string) Specifies the node or shard the operation should be performed on. Random by default.

profile

(Optional, boolean) If true, the query execution is profiled. Defaults to false.

rest_total_hits_as_int

(Optional, boolean) If true, hits.total are rendered as an integer in the response. Defaults to false.

routing

(Optional, string) Target the specified primary shard.

scroll

(Optional, time units) Specifies how long a consistent view of the index should be maintained for scrolled search.

search_type

(Optional, string) The type of the search operation. Available options:

  • query_then_fetch
  • dfs_query_then_fetch

typed_keys

(Optional, boolean) If true, aggregation and suggester names are prefixed by their respective types in the response. Defaults to false.

Request body

The API request body must contain the search definition template and its parameters.

Response codes

Store a search template

You can store a search template using the stored scripts API.

  1. POST _scripts/<templateid>
  2. {
  3. "script": {
  4. "lang": "mustache",
  5. "source": {
  6. "query": {
  7. "match": {
  8. "title": "{{query_string}}"
  9. }
  10. }
  11. }
  12. }
  13. }

The template can be retrieved by calling

  1. GET _scripts/<templateid>

The API returns the following result:

  1. {
  2. "script" : {
  3. "lang" : "mustache",
  4. "source" : "{\"query\":{\"match\":{\"title\":\"{{query_string}}\"}}}",
  5. "options": {
  6. "content_type" : "application/json; charset=UTF-8"
  7. }
  8. },
  9. "_id": "<templateid>",
  10. "found": true
  11. }

This template can be deleted by calling

  1. DELETE _scripts/<templateid>

Using a stored search template

To use a stored template at search time send the following request:

  1. GET _search/template
  2. {
  3. "id": "<templateid>",
  4. "params": {
  5. "query_string": "search for these words"
  6. }
  7. }

Name of the stored template script.

Validating a search template

A template can be rendered in a response with given parameters by using the following request:

  1. GET _render/template
  2. {
  3. "source": "{ \"query\": { \"terms\": {{#toJson}}statuses{{/toJson}} }}",
  4. "params": {
  5. "statuses" : {
  6. "status": [ "pending", "published" ]
  7. }
  8. }
  9. }

The API returns the rendered template:

  1. {
  2. "template_output": {
  3. "query": {
  4. "terms": {
  5. "status": [
  6. "pending",
  7. "published"
  8. ]
  9. }
  10. }
  11. }
  12. }

status array has been populated with values from the params object.

Stored templates can also be rendered by calling the following request:

  1. GET _render/template/<template_name>
  2. {
  3. "params": {
  4. "..."
  5. }
  6. }

Using the explain parameter

You can use the explain parameter when running a template:

  1. GET _search/template
  2. {
  3. "id": "my_template",
  4. "params": {
  5. "status": [ "pending", "published" ]
  6. },
  7. "explain": true
  8. }

Profiling

You can use the profile parameter when running a template:

  1. GET _search/template
  2. {
  3. "id": "my_template",
  4. "params": {
  5. "status": [ "pending", "published" ]
  6. },
  7. "profile": true
  8. }

Filling in a query string with a single value

  1. GET _search/template
  2. {
  3. "source": {
  4. "query": {
  5. "term": {
  6. "message": "{{query_string}}"
  7. }
  8. }
  9. },
  10. "params": {
  11. "query_string": "search for these words"
  12. }
  13. }

Converting parameters to JSON

The {{#toJson}}parameter{{/toJson}} function can be used to convert parameters like maps and array to their JSON representation:

  1. GET _search/template
  2. {
  3. "source": "{ \"query\": { \"terms\": {{#toJson}}statuses{{/toJson}} }}",
  4. "params": {
  5. "statuses" : {
  6. "status": [ "pending", "published" ]
  7. }
  8. }
  9. }

which is rendered as:

  1. {
  2. "query": {
  3. "terms": {
  4. "status": [
  5. "pending",
  6. "published"
  7. ]
  8. }
  9. }
  10. }

A more complex example substitutes an array of JSON objects:

  1. GET _search/template
  2. {
  3. "source": "{\"query\":{\"bool\":{\"must\": {{#toJson}}clauses{{/toJson}} }}}",
  4. "params": {
  5. "clauses": [
  6. { "term": { "user" : "foo" } },
  7. { "term": { "user" : "bar" } }
  8. ]
  9. }
  10. }

which is rendered as:

  1. {
  2. "query": {
  3. "bool": {
  4. "must": [
  5. {
  6. "term": {
  7. "user": "foo"
  8. }
  9. },
  10. {
  11. "term": {
  12. "user": "bar"
  13. }
  14. }
  15. ]
  16. }
  17. }
  18. }

Concatenating array of values

The {{#join}}array{{/join}} function can be used to concatenate the values of an array as a comma delimited string:

  1. GET _search/template
  2. {
  3. "source": {
  4. "query": {
  5. "match": {
  6. "emails": "{{#join}}emails{{/join}}"
  7. }
  8. }
  9. },
  10. "params": {
  11. "emails": [ "username@email.com", "lastname@email.com" ]
  12. }
  13. }

which is rendered as:

  1. {
  2. "query" : {
  3. "match" : {
  4. "emails" : "username@email.com,lastname@email.com"
  5. }
  6. }
  7. }

The function also accepts a custom delimiter:

  1. GET _search/template
  2. {
  3. "source": {
  4. "query": {
  5. "range": {
  6. "born": {
  7. "gte" : "{{date.min}}",
  8. "lte" : "{{date.max}}",
  9. "format": "{{#join delimiter='||'}}date.formats{{/join delimiter='||'}}"
  10. }
  11. }
  12. }
  13. },
  14. "params": {
  15. "date": {
  16. "min": "2016",
  17. "max": "31/12/2017",
  18. "formats": ["dd/MM/yyyy", "yyyy"]
  19. }
  20. }
  21. }

which is rendered as:

  1. {
  2. "query": {
  3. "range": {
  4. "born": {
  5. "gte": "2016",
  6. "lte": "31/12/2017",
  7. "format": "dd/MM/yyyy||yyyy"
  8. }
  9. }
  10. }
  11. }

Default values

A default value is written as {{var}}{{^var}}default{{/var}} for instance:

  1. {
  2. "source": {
  3. "query": {
  4. "range": {
  5. "line_no": {
  6. "gte": "{{start}}",
  7. "lte": "{{end}}{{^end}}20{{/end}}"
  8. }
  9. }
  10. }
  11. },
  12. "params": { ... }
  13. }

When params is { "start": 10, "end": 15 } this query would be rendered as:

  1. {
  2. "range": {
  3. "line_no": {
  4. "gte": "10",
  5. "lte": "15"
  6. }
  7. }
  8. }

But when params is { "start": 10 } this query would use the default value for end:

  1. {
  2. "range": {
  3. "line_no": {
  4. "gte": "10",
  5. "lte": "20"
  6. }
  7. }
  8. }

Conditional clauses

Conditional clauses cannot be expressed using the JSON form of the template. Instead, the template must be passed as a string. For instance, let’s say we wanted to run a match query on the line field, and optionally wanted to filter by line numbers, where start and end are optional.

The params would look like:

  1. {
  2. "params": {
  3. "text": "words to search for",
  4. "line_no": {
  5. "start": 10,
  6. "end": 20
  7. }
  8. }
  9. }

The line_no, start, and end parameters are optional.

When written as a query, the template would include invalid JSON, such as section markers like {{#line_no}}:

  1. {
  2. "query": {
  3. "bool": {
  4. "must": {
  5. "match": {
  6. "line": "{{text}}"
  7. }
  8. },
  9. "filter": {
  10. {{#line_no}}
  11. "range": {
  12. "line_no": {
  13. {{#start}}
  14. "gte": "{{start}}"
  15. {{#end}},{{/end}}
  16. {{/start}}
  17. {{#end}}
  18. "lte": "{{end}}"
  19. {{/end}}
  20. }
  21. }
  22. {{/line_no}}
  23. }
  24. }
  25. }
  26. }

Fill in the value of param text

Include the range filter only if line_no is specified

Include the gte clause only if line_no.start is specified

Fill in the value of param line_no.start

Add a comma after the gte clause only if line_no.start AND line_no.end are specified

Include the lte clause only if line_no.end is specified

Fill in the value of param line_no.end

Because search templates cannot include invalid JSON, you can pass the same query as a string instead:

  1. "source": "{\"query\":{\"bool\":{\"must\":{\"match\":{\"line\":\"{{text}}\"}},\"filter\":{{{#line_no}}\"range\":{\"line_no\":{{{#start}}\"gte\":\"{{start}}\"{{#end}},{{/end}}{{/start}}{{#end}}\"lte\":\"{{end}}\"{{/end}}}}{{/line_no}}}}}}"

Encoding URLs

The {{#url}}value{{/url}} function can be used to encode a string value in a HTML encoding form as defined in by the HTML specification.

As an example, it is useful to encode a URL:

  1. GET _render/template
  2. {
  3. "source": {
  4. "query": {
  5. "term": {
  6. "http_access_log": "{{#url}}{{host}}/{{page}}{{/url}}"
  7. }
  8. }
  9. },
  10. "params": {
  11. "host": "https://www.elastic.co/",
  12. "page": "learn"
  13. }
  14. }

The previous query will be rendered as:

  1. {
  2. "template_output": {
  3. "query": {
  4. "term": {
  5. "http_access_log": "https%3A%2F%2Fwww.elastic.co%2F%2Flearn"
  6. }
  7. }
  8. }
  9. }