0

I have below code working fine in my java service.

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

Now, I want to save this query as a template in elastic and just pass params and search template from java service to elastic to execute the query.

Search Template added in Elastic


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

Call this template

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

But unfortunately not able to find API reference for the same to call this search template from JAVA (spring-data-elasticsearch)

3

2 Answers 2

1

As mentioned by val this can be used to call the search template query from 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());
        });
Sign up to request clarification or add additional context in comments.

1 Comment

Glad you figured it out!
0

This is currently not yet possible. There is an issue for this in Spring Data Elasticsearch.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.