在ElasticSearch模板中传递一个double的动态列表作为参数值

gwo2fgha  于 2023-05-06  发布在  ElasticSearch
关注(0)|答案(1)|浏览(121)

我尝试使用下面的mustache模板将double数组传递给ElasticSearch模板

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}}"
            }
          }
        }
      }
    }
  }
}

当我通过传递参数值来呈现模板时

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

我得到了一个关于将String转换为ArrayList的错误,我理解。
我看过相关的帖子,但没有运气。这个SO帖子看起来很有希望,但我只能让它显示为字符串列表而不是双精度列表。列表的大小本身可以变化,因此这是解决方案的另一个缺点。
是否可以在mustache模板中参数化此值?
{编辑}基于@瓦尔的建议,我能够让渲染工作。然而,当我运行呈现的模板对索引它给我一个错误

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

我得到的错误是

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

57hvy0tb1#

你需要这样做(+将查询存储为字符串而不是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}}"
            }
          }
        }
      }
     }
    """
  }
}

相关问题