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

fgw7neuy  于 2022-11-02  发布在  ElasticSearch
关注(0)|答案(2)|浏览(202)

我有下面的代码在我的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中的一个模板,只需将params和search模板从java服务传递到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)

oo7oh9g9

oo7oh9g91#

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());
        });
wvmv3b1j

wvmv3b1j2#

目前还不可能。Spring Data Elasticsearch中有an issue可用于此操作。

相关问题