|
24 | 24 | import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
|
25 | 25 | import co.elastic.clients.elasticsearch._types.query_dsl.Query;
|
26 | 26 | import co.elastic.clients.elasticsearch._types.query_dsl.RangeQuery;
|
| 27 | +import co.elastic.clients.elasticsearch.core.PutScriptResponse; |
27 | 28 | import co.elastic.clients.elasticsearch.core.SearchResponse;
|
| 29 | +import co.elastic.clients.elasticsearch.core.SearchTemplateResponse; |
28 | 30 | import co.elastic.clients.elasticsearch.core.search.Hit;
|
29 | 31 | import co.elastic.clients.elasticsearch.core.search.TotalHits;
|
30 | 32 | import co.elastic.clients.elasticsearch.core.search.TotalHitsRelation;
|
@@ -133,4 +135,43 @@ public void searchNested() throws Exception {
|
133 | 135 | }
|
134 | 136 | //end::search-nested
|
135 | 137 | }
|
| 138 | + |
| 139 | + @Test |
| 140 | + public void searchTemplate() throws Exception { |
| 141 | + |
| 142 | + transport.setResult(PutScriptResponse.of(r -> r.acknowledged(true))); |
| 143 | + |
| 144 | + //tag::search-template-script |
| 145 | + // Create a script |
| 146 | + esClient.putScript(r -> r |
| 147 | + .id("query-script") // <1> |
| 148 | + .script(s -> s |
| 149 | + .lang("mustache") |
| 150 | + .source("{\"query\":{\"match\":{\"{{field}}\":\"{{value}}\"}}}") |
| 151 | + )); |
| 152 | + //end::search-template-script |
| 153 | + |
| 154 | + transport.setResult(SearchTemplateResponse.<JsonData>of(r -> r |
| 155 | + .hits(searchResponse.hits()) |
| 156 | + .took(searchResponse.took()) |
| 157 | + .timedOut(false) |
| 158 | + .shards(searchResponse.shards()) |
| 159 | + )); |
| 160 | + |
| 161 | + //tag::search-template-query |
| 162 | + SearchTemplateResponse<Product> response = esClient.searchTemplate(r -> r |
| 163 | + .index("some-index") |
| 164 | + .id("query-script") // <1> |
| 165 | + .params("field", JsonData.of("some-field")) // <2> |
| 166 | + .params("value", JsonData.of("some-data")), |
| 167 | + Product.class |
| 168 | + ); |
| 169 | + |
| 170 | + List<Hit<Product>> hits = response.hits().hits(); |
| 171 | + for (Hit<Product> hit: hits) { |
| 172 | + Product product = hit.source(); |
| 173 | + logger.info("Found product " + product.getSku() + ", score " + hit.score()); |
| 174 | + } |
| 175 | + //end::search-template-query |
| 176 | + } |
136 | 177 | }
|
0 commit comments