Elasticsearch Java - 使用搜索模板进行查询

Elasticsearch Java - use Search Template to query

我的 java 服务中的以下代码运行良好。

 Query searchQuery = new StringQuery(
    "{\"bool\":{\"must\":[{\"match\":{\"id\":\"" + id + "\"}}]}}");
 SearchHits<Instance> instanceSearchHits = elasticsearchOperations.search(searchQuery, Instance.class, IndexCoordinates.of("test"));
  log.info("hits :: " + instanceSearchHits.getSearchHits().size());
           

现在,我想将此查询保存为 elastic 中的模板,只需将参数和搜索模板从 java 服务传递到 elastic 即可执行查询。

在 Elastic 中添加了搜索模板


PUT _scripts/search-template-1
{
  "script": {
    "lang": "mustache",
    "source": {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "id": "{{id}}"
              }
            }
          ]
        }
      }
    },
    "params": {
      "id": "id to search"
    }
  }
}

调用此模板

GET test/_search/template
{
  "id": "search-template-1",
  "params": {
    "id": "f52c2c62-e921-4410-847f-25ea0f3eeb40"
  }
}

但遗憾的是无法找到 API 参考以从 JAVA (spring-data-elasticsearch)

中调用此搜索模板

val 所述,这可用于从 java

调用搜索模板查询
SearchTemplateRequest request = new SearchTemplateRequest();
request.setRequest(new SearchRequest("posts"));

request.setScriptType(ScriptType.STORED);
request.setScript("title_search");

Map<String, Object> params = new HashMap<>();
params.put("field", "title");
params.put("value", "elasticsearch");
params.put("size", 5);
request.setScriptParams(params);

 SearchTemplateResponse response = client.searchTemplate(request, RequestOptions.DEFAULT);
        SearchResponse searchResponse = response.getResponse();
        SearchHits searchHits = searchResponse.getHits();
        log.info("hits :: " + searchHits.getMaxScore());
        searchHits.forEach(searchHit -> {
            log.info("this is the response, " + searchHit.getSourceAsString());
        });

这目前还不可能。在 Spring Data Elasticsearch 中有 an issue