Skip to content

Commit abc6751

Browse files
committed
HLRest: Add get index templates API (#31161)
Relates #27205
1 parent 197aa9b commit abc6751

File tree

9 files changed

+364
-3
lines changed

9 files changed

+364
-3
lines changed

client/rest-high-level/src/main/java/org/elasticsearch/client/IndicesClient.java

+31
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@
5454
import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsResponse;
5555
import org.elasticsearch.action.admin.indices.shrink.ResizeRequest;
5656
import org.elasticsearch.action.admin.indices.shrink.ResizeResponse;
57+
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesRequest;
58+
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse;
5759
import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest;
5860
import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateResponse;
5961

@@ -1059,4 +1061,33 @@ public void putTemplateAsync(PutIndexTemplateRequest putIndexTemplateRequest, Re
10591061
restHighLevelClient.performRequestAsyncAndParseEntity(putIndexTemplateRequest, RequestConverters::putTemplate, options,
10601062
PutIndexTemplateResponse::fromXContent, listener, emptySet());
10611063
}
1064+
1065+
/**
1066+
* Gets index templates using the Index Templates API
1067+
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html"> Index Templates API
1068+
* on elastic.co</a>
1069+
* @param getIndexTemplatesRequest the request
1070+
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
1071+
* @return the response
1072+
* @throws IOException in case there is a problem sending the request or parsing back the response
1073+
*/
1074+
public GetIndexTemplatesResponse getTemplate(GetIndexTemplatesRequest getIndexTemplatesRequest,
1075+
RequestOptions options) throws IOException {
1076+
return restHighLevelClient.performRequestAndParseEntity(getIndexTemplatesRequest, RequestConverters::getTemplates,
1077+
options, GetIndexTemplatesResponse::fromXContent, emptySet());
1078+
}
1079+
1080+
/**
1081+
* Asynchronously gets index templates using the Index Templates API
1082+
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html"> Index Templates API
1083+
* on elastic.co</a>
1084+
* @param getIndexTemplatesRequest the request
1085+
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
1086+
* @param listener the listener to be notified upon request completion
1087+
*/
1088+
public void getTemplateAsync(GetIndexTemplatesRequest getIndexTemplatesRequest, RequestOptions options,
1089+
ActionListener<GetIndexTemplatesResponse> listener) {
1090+
restHighLevelClient.performRequestAsyncAndParseEntity(getIndexTemplatesRequest, RequestConverters::getTemplates,
1091+
options, GetIndexTemplatesResponse::fromXContent, listener, emptySet());
1092+
}
10621093
}

client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java

+11
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest;
5656
import org.elasticsearch.action.admin.indices.shrink.ResizeRequest;
5757
import org.elasticsearch.action.admin.indices.shrink.ResizeType;
58+
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesRequest;
5859
import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest;
5960
import org.elasticsearch.action.bulk.BulkRequest;
6061
import org.elasticsearch.action.delete.DeleteRequest;
@@ -841,6 +842,16 @@ static Request putTemplate(PutIndexTemplateRequest putIndexTemplateRequest) thro
841842
return request;
842843
}
843844

845+
static Request getTemplates(GetIndexTemplatesRequest getIndexTemplatesRequest) throws IOException {
846+
String[] names = getIndexTemplatesRequest.names();
847+
String endpoint = new EndpointBuilder().addPathPartAsIs("_template").addCommaSeparatedPathParts(names).build();
848+
Request request = new Request(HttpGet.METHOD_NAME, endpoint);
849+
Params params = new Params(request);
850+
params.withLocal(getIndexTemplatesRequest.local());
851+
params.withMasterTimeout(getIndexTemplatesRequest.masterNodeTimeout());
852+
return request;
853+
}
854+
844855
private static HttpEntity createEntity(ToXContent toXContent, XContentType xContentType) throws IOException {
845856
BytesRef source = XContentHelper.toXContent(toXContent, xContentType, false).toBytesRef();
846857
return new ByteArrayEntity(source.bytes, source.offset, source.length, createContentType(xContentType));

client/rest-high-level/src/test/java/org/elasticsearch/client/IndicesClientIT.java

+51
Original file line numberDiff line numberDiff line change
@@ -60,13 +60,16 @@
6060
import org.elasticsearch.action.admin.indices.shrink.ResizeRequest;
6161
import org.elasticsearch.action.admin.indices.shrink.ResizeResponse;
6262
import org.elasticsearch.action.admin.indices.shrink.ResizeType;
63+
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesRequest;
64+
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse;
6365
import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest;
6466
import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateResponse;
6567
import org.elasticsearch.action.index.IndexRequest;
6668
import org.elasticsearch.action.support.IndicesOptions;
6769
import org.elasticsearch.action.support.WriteRequest;
6870
import org.elasticsearch.action.support.broadcast.BroadcastResponse;
6971
import org.elasticsearch.cluster.metadata.IndexMetaData;
72+
import org.elasticsearch.cluster.metadata.IndexTemplateMetaData;
7073
import org.elasticsearch.common.ValidationException;
7174
import org.elasticsearch.common.settings.Setting;
7275
import org.elasticsearch.common.settings.Settings;
@@ -89,6 +92,7 @@
8992
import static org.elasticsearch.common.xcontent.support.XContentMapValues.extractRawValues;
9093
import static org.elasticsearch.common.xcontent.support.XContentMapValues.extractValue;
9194
import static org.hamcrest.CoreMatchers.hasItem;
95+
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
9296
import static org.hamcrest.Matchers.contains;
9397
import static org.hamcrest.Matchers.containsString;
9498
import static org.hamcrest.Matchers.equalTo;
@@ -999,4 +1003,51 @@ public void testPutTemplateBadRequests() throws Exception {
9991003
() -> execute(unknownSettingTemplate, client.indices()::putTemplate, client.indices()::putTemplateAsync));
10001004
assertThat(unknownSettingError.getDetailedMessage(), containsString("unknown setting [index.this-setting-does-not-exist]"));
10011005
}
1006+
1007+
public void testGetIndexTemplate() throws Exception {
1008+
RestHighLevelClient client = highLevelClient();
1009+
1010+
PutIndexTemplateRequest putTemplate1 = new PutIndexTemplateRequest().name("template-1")
1011+
.patterns(Arrays.asList("pattern-1", "name-1")).alias(new Alias("alias-1"));
1012+
assertThat(execute(putTemplate1, client.indices()::putTemplate, client.indices()::putTemplateAsync).isAcknowledged(),
1013+
equalTo(true));
1014+
PutIndexTemplateRequest putTemplate2 = new PutIndexTemplateRequest().name("template-2")
1015+
.patterns(Arrays.asList("pattern-2", "name-2"))
1016+
.settings(Settings.builder().put("number_of_shards", "2").put("number_of_replicas", "0"));
1017+
assertThat(execute(putTemplate2, client.indices()::putTemplate, client.indices()::putTemplateAsync).isAcknowledged(),
1018+
equalTo(true));
1019+
1020+
GetIndexTemplatesResponse getTemplate1 = execute(new GetIndexTemplatesRequest().names("template-1"),
1021+
client.indices()::getTemplate, client.indices()::getTemplateAsync);
1022+
assertThat(getTemplate1.getIndexTemplates(), hasSize(1));
1023+
IndexTemplateMetaData template1 = getTemplate1.getIndexTemplates().get(0);
1024+
assertThat(template1.name(), equalTo("template-1"));
1025+
assertThat(template1.patterns(), contains("pattern-1", "name-1"));
1026+
assertTrue(template1.aliases().containsKey("alias-1"));
1027+
1028+
GetIndexTemplatesResponse getTemplate2 = execute(new GetIndexTemplatesRequest().names("template-2"),
1029+
client.indices()::getTemplate, client.indices()::getTemplateAsync);
1030+
assertThat(getTemplate2.getIndexTemplates(), hasSize(1));
1031+
IndexTemplateMetaData template2 = getTemplate2.getIndexTemplates().get(0);
1032+
assertThat(template2.name(), equalTo("template-2"));
1033+
assertThat(template2.patterns(), contains("pattern-2", "name-2"));
1034+
assertTrue(template2.aliases().isEmpty());
1035+
assertThat(template2.settings().get("index.number_of_shards"), equalTo("2"));
1036+
assertThat(template2.settings().get("index.number_of_replicas"), equalTo("0"));
1037+
1038+
GetIndexTemplatesRequest getBothRequest = new GetIndexTemplatesRequest();
1039+
if (randomBoolean()) {
1040+
getBothRequest.names("*-1", "template-2");
1041+
} else {
1042+
getBothRequest.names("template-*");
1043+
}
1044+
GetIndexTemplatesResponse getBoth = execute(getBothRequest, client.indices()::getTemplate, client.indices()::getTemplateAsync);
1045+
assertThat(getBoth.getIndexTemplates(), hasSize(2));
1046+
assertThat(getBoth.getIndexTemplates().stream().map(IndexTemplateMetaData::getName).toArray(),
1047+
arrayContainingInAnyOrder("template-1", "template-2"));
1048+
1049+
ElasticsearchException notFound = expectThrows(ElasticsearchException.class, () -> execute(
1050+
new GetIndexTemplatesRequest().names("the-template-*"), client.indices()::getTemplate, client.indices()::getTemplateAsync));
1051+
assertThat(notFound.status(), equalTo(RestStatus.NOT_FOUND));
1052+
}
10021053
}

client/rest-high-level/src/test/java/org/elasticsearch/client/RequestConvertersTests.java

+20
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest;
5858
import org.elasticsearch.action.admin.indices.shrink.ResizeRequest;
5959
import org.elasticsearch.action.admin.indices.shrink.ResizeType;
60+
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesRequest;
6061
import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest;
6162
import org.elasticsearch.action.bulk.BulkRequest;
6263
import org.elasticsearch.action.bulk.BulkShardRequest;
@@ -140,6 +141,7 @@
140141
import java.util.function.Consumer;
141142
import java.util.function.Function;
142143
import java.util.function.Supplier;
144+
import java.util.stream.Collectors;
143145

144146
import static java.util.Collections.singletonMap;
145147
import static org.elasticsearch.client.RequestConverters.REQUEST_BODY_CONTENT_TYPE;
@@ -1812,6 +1814,24 @@ public void testPutTemplateRequest() throws Exception {
18121814
assertToXContentBody(putTemplateRequest, request.getEntity());
18131815
}
18141816

1817+
public void testGetTemplateRequest() throws Exception {
1818+
Map<String, String> encodes = new HashMap<>();
1819+
encodes.put("log", "log");
1820+
encodes.put("1", "1");
1821+
encodes.put("template#1", "template%231");
1822+
encodes.put("template-*", "template-*");
1823+
encodes.put("foo^bar", "foo%5Ebar");
1824+
List<String> names = randomSubsetOf(1, encodes.keySet());
1825+
GetIndexTemplatesRequest getTemplatesRequest = new GetIndexTemplatesRequest().names(names.toArray(new String[0]));
1826+
Map<String, String> expectedParams = new HashMap<>();
1827+
setRandomMasterTimeout(getTemplatesRequest, expectedParams);
1828+
setRandomLocal(getTemplatesRequest, expectedParams);
1829+
Request request = RequestConverters.getTemplates(getTemplatesRequest);
1830+
assertThat(request.getEndpoint(), equalTo("/_template/" + names.stream().map(encodes::get).collect(Collectors.joining(","))));
1831+
assertThat(request.getParameters(), equalTo(expectedParams));
1832+
assertThat(request.getEntity(), nullValue());
1833+
}
1834+
18151835
private static void assertToXContentBody(ToXContent expectedBody, HttpEntity actualEntity) throws IOException {
18161836
BytesReference expectedBytes = XContentHelper.toXContent(expectedBody, REQUEST_BODY_CONTENT_TYPE, false);
18171837
assertEquals(XContentType.JSON.mediaTypeWithoutParameters(), actualEntity.getContentType().getValue());

client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/IndicesClientDocumentationIT.java

+72
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@
5858
import org.elasticsearch.action.admin.indices.shrink.ResizeRequest;
5959
import org.elasticsearch.action.admin.indices.shrink.ResizeResponse;
6060
import org.elasticsearch.action.admin.indices.shrink.ResizeType;
61+
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesRequest;
62+
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse;
6163
import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest;
6264
import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateResponse;
6365
import org.elasticsearch.action.support.ActiveShardCount;
@@ -67,6 +69,7 @@
6769
import org.elasticsearch.client.RequestOptions;
6870
import org.elasticsearch.client.RestHighLevelClient;
6971
import org.elasticsearch.client.SyncedFlushResponse;
72+
import org.elasticsearch.cluster.metadata.IndexTemplateMetaData;
7073
import org.elasticsearch.cluster.metadata.MappingMetaData;
7174
import org.elasticsearch.common.collect.ImmutableOpenMap;
7275
import org.elasticsearch.common.settings.Settings;
@@ -82,11 +85,13 @@
8285
import java.io.IOException;
8386
import java.util.Arrays;
8487
import java.util.HashMap;
88+
import java.util.List;
8589
import java.util.Map;
8690
import java.util.concurrent.CountDownLatch;
8791
import java.util.concurrent.TimeUnit;
8892

8993
import static org.hamcrest.Matchers.equalTo;
94+
import static org.hamcrest.Matchers.hasSize;
9095

9196
/**
9297
* This class is used to generate the Java Indices API documentation.
@@ -1982,4 +1987,71 @@ public void onFailure(Exception e) {
19821987

19831988
assertTrue(latch.await(30L, TimeUnit.SECONDS));
19841989
}
1990+
1991+
public void testGetTemplates() throws Exception {
1992+
RestHighLevelClient client = highLevelClient();
1993+
{
1994+
PutIndexTemplateRequest putRequest = new PutIndexTemplateRequest("my-template");
1995+
putRequest.patterns(Arrays.asList("pattern-1", "log-*"));
1996+
putRequest.settings(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 1));
1997+
putRequest.mapping("tweet",
1998+
"{\n" +
1999+
" \"tweet\": {\n" +
2000+
" \"properties\": {\n" +
2001+
" \"message\": {\n" +
2002+
" \"type\": \"text\"\n" +
2003+
" }\n" +
2004+
" }\n" +
2005+
" }\n" +
2006+
"}", XContentType.JSON);
2007+
assertTrue(client.indices().putTemplate(putRequest, RequestOptions.DEFAULT).isAcknowledged());
2008+
}
2009+
2010+
// tag::get-templates-request
2011+
GetIndexTemplatesRequest request = new GetIndexTemplatesRequest("my-template"); // <1>
2012+
request.names("template-1", "template-2"); // <2>
2013+
request.names("my-*"); // <3>
2014+
// end::get-templates-request
2015+
2016+
// tag::get-templates-request-masterTimeout
2017+
request.masterNodeTimeout(TimeValue.timeValueMinutes(1)); // <1>
2018+
request.masterNodeTimeout("1m"); // <2>
2019+
// end::get-templates-request-masterTimeout
2020+
2021+
// tag::get-templates-execute
2022+
GetIndexTemplatesResponse getTemplatesResponse = client.indices().getTemplate(request, RequestOptions.DEFAULT);
2023+
// end::get-templates-execute
2024+
2025+
// tag::get-templates-response
2026+
List<IndexTemplateMetaData> templates = getTemplatesResponse.getIndexTemplates(); // <1>
2027+
// end::get-templates-response
2028+
2029+
assertThat(templates, hasSize(1));
2030+
assertThat(templates.get(0).name(), equalTo("my-template"));
2031+
2032+
// tag::get-templates-execute-listener
2033+
ActionListener<GetIndexTemplatesResponse> listener =
2034+
new ActionListener<GetIndexTemplatesResponse>() {
2035+
@Override
2036+
public void onResponse(GetIndexTemplatesResponse response) {
2037+
// <1>
2038+
}
2039+
2040+
@Override
2041+
public void onFailure(Exception e) {
2042+
// <2>
2043+
}
2044+
};
2045+
// end::get-templates-execute-listener
2046+
2047+
// Replace the empty listener by a blocking listener in test
2048+
final CountDownLatch latch = new CountDownLatch(1);
2049+
listener = new LatchedActionListener<>(listener, latch);
2050+
2051+
// tag::get-templates-execute-async
2052+
client.indices().getTemplateAsync(request, RequestOptions.DEFAULT, listener); // <1>
2053+
// end::get-templates-execute-async
2054+
2055+
assertTrue(latch.await(30L, TimeUnit.SECONDS));
2056+
}
19852057
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
[[java-rest-high-get-templates]]
2+
=== Get Templates API
3+
4+
The Get Templates API allows to retrieve a list of index templates by name.
5+
6+
[[java-rest-high-get-templates-request]]
7+
==== Get Index Templates Request
8+
9+
A `GetIndexTemplatesRequest` specifies one or several names of the index templates to get.
10+
11+
["source","java",subs="attributes,callouts,macros"]
12+
--------------------------------------------------
13+
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[get-templates-request]
14+
--------------------------------------------------
15+
<1> A single index template name
16+
<2> Multiple index template names
17+
<3> An index template name using wildcard
18+
19+
["source","java",subs="attributes,callouts,macros"]
20+
--------------------------------------------------
21+
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[get-templates-request-masterTimeout]
22+
--------------------------------------------------
23+
<1> Timeout to connect to the master node as a `TimeValue`
24+
<2> Timeout to connect to the master node as a `String`
25+
26+
[[java-rest-high-get-templates-sync]]
27+
==== Synchronous Execution
28+
29+
["source","java",subs="attributes,callouts,macros"]
30+
--------------------------------------------------
31+
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[get-templates-execute]
32+
--------------------------------------------------
33+
34+
[[java-rest-high-get-templates-async]]
35+
==== Asynchronous Execution
36+
37+
The asynchronous execution of a get index templates request requires a `GetTemplatesRequest`
38+
instance and an `ActionListener` instance to be passed to the asynchronous
39+
method:
40+
41+
["source","java",subs="attributes,callouts,macros"]
42+
--------------------------------------------------
43+
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[get-templates-execute-async]
44+
--------------------------------------------------
45+
<1> The `GetTemplatesRequest` to execute and the `ActionListener` to use when
46+
the execution completes
47+
48+
The asynchronous method does not block and returns immediately. Once it is
49+
completed the `ActionListener` is called back using the `onResponse` method
50+
if the execution successfully completed or using the `onFailure` method if
51+
it failed.
52+
53+
A typical listener for `GetTemplatesResponse` looks like:
54+
55+
["source","java",subs="attributes,callouts,macros"]
56+
--------------------------------------------------
57+
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[get-templates-execute-listener]
58+
--------------------------------------------------
59+
<1> Called when the execution is successfully completed. The response is
60+
provided as an argument
61+
<2> Called in case of failure. The raised exception is provided as an argument
62+
63+
[[java-rest-high-get-templates-response]]
64+
==== Get Templates Response
65+
66+
The returned `GetTemplatesResponse` consists a list of matching index templates.
67+
68+
["source","java",subs="attributes,callouts,macros"]
69+
--------------------------------------------------
70+
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[get-templates-response]
71+
--------------------------------------------------
72+
<1> A list of matching index templates
73+

docs/java-rest/high-level/supported-apis.asciidoc

+2-1
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,9 @@ include::indices/get_mappings.asciidoc[]
9999
include::indices/update_aliases.asciidoc[]
100100
include::indices/exists_alias.asciidoc[]
101101
include::indices/put_settings.asciidoc[]
102-
include::indices/put_template.asciidoc[]
103102
include::indices/get_settings.asciidoc[]
103+
include::indices/put_template.asciidoc[]
104+
include::indices/get_templates.asciidoc[]
104105

105106
== Cluster APIs
106107

0 commit comments

Comments
 (0)