elasticsearchmustache

Passing a dynamic list of doubles as param value in ElasticSearch templates


I am trying to pass an array of doubles to an ElasticSearch template using the below mustache template

PUT _scripts/my_template
{
  "script": {
    "lang": "mustache",
    "source": {
      "query": {
        "script_score": {
          "query": {
            "match_all": {}
          },
          "script": {
            "source": "knn_score",
            "lang": "knn",
            "params": {
              "field": "{{field}}",
              "query_value": "{{query_value}}",
              "space_type": "{{space_type}}"
            }
          }
        }
      }
    }
  }
}

When I render the template by passing the param values

GET _render/template
{
  "id": "my_template",
  "params": {
    "field": "embeddings_field",
    "query_value": [0.1, 0.2],
    "space_type": "cosinesimil"
  }
}

I get an error about casting String as an ArrayList which I understand.

I have looked in related SO posts but having no luck. This SO post looked promising but I have been only able to get it show as a list of strings rather than list of doubles. The size of the list can itself vary so that is one more downside with the solution.

Is it possible to parameterize this value in the mustache template?

{EDIT} Based on @Val's suggestion I was able to get the rendering working. However when I run the rendered template against the index it gives me an error

GET my_index/_search/template
{
  "id": "my_template",
  "params": {
    "field": "embeddings",
    "query_value": [
            -0.03159378841519356,
            0.0715613141655922
          ],
        "space_type": "cosinesimil"
  }
}

The error I get is

{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"Required [script]"}],"type":"illegal_argument_exception","reason":"Required [script]"},"status":400}

Solution

  • You need to do it this way (+ store the query as a string instead of JSON):

    PUT _scripts/my_template
    {
      "script": {
        "lang": "mustache",
        "source": """
         {
          "query": {
            "script_score": {
              "query": {
                "match_all": {}
              },
              "script": {
                "source": "knn_score",
                "lang": "knn",
                "params": {
                  "field": "{{field}}",
                  "query_value": {{#toJSON}}query_value{{/toJSON}},
                  "space_type": "{{space_type}}"
                }
              }
            }
          }
         }
        """
      }
    }