Re'em
Re'em

Reputation: 260

Elasticsearch search templates

I tried using ES's search template to do a conditional clause as specified here. I'm sending my request to the /[my_index]/_search/template endpoint. The request fails because of JSON parsing issues, which makes sense because after adding the conditional clause the payload is no longer a valid JSON. How than am I supposed to use the search templates? Is there a designated endpoint for non-JSON templates?

Upvotes: 0

Views: 3882

Answers (2)

Iswarya Rajagopal
Iswarya Rajagopal

Reputation: 21

When using conditional clauses,the template will not be a valid JSON because it will include the section markers {{# like this }}.For this reason, the template should either be stored in a file or, when used via the REST API, should be written as a string.

Method 1 : tempalte stored in a file

  1. Save the query part of the template in config/scripts

    ES installation>Config>scripts

    test_template.mustache

    {
        "query":{ whatever query }
    }
    
  2. you can use the saved template by this method through sense

    GET /_search/template
    {
        "template": "test_template",
        "params": {
            whatever params
        }
    }
    

Method 2: template written as a string

  1. convert the template to string form and use via rest api

    POST /_search/template/test_template { "template": "{\"query\":{ whatever query; remember to escape quotes}}" }

  2. To search using this template,

    GET /_search/template { "template": { "id": "test_template" }, "params": { whatever params } }

Reference: https://www.elastic.co/guide/en/elasticsearch/reference/1.7/search-template.html#_conditional_clauses

Upvotes: 2

itaifrenkel
itaifrenkel

Reputation: 1598

You need to escape the template in wrapping string.

From the same link you referenced:

As written above, this template is not valid JSON because it includes the section markers like {{#line_no}}. For this reason, the template should either be stored in a file (see the section called “Pre-registered templateedit”) or, when used via the REST API, should be written as a string:

"template": "{\"query\":{\"filtered\":{\"query\":{\"match\":{\"line\":\"{{text}}\"}},\"filter\":{{{#line_no}}\"range\":{\"line_no\":{{{#start}}\"gte\":\"{{start}}\"{{#end}},{{/end}}{{/start}}{{#end}}\"lte\":\"{{end}}\"{{/end}}}}{{/line_no}}}}}}"

Upvotes: 0

Related Questions