Skip to content

Commit c20cbe5

Browse files
catalin-ursachijavanna
authored andcommitted
Added Create Index support to high-level REST client (#27351)
Relates to #27205
1 parent 75e64f4 commit c20cbe5

File tree

15 files changed

+632
-52
lines changed

15 files changed

+632
-52
lines changed

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

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121

2222
import org.apache.http.Header;
2323
import org.elasticsearch.action.ActionListener;
24+
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
25+
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
2426
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
2527
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
2628

@@ -29,13 +31,13 @@
2931

3032
/**
3133
* A wrapper for the {@link RestHighLevelClient} that provides methods for accessing the Indices API.
32-
*
34+
* <p>
3335
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices.html">Indices API on elastic.co</a>
3436
*/
3537
public final class IndicesClient {
3638
private final RestHighLevelClient restHighLevelClient;
3739

38-
public IndicesClient(RestHighLevelClient restHighLevelClient) {
40+
IndicesClient(RestHighLevelClient restHighLevelClient) {
3941
this.restHighLevelClient = restHighLevelClient;
4042
}
4143

@@ -56,8 +58,32 @@ public DeleteIndexResponse deleteIndex(DeleteIndexRequest deleteIndexRequest, He
5658
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-delete-index.html">
5759
* Delete Index API on elastic.co</a>
5860
*/
59-
public void deleteIndexAsync(DeleteIndexRequest deleteIndexRequest, ActionListener<DeleteIndexResponse> listener, Header... headers) {
61+
public void deleteIndexAsync(DeleteIndexRequest deleteIndexRequest, ActionListener<DeleteIndexResponse> listener,
62+
Header... headers) {
6063
restHighLevelClient.performRequestAsyncAndParseEntity(deleteIndexRequest, Request::deleteIndex, DeleteIndexResponse::fromXContent,
6164
listener, Collections.emptySet(), headers);
6265
}
66+
67+
/**
68+
* Creates an index using the Create Index API
69+
* <p>
70+
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html">
71+
* Create Index API on elastic.co</a>
72+
*/
73+
public CreateIndexResponse createIndex(CreateIndexRequest createIndexRequest, Header... headers) throws IOException {
74+
return restHighLevelClient.performRequestAndParseEntity(createIndexRequest, Request::createIndex, CreateIndexResponse::fromXContent,
75+
Collections.emptySet(), headers);
76+
}
77+
78+
/**
79+
* Asynchronously creates an index using the Create Index API
80+
* <p>
81+
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html">
82+
* Create Index API on elastic.co</a>
83+
*/
84+
public void createIndexAsync(CreateIndexRequest createIndexRequest, ActionListener<CreateIndexResponse> listener,
85+
Header... headers) {
86+
restHighLevelClient.performRequestAsyncAndParseEntity(createIndexRequest, Request::createIndex, CreateIndexResponse::fromXContent,
87+
listener, Collections.emptySet(), headers);
88+
}
6389
}

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import org.apache.http.entity.ContentType;
3030
import org.apache.lucene.util.BytesRef;
3131
import org.elasticsearch.action.DocWriteRequest;
32+
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
3233
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
3334
import org.elasticsearch.action.bulk.BulkRequest;
3435
import org.elasticsearch.action.delete.DeleteRequest;
@@ -137,6 +138,19 @@ static Request deleteIndex(DeleteIndexRequest deleteIndexRequest) {
137138
return new Request(HttpDelete.METHOD_NAME, endpoint, parameters.getParams(), null);
138139
}
139140

141+
static Request createIndex(CreateIndexRequest createIndexRequest) throws IOException {
142+
String endpoint = endpoint(createIndexRequest.indices(), Strings.EMPTY_ARRAY, "");
143+
144+
Params parameters = Params.builder();
145+
parameters.withTimeout(createIndexRequest.timeout());
146+
parameters.withMasterTimeout(createIndexRequest.masterNodeTimeout());
147+
parameters.withWaitForActiveShards(createIndexRequest.waitForActiveShards());
148+
parameters.withUpdateAllTypes(createIndexRequest.updateAllTypes());
149+
150+
HttpEntity entity = createEntity(createIndexRequest, REQUEST_BODY_CONTENT_TYPE);
151+
return new Request(HttpPut.METHOD_NAME, endpoint, parameters.getParams(), entity);
152+
}
153+
140154
static Request info() {
141155
return new Request(HttpGet.METHOD_NAME, "/", Collections.emptyMap(), null);
142156
}
@@ -534,6 +548,13 @@ Params withTimeout(TimeValue timeout) {
534548
return putParam("timeout", timeout);
535549
}
536550

551+
Params withUpdateAllTypes(boolean updateAllTypes) {
552+
if (updateAllTypes) {
553+
return putParam("update_all_types", Boolean.TRUE.toString());
554+
}
555+
return this;
556+
}
557+
537558
Params withVersion(long version) {
538559
if (version != Versions.MATCH_ANY) {
539560
return putParam("version", Long.toString(version));

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

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,88 @@
2020
package org.elasticsearch.client;
2121

2222
import org.elasticsearch.ElasticsearchException;
23+
import org.elasticsearch.action.admin.indices.alias.Alias;
24+
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
25+
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
2326
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
2427
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
28+
import org.elasticsearch.common.settings.Settings;
29+
import org.elasticsearch.common.xcontent.XContentBuilder;
30+
import org.elasticsearch.common.xcontent.XContentHelper;
31+
import org.elasticsearch.common.xcontent.XContentType;
32+
import org.elasticsearch.common.xcontent.json.JsonXContent;
2533
import org.elasticsearch.rest.RestStatus;
2634

2735
import java.io.IOException;
36+
import java.util.Map;
37+
38+
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS;
2839

2940
public class IndicesClientIT extends ESRestHighLevelClientTestCase {
3041

42+
@SuppressWarnings("unchecked")
43+
public void testCreateIndex() throws IOException {
44+
{
45+
// Create index
46+
String indexName = "plain_index";
47+
assertFalse(indexExists(indexName));
48+
49+
CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
50+
51+
CreateIndexResponse createIndexResponse =
52+
execute(createIndexRequest, highLevelClient().indices()::createIndex, highLevelClient().indices()::createIndexAsync);
53+
assertTrue(createIndexResponse.isAcknowledged());
54+
55+
assertTrue(indexExists(indexName));
56+
}
57+
{
58+
// Create index with mappings, aliases and settings
59+
String indexName = "rich_index";
60+
assertFalse(indexExists(indexName));
61+
62+
CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
63+
64+
Alias alias = new Alias("alias_name");
65+
alias.filter("{\"term\":{\"year\":2016}}");
66+
alias.routing("1");
67+
createIndexRequest.alias(alias);
68+
69+
Settings.Builder settings = Settings.builder();
70+
settings.put(SETTING_NUMBER_OF_REPLICAS, 2);
71+
createIndexRequest.settings(settings);
72+
73+
XContentBuilder mappingBuilder = JsonXContent.contentBuilder();
74+
mappingBuilder.startObject().startObject("properties").startObject("field");
75+
mappingBuilder.field("type", "text");
76+
mappingBuilder.endObject().endObject().endObject();
77+
createIndexRequest.mapping("type_name", mappingBuilder);
78+
79+
CreateIndexResponse createIndexResponse =
80+
execute(createIndexRequest, highLevelClient().indices()::createIndex, highLevelClient().indices()::createIndexAsync);
81+
assertTrue(createIndexResponse.isAcknowledged());
82+
83+
Map<String, Object> indexMetaData = getIndexMetadata(indexName);
84+
85+
Map<String, Object> settingsData = (Map) indexMetaData.get("settings");
86+
Map<String, Object> indexSettings = (Map) settingsData.get("index");
87+
assertEquals("2", indexSettings.get("number_of_replicas"));
88+
89+
Map<String, Object> aliasesData = (Map) indexMetaData.get("aliases");
90+
Map<String, Object> aliasData = (Map) aliasesData.get("alias_name");
91+
assertEquals("1", aliasData.get("index_routing"));
92+
Map<String, Object> filter = (Map) aliasData.get("filter");
93+
Map<String, Object> term = (Map) filter.get("term");
94+
assertEquals(2016, term.get("year"));
95+
96+
Map<String, Object> mappingsData = (Map) indexMetaData.get("mappings");
97+
Map<String, Object> typeData = (Map) mappingsData.get("type_name");
98+
Map<String, Object> properties = (Map) typeData.get("properties");
99+
Map<String, Object> field = (Map) properties.get("field");
100+
101+
assertEquals("text", field.get("type"));
102+
}
103+
}
104+
31105
public void testDeleteIndex() throws IOException {
32106
{
33107
// Delete index if exists
@@ -65,4 +139,18 @@ private static boolean indexExists(String index) throws IOException {
65139

66140
return response.getStatusLine().getStatusCode() == 200;
67141
}
142+
143+
@SuppressWarnings("unchecked")
144+
private Map<String, Object> getIndexMetadata(String index) throws IOException {
145+
Response response = client().performRequest("GET", index);
146+
147+
XContentType entityContentType = XContentType.fromMediaTypeOrFormat(response.getEntity().getContentType().getValue());
148+
Map<String, Object> responseEntity = XContentHelper.convertToMap(entityContentType.xContent(), response.getEntity().getContent(),
149+
false);
150+
151+
Map<String, Object> indexMetaData = (Map) responseEntity.get(index);
152+
assertNotNull(indexMetaData);
153+
154+
return indexMetaData;
155+
}
68156
}

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

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import org.apache.http.entity.StringEntity;
2626
import org.apache.http.util.EntityUtils;
2727
import org.elasticsearch.action.DocWriteRequest;
28+
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
2829
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
2930
import org.elasticsearch.action.bulk.BulkRequest;
3031
import org.elasticsearch.action.bulk.BulkShardRequest;
@@ -36,6 +37,7 @@
3637
import org.elasticsearch.action.search.SearchRequest;
3738
import org.elasticsearch.action.search.SearchScrollRequest;
3839
import org.elasticsearch.action.search.SearchType;
40+
import org.elasticsearch.action.support.ActiveShardCount;
3941
import org.elasticsearch.action.support.IndicesOptions;
4042
import org.elasticsearch.action.support.WriteRequest;
4143
import org.elasticsearch.action.support.master.AcknowledgedRequest;
@@ -253,6 +255,34 @@ private static void getAndExistsTest(Function<GetRequest, Request> requestConver
253255
assertEquals(method, request.getMethod());
254256
}
255257

258+
public void testCreateIndex() throws IOException {
259+
CreateIndexRequest createIndexRequest = new CreateIndexRequest();
260+
261+
String indexName = "index-" + randomAlphaOfLengthBetween(2, 5);
262+
263+
createIndexRequest.index(indexName);
264+
265+
Map<String, String> expectedParams = new HashMap<>();
266+
267+
setRandomTimeout(createIndexRequest::timeout, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams);
268+
setRandomMasterTimeout(createIndexRequest, expectedParams);
269+
setRandomWaitForActiveShards(createIndexRequest::waitForActiveShards, expectedParams);
270+
271+
if (randomBoolean()) {
272+
boolean updateAllTypes = randomBoolean();
273+
createIndexRequest.updateAllTypes(updateAllTypes);
274+
if (updateAllTypes) {
275+
expectedParams.put("update_all_types", Boolean.TRUE.toString());
276+
}
277+
}
278+
279+
Request request = Request.createIndex(createIndexRequest);
280+
assertEquals("/" + indexName, request.getEndpoint());
281+
assertEquals(expectedParams, request.getParameters());
282+
assertEquals("PUT", request.getMethod());
283+
assertToXContentBody(createIndexRequest, request.getEntity());
284+
}
285+
256286
public void testDeleteIndex() throws IOException {
257287
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest();
258288

@@ -407,11 +437,7 @@ public void testUpdate() throws IOException {
407437
expectedParams.put("refresh", refreshPolicy.getValue());
408438
}
409439
}
410-
if (randomBoolean()) {
411-
int waitForActiveShards = randomIntBetween(0, 10);
412-
updateRequest.waitForActiveShards(waitForActiveShards);
413-
expectedParams.put("wait_for_active_shards", String.valueOf(waitForActiveShards));
414-
}
440+
setRandomWaitForActiveShards(updateRequest::waitForActiveShards, expectedParams);
415441
if (randomBoolean()) {
416442
long version = randomLong();
417443
updateRequest.version(version);
@@ -1016,6 +1042,14 @@ private static void setRandomMasterTimeout(MasterNodeRequest<?> request, Map<Str
10161042
}
10171043
}
10181044

1045+
private static void setRandomWaitForActiveShards(Consumer<Integer> setter, Map<String, String> expectedParams) {
1046+
if (randomBoolean()) {
1047+
int waitForActiveShards = randomIntBetween(0, 10);
1048+
setter.accept(waitForActiveShards);
1049+
expectedParams.put("wait_for_active_shards", String.valueOf(waitForActiveShards));
1050+
}
1051+
}
1052+
10191053
private static void setRandomRefreshPolicy(ReplicatedWriteRequest<?> request, Map<String, String> expectedParams) {
10201054
if (randomBoolean()) {
10211055
WriteRequest.RefreshPolicy refreshPolicy = randomFrom(WriteRequest.RefreshPolicy.values());

0 commit comments

Comments
 (0)