Add Close Index API to the high level REST client (#27734)

Add support for _close endpoint to the high level REST client

Relates to #27205
This commit is contained in:
olcbean 2018-01-17 11:47:08 +01:00 committed by Luca Cavanna
parent d32cb8089b
commit b98514c6d9
15 changed files with 511 additions and 70 deletions

View File

@ -21,6 +21,8 @@ package org.elasticsearch.client;
import org.apache.http.Header; import org.apache.http.Header;
import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.close.CloseIndexRequest;
import org.elasticsearch.action.admin.indices.close.CloseIndexResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
@ -51,7 +53,7 @@ public final class IndicesClient {
*/ */
public DeleteIndexResponse deleteIndex(DeleteIndexRequest deleteIndexRequest, Header... headers) throws IOException { public DeleteIndexResponse deleteIndex(DeleteIndexRequest deleteIndexRequest, Header... headers) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(deleteIndexRequest, Request::deleteIndex, DeleteIndexResponse::fromXContent, return restHighLevelClient.performRequestAndParseEntity(deleteIndexRequest, Request::deleteIndex, DeleteIndexResponse::fromXContent,
Collections.emptySet(), headers); Collections.emptySet(), headers);
} }
/** /**
@ -60,10 +62,9 @@ public final class IndicesClient {
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-delete-index.html"> * See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-delete-index.html">
* Delete Index API on elastic.co</a> * Delete Index API on elastic.co</a>
*/ */
public void deleteIndexAsync(DeleteIndexRequest deleteIndexRequest, ActionListener<DeleteIndexResponse> listener, public void deleteIndexAsync(DeleteIndexRequest deleteIndexRequest, ActionListener<DeleteIndexResponse> listener, Header... headers) {
Header... headers) {
restHighLevelClient.performRequestAsyncAndParseEntity(deleteIndexRequest, Request::deleteIndex, DeleteIndexResponse::fromXContent, restHighLevelClient.performRequestAsyncAndParseEntity(deleteIndexRequest, Request::deleteIndex, DeleteIndexResponse::fromXContent,
listener, Collections.emptySet(), headers); listener, Collections.emptySet(), headers);
} }
/** /**
@ -83,10 +84,9 @@ public final class IndicesClient {
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html"> * See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html">
* Create Index API on elastic.co</a> * Create Index API on elastic.co</a>
*/ */
public void createIndexAsync(CreateIndexRequest createIndexRequest, ActionListener<CreateIndexResponse> listener, public void createIndexAsync(CreateIndexRequest createIndexRequest, ActionListener<CreateIndexResponse> listener, Header... headers) {
Header... headers) {
restHighLevelClient.performRequestAsyncAndParseEntity(createIndexRequest, Request::createIndex, CreateIndexResponse::fromXContent, restHighLevelClient.performRequestAsyncAndParseEntity(createIndexRequest, Request::createIndex, CreateIndexResponse::fromXContent,
listener, Collections.emptySet(), headers); listener, Collections.emptySet(), headers);
} }
/** /**
@ -111,4 +111,25 @@ public final class IndicesClient {
listener, Collections.emptySet(), headers); listener, Collections.emptySet(), headers);
} }
/**
* Closes an index using the Close Index API
* <p>
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-open-close.html">
* Close Index API on elastic.co</a>
*/
public CloseIndexResponse closeIndex(CloseIndexRequest closeIndexRequest, Header... headers) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(closeIndexRequest, Request::closeIndex, CloseIndexResponse::fromXContent,
Collections.emptySet(), headers);
}
/**
* Asynchronously closes an index using the Close Index API
* <p>
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-open-close.html">
* Close Index API on elastic.co</a>
*/
public void closeIndexAsync(CloseIndexRequest closeIndexRequest, ActionListener<CloseIndexResponse> listener, Header... headers) {
restHighLevelClient.performRequestAsyncAndParseEntity(closeIndexRequest, Request::closeIndex, CloseIndexResponse::fromXContent,
listener, Collections.emptySet(), headers);
}
} }

View File

@ -29,6 +29,7 @@ import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType; import org.apache.http.entity.ContentType;
import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRef;
import org.elasticsearch.action.DocWriteRequest; import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.admin.indices.close.CloseIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.open.OpenIndexRequest; import org.elasticsearch.action.admin.indices.open.OpenIndexRequest;
@ -153,6 +154,18 @@ public final class Request {
return new Request(HttpPost.METHOD_NAME, endpoint, parameters.getParams(), null); return new Request(HttpPost.METHOD_NAME, endpoint, parameters.getParams(), null);
} }
static Request closeIndex(CloseIndexRequest closeIndexRequest) {
String endpoint = endpoint(closeIndexRequest.indices(), Strings.EMPTY_ARRAY, "_close");
Params parameters = Params.builder();
parameters.withTimeout(closeIndexRequest.timeout());
parameters.withMasterTimeout(closeIndexRequest.masterNodeTimeout());
parameters.withIndicesOptions(closeIndexRequest.indicesOptions());
return new Request(HttpPost.METHOD_NAME, endpoint, parameters.getParams(), null);
}
static Request createIndex(CreateIndexRequest createIndexRequest) throws IOException { static Request createIndex(CreateIndexRequest createIndexRequest) throws IOException {
String endpoint = endpoint(createIndexRequest.indices(), Strings.EMPTY_ARRAY, ""); String endpoint = endpoint(createIndexRequest.indices(), Strings.EMPTY_ARRAY, "");

View File

@ -26,8 +26,6 @@ import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.admin.indices.open.OpenIndexRequest;
import org.elasticsearch.action.admin.indices.open.OpenIndexResponse;
import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteRequest;

View File

@ -21,6 +21,8 @@ package org.elasticsearch.client;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.admin.indices.alias.Alias; import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.close.CloseIndexRequest;
import org.elasticsearch.action.admin.indices.close.CloseIndexResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
@ -28,21 +30,18 @@ import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.open.OpenIndexRequest; import org.elasticsearch.action.admin.indices.open.OpenIndexRequest;
import org.elasticsearch.action.admin.indices.open.OpenIndexResponse; import org.elasticsearch.action.admin.indices.open.OpenIndexResponse;
import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.rest.RestStatus;
import java.io.IOException;
import java.util.Locale;
import static org.hamcrest.Matchers.equalTo;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.rest.RestStatus;
import java.io.IOException;
import java.util.Map; import java.util.Map;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS;
import static org.hamcrest.Matchers.equalTo;
public class IndicesClientIT extends ESRestHighLevelClientTestCase { public class IndicesClientIT extends ESRestHighLevelClientTestCase {
@ -136,57 +135,68 @@ public class IndicesClientIT extends ESRestHighLevelClientTestCase {
} }
public void testOpenExistingIndex() throws IOException { public void testOpenExistingIndex() throws IOException {
String[] indices = randomIndices(1, 5); String index = "index";
for (String index : indices) { createIndex(index);
createIndex(index); closeIndex(index);
closeIndex(index); ResponseException exception = expectThrows(ResponseException.class, () -> client().performRequest("GET", index + "/_search"));
ResponseException exception = expectThrows(ResponseException.class, () -> client().performRequest("GET", index + "/_search")); assertThat(exception.getResponse().getStatusLine().getStatusCode(), equalTo(RestStatus.BAD_REQUEST.getStatus()));
assertThat(exception.getResponse().getStatusLine().getStatusCode(), equalTo(RestStatus.BAD_REQUEST.getStatus())); assertThat(exception.getMessage().contains(index), equalTo(true));
assertThat(exception.getMessage().contains(index), equalTo(true));
}
OpenIndexRequest openIndexRequest = new OpenIndexRequest(indices); OpenIndexRequest openIndexRequest = new OpenIndexRequest(index);
OpenIndexResponse openIndexResponse = execute(openIndexRequest, highLevelClient().indices()::openIndex, OpenIndexResponse openIndexResponse = execute(openIndexRequest, highLevelClient().indices()::openIndex,
highLevelClient().indices()::openIndexAsync); highLevelClient().indices()::openIndexAsync);
assertTrue(openIndexResponse.isAcknowledged()); assertTrue(openIndexResponse.isAcknowledged());
for (String index : indices) { Response response = client().performRequest("GET", index + "/_search");
Response response = client().performRequest("GET", index + "/_search"); assertThat(response.getStatusLine().getStatusCode(), equalTo(RestStatus.OK.getStatus()));
assertThat(response.getStatusLine().getStatusCode(), equalTo(RestStatus.OK.getStatus()));
}
} }
public void testOpenNonExistentIndex() throws IOException { public void testOpenNonExistentIndex() throws IOException {
String[] nonExistentIndices = randomIndices(1, 5); String nonExistentIndex = "non_existent_index";
for (String nonExistentIndex : nonExistentIndices) { assertFalse(indexExists(nonExistentIndex));
assertFalse(indexExists(nonExistentIndex));
}
OpenIndexRequest openIndexRequest = new OpenIndexRequest(nonExistentIndices); OpenIndexRequest openIndexRequest = new OpenIndexRequest(nonExistentIndex);
ElasticsearchException exception = expectThrows(ElasticsearchException.class, ElasticsearchException exception = expectThrows(ElasticsearchException.class,
() -> execute(openIndexRequest, highLevelClient().indices()::openIndex, highLevelClient().indices()::openIndexAsync)); () -> execute(openIndexRequest, highLevelClient().indices()::openIndex, highLevelClient().indices()::openIndexAsync));
assertEquals(RestStatus.NOT_FOUND, exception.status()); assertEquals(RestStatus.NOT_FOUND, exception.status());
OpenIndexRequest lenientOpenIndexRequest = new OpenIndexRequest(nonExistentIndices); OpenIndexRequest lenientOpenIndexRequest = new OpenIndexRequest(nonExistentIndex);
lenientOpenIndexRequest.indicesOptions(IndicesOptions.lenientExpandOpen()); lenientOpenIndexRequest.indicesOptions(IndicesOptions.lenientExpandOpen());
OpenIndexResponse lenientOpenIndexResponse = execute(lenientOpenIndexRequest, highLevelClient().indices()::openIndex, OpenIndexResponse lenientOpenIndexResponse = execute(lenientOpenIndexRequest, highLevelClient().indices()::openIndex,
highLevelClient().indices()::openIndexAsync); highLevelClient().indices()::openIndexAsync);
assertThat(lenientOpenIndexResponse.isAcknowledged(), equalTo(true)); assertThat(lenientOpenIndexResponse.isAcknowledged(), equalTo(true));
OpenIndexRequest strictOpenIndexRequest = new OpenIndexRequest(nonExistentIndices); OpenIndexRequest strictOpenIndexRequest = new OpenIndexRequest(nonExistentIndex);
strictOpenIndexRequest.indicesOptions(IndicesOptions.strictExpandOpen()); strictOpenIndexRequest.indicesOptions(IndicesOptions.strictExpandOpen());
ElasticsearchException strictException = expectThrows(ElasticsearchException.class, ElasticsearchException strictException = expectThrows(ElasticsearchException.class,
() -> execute(openIndexRequest, highLevelClient().indices()::openIndex, highLevelClient().indices()::openIndexAsync)); () -> execute(openIndexRequest, highLevelClient().indices()::openIndex, highLevelClient().indices()::openIndexAsync));
assertEquals(RestStatus.NOT_FOUND, strictException.status()); assertEquals(RestStatus.NOT_FOUND, strictException.status());
} }
private static String[] randomIndices(int minIndicesNum, int maxIndicesNum) { public void testCloseExistingIndex() throws IOException {
int numIndices = randomIntBetween(minIndicesNum, maxIndicesNum); String index = "index";
String[] indices = new String[numIndices]; createIndex(index);
for (int i = 0; i < numIndices; i++) { Response response = client().performRequest("GET", index + "/_search");
indices[i] = "index-" + randomAlphaOfLengthBetween(2, 5).toLowerCase(Locale.ROOT); assertThat(response.getStatusLine().getStatusCode(), equalTo(RestStatus.OK.getStatus()));
}
return indices; CloseIndexRequest closeIndexRequest = new CloseIndexRequest(index);
CloseIndexResponse closeIndexResponse = execute(closeIndexRequest, highLevelClient().indices()::closeIndex,
highLevelClient().indices()::closeIndexAsync);
assertTrue(closeIndexResponse.isAcknowledged());
ResponseException exception = expectThrows(ResponseException.class, () -> client().performRequest("GET", index + "/_search"));
assertThat(exception.getResponse().getStatusLine().getStatusCode(), equalTo(RestStatus.BAD_REQUEST.getStatus()));
assertThat(exception.getMessage().contains(index), equalTo(true));
}
public void testCloseNonExistentIndex() throws IOException {
String nonExistentIndex = "non_existent_index";
assertFalse(indexExists(nonExistentIndex));
CloseIndexRequest closeIndexRequest = new CloseIndexRequest(nonExistentIndex);
ElasticsearchException exception = expectThrows(ElasticsearchException.class,
() -> execute(closeIndexRequest, highLevelClient().indices()::closeIndex, highLevelClient().indices()::closeIndexAsync));
assertEquals(RestStatus.NOT_FOUND, exception.status());
} }
private static void createIndex(String index) throws IOException { private static void createIndex(String index) throws IOException {

View File

@ -25,6 +25,7 @@ import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.DocWriteRequest; import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.admin.indices.close.CloseIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.open.OpenIndexRequest; import org.elasticsearch.action.admin.indices.open.OpenIndexRequest;
@ -325,17 +326,10 @@ public class RequestTests extends ESTestCase {
} }
public void testDeleteIndex() { public void testDeleteIndex() {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(); String[] indices = randomIndicesNames(0, 5);
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indices);
int numIndices = randomIntBetween(0, 5);
String[] indices = new String[numIndices];
for (int i = 0; i < numIndices; i++) {
indices[i] = "index-" + randomAlphaOfLengthBetween(2, 5);
}
deleteIndexRequest.indices(indices);
Map<String, String> expectedParams = new HashMap<>(); Map<String, String> expectedParams = new HashMap<>();
setRandomTimeout(deleteIndexRequest::timeout, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams); setRandomTimeout(deleteIndexRequest::timeout, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams);
setRandomMasterTimeout(deleteIndexRequest, expectedParams); setRandomMasterTimeout(deleteIndexRequest, expectedParams);
@ -349,12 +343,8 @@ public class RequestTests extends ESTestCase {
} }
public void testOpenIndex() { public void testOpenIndex() {
OpenIndexRequest openIndexRequest = new OpenIndexRequest(); String[] indices = randomIndicesNames(1, 5);
int numIndices = randomIntBetween(1, 5); OpenIndexRequest openIndexRequest = new OpenIndexRequest(indices);
String[] indices = new String[numIndices];
for (int i = 0; i < numIndices; i++) {
indices[i] = "index-" + randomAlphaOfLengthBetween(2, 5);
}
openIndexRequest.indices(indices); openIndexRequest.indices(indices);
Map<String, String> expectedParams = new HashMap<>(); Map<String, String> expectedParams = new HashMap<>();
@ -371,6 +361,23 @@ public class RequestTests extends ESTestCase {
assertThat(request.getEntity(), nullValue()); assertThat(request.getEntity(), nullValue());
} }
public void testCloseIndex() {
String[] indices = randomIndicesNames(1, 5);
CloseIndexRequest closeIndexRequest = new CloseIndexRequest(indices);
Map<String, String> expectedParams = new HashMap<>();
setRandomTimeout(closeIndexRequest::timeout, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams);
setRandomMasterTimeout(closeIndexRequest, expectedParams);
setRandomIndicesOptions(closeIndexRequest::indicesOptions, closeIndexRequest::indicesOptions, expectedParams);
Request request = Request.closeIndex(closeIndexRequest);
StringJoiner endpoint = new StringJoiner("/", "/", "").add(String.join(",", indices)).add("_close");
assertThat(endpoint.toString(), equalTo(request.getEndpoint()));
assertThat(expectedParams, equalTo(request.getParameters()));
assertThat(request.getMethod(), equalTo("POST"));
assertThat(request.getEntity(), nullValue());
}
public void testIndex() throws IOException { public void testIndex() throws IOException {
String index = randomAlphaOfLengthBetween(3, 10); String index = randomAlphaOfLengthBetween(3, 10);
String type = randomAlphaOfLengthBetween(3, 10); String type = randomAlphaOfLengthBetween(3, 10);
@ -748,13 +755,9 @@ public class RequestTests extends ESTestCase {
} }
public void testSearch() throws Exception { public void testSearch() throws Exception {
SearchRequest searchRequest = new SearchRequest(); String[] indices = randomIndicesNames(0, 5);
int numIndices = randomIntBetween(0, 5); SearchRequest searchRequest = new SearchRequest(indices);
String[] indices = new String[numIndices];
for (int i = 0; i < numIndices; i++) {
indices[i] = "index-" + randomAlphaOfLengthBetween(2, 5);
}
searchRequest.indices(indices);
int numTypes = randomIntBetween(0, 5); int numTypes = randomIntBetween(0, 5);
String[] types = new String[numTypes]; String[] types = new String[numTypes];
for (int i = 0; i < numTypes; i++) { for (int i = 0; i < numTypes; i++) {
@ -1130,4 +1133,13 @@ public class RequestTests extends ESTestCase {
} }
return excludesParam.toString(); return excludesParam.toString();
} }
private static String[] randomIndicesNames(int minIndicesNum, int maxIndicesNum) {
int numIndices = randomIntBetween(minIndicesNum, maxIndicesNum);
String[] indices = new String[numIndices];
for (int i = 0; i < numIndices; i++) {
indices[i] = "index-" + randomAlphaOfLengthBetween(2, 5).toLowerCase(Locale.ROOT);
}
return indices;
}
} }

View File

@ -22,10 +22,14 @@ package org.elasticsearch.client.documentation;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.alias.Alias; import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.close.CloseIndexRequest;
import org.elasticsearch.action.admin.indices.close.CloseIndexResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.open.OpenIndexRequest;
import org.elasticsearch.action.admin.indices.open.OpenIndexResponse;
import org.elasticsearch.action.support.ActiveShardCount; import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.ESRestHighLevelClientTestCase; import org.elasticsearch.client.ESRestHighLevelClientTestCase;
@ -224,4 +228,138 @@ public class IndicesClientDocumentationIT extends ESRestHighLevelClientTestCase
} }
} }
public void testOpenIndex() throws IOException {
RestHighLevelClient client = highLevelClient();
{
CreateIndexResponse createIndexResponse = client.indices().createIndex(new CreateIndexRequest("index"));
assertTrue(createIndexResponse.isAcknowledged());
}
{
// tag::open-index-request
OpenIndexRequest request = new OpenIndexRequest("index"); // <1>
// end::open-index-request
// tag::open-index-request-timeout
request.timeout(TimeValue.timeValueMinutes(2)); // <1>
request.timeout("2m"); // <2>
// end::open-index-request-timeout
// tag::open-index-request-masterTimeout
request.masterNodeTimeout(TimeValue.timeValueMinutes(1)); // <1>
request.masterNodeTimeout("1m"); // <2>
// end::open-index-request-masterTimeout
// tag::open-index-request-waitForActiveShards
request.waitForActiveShards(2); // <1>
request.waitForActiveShards(ActiveShardCount.DEFAULT); // <2>
// end::open-index-request-waitForActiveShards
// tag::open-index-request-indicesOptions
request.indicesOptions(IndicesOptions.strictExpandOpen()); // <1>
// end::open-index-request-indicesOptions
// tag::open-index-execute
OpenIndexResponse openIndexResponse = client.indices().openIndex(request);
// end::open-index-execute
// tag::open-index-response
boolean acknowledged = openIndexResponse.isAcknowledged(); // <1>
boolean shardsAcked = openIndexResponse.isShardsAcknowledged(); // <2>
// end::open-index-response
assertTrue(acknowledged);
assertTrue(shardsAcked);
// tag::open-index-execute-async
client.indices().openIndexAsync(request, new ActionListener<OpenIndexResponse>() {
@Override
public void onResponse(OpenIndexResponse openIndexResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
});
// end::open-index-execute-async
}
{
// tag::open-index-notfound
try {
OpenIndexRequest request = new OpenIndexRequest("does_not_exist");
client.indices().openIndex(request);
} catch (ElasticsearchException exception) {
if (exception.status() == RestStatus.BAD_REQUEST) {
// <1>
}
}
// end::open-index-notfound
}
}
public void testCloseIndex() throws IOException {
RestHighLevelClient client = highLevelClient();
{
CreateIndexResponse createIndexResponse = client.indices().createIndex(new CreateIndexRequest("index"));
assertTrue(createIndexResponse.isAcknowledged());
}
{
// tag::close-index-request
CloseIndexRequest request = new CloseIndexRequest("index"); // <1>
// end::close-index-request
// tag::close-index-request-timeout
request.timeout(TimeValue.timeValueMinutes(2)); // <1>
request.timeout("2m"); // <2>
// end::close-index-request-timeout
// tag::close-index-request-masterTimeout
request.masterNodeTimeout(TimeValue.timeValueMinutes(1)); // <1>
request.masterNodeTimeout("1m"); // <2>
// end::close-index-request-masterTimeout
// tag::close-index-request-indicesOptions
request.indicesOptions(IndicesOptions.lenientExpandOpen()); // <1>
// end::close-index-request-indicesOptions
// tag::close-index-execute
CloseIndexResponse closeIndexResponse = client.indices().closeIndex(request);
// end::close-index-execute
// tag::close-index-response
boolean acknowledged = closeIndexResponse.isAcknowledged(); // <1>
// end::close-index-response
assertTrue(acknowledged);
// tag::close-index-execute-async
client.indices().closeIndexAsync(request, new ActionListener<CloseIndexResponse>() {
@Override
public void onResponse(CloseIndexResponse closeIndexResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
});
// end::close-index-execute-async
}
{
// tag::close-index-notfound
try {
CloseIndexRequest request = new CloseIndexRequest("does_not_exist");
client.indices().closeIndex(request);
} catch (ElasticsearchException exception) {
if (exception.status() == RestStatus.BAD_REQUEST) {
// <1>
}
}
// end::close-index-notfound
}
}
} }

View File

@ -0,0 +1,70 @@
[[java-rest-high-close-index]]
=== Close Index API
[[java-rest-high-close-index-request]]
==== Close Index Request
A `CloseIndexRequest` requires an `index` argument:
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[close-index-request]
--------------------------------------------------
<1> The index to close
==== Optional arguments
The following arguments can optionally be provided:
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[close-index-request-timeout]
--------------------------------------------------
<1> Timeout to wait for the all the nodes to acknowledge the index is closed
as a `TimeValue`
<2> Timeout to wait for the all the nodes to acknowledge the index is closed
as a `String`
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[close-index-request-masterTimeout]
--------------------------------------------------
<1> Timeout to connect to the master node as a `TimeValue`
<2> Timeout to connect to the master node as a `String`
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[close-index-request-indicesOptions]
--------------------------------------------------
<1> Setting `IndicesOptions` controls how unavailable indices are resolved and
how wildcard expressions are expanded
[[java-rest-high-close-index-sync]]
==== Synchronous Execution
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[close-index-execute]
--------------------------------------------------
[[java-rest-high-close-index-async]]
==== Asynchronous Execution
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[close-index-execute-async]
--------------------------------------------------
<1> Called when the execution is successfully completed. The response is
provided as an argument
<2> Called in case of failure. The raised exception is provided as an argument
[[java-rest-high-close-index-response]]
==== Close Index Response
The returned `CloseIndexResponse` allows to retrieve information about the
executed operation as follows:
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[close-index-response]
--------------------------------------------------
<1> Indicates whether all of the nodes have acknowledged the request

View File

@ -48,7 +48,7 @@ The following arguments can optionally be provided:
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[create-index-request-timeout] include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[create-index-request-timeout]
-------------------------------------------------- --------------------------------------------------
<1> Timeout to wait for the all the nodes to acknowledge the index creation as a `TimeValue` <1> Timeout to wait for the all the nodes to acknowledge the index creation as a `TimeValue`
<2> Timeout to wait for the all the nodes to acknowledge the index creatiom as a `String` <2> Timeout to wait for the all the nodes to acknowledge the index creation as a `String`
["source","java",subs="attributes,callouts,macros"] ["source","java",subs="attributes,callouts,macros"]
-------------------------------------------------- --------------------------------------------------
@ -61,8 +61,10 @@ include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[create-index-reque
-------------------------------------------------- --------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[create-index-request-waitForActiveShards] include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[create-index-request-waitForActiveShards]
-------------------------------------------------- --------------------------------------------------
<1> The number of active shard copies to wait for before proceeding with the operation, as an `int`. <1> The number of active shard copies to wait for before the create index API returns a
<2> The number of active shard copies to wait for before proceeding with the operation, as an `ActiveShardCount`. response, as an `int`.
<2> The number of active shard copies to wait for before the create index API returns a
response, as an `ActiveShardCount`.
[[java-rest-high-create-index-sync]] [[java-rest-high-create-index-sync]]
==== Synchronous Execution ==== Synchronous Execution

View File

@ -1,10 +1,23 @@
include::createindex.asciidoc[] include::createindex.asciidoc[]
include::deleteindex.asciidoc[] include::deleteindex.asciidoc[]
include::open_index.asciidoc[]
include::close_index.asciidoc[]
include::_index.asciidoc[] include::_index.asciidoc[]
include::get.asciidoc[] include::get.asciidoc[]
include::delete.asciidoc[] include::delete.asciidoc[]
include::update.asciidoc[] include::update.asciidoc[]
include::bulk.asciidoc[] include::bulk.asciidoc[]
include::search.asciidoc[] include::search.asciidoc[]
include::scroll.asciidoc[] include::scroll.asciidoc[]
include::main.asciidoc[] include::main.asciidoc[]

View File

@ -0,0 +1,81 @@
[[java-rest-high-open-index]]
=== Open Index API
[[java-rest-high-open-index-request]]
==== Open Index Request
An `OpenIndexRequest` requires an `index` argument:
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[open-index-request]
--------------------------------------------------
<1> The index to open
==== Optional arguments
The following arguments can optionally be provided:
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[open-index-request-timeout]
--------------------------------------------------
<1> Timeout to wait for the all the nodes to acknowledge the index is opened
as a `TimeValue`
<2> Timeout to wait for the all the nodes to acknowledge the index is opened
as a `String`
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[open-index-request-masterTimeout]
--------------------------------------------------
<1> Timeout to connect to the master node as a `TimeValue`
<2> Timeout to connect to the master node as a `String`
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[open-index-request-waitForActiveShards]
--------------------------------------------------
<1> The number of active shard copies to wait for before the open index API
returns a response, as an `int`.
<2> The number of active shard copies to wait for before the open index API
returns a response, as an `ActiveShardCount`.
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[open-index-request-indicesOptions]
--------------------------------------------------
<1> Setting `IndicesOptions` controls how unavailable indices are resolved and
how wildcard expressions are expanded
[[java-rest-high-open-index-sync]]
==== Synchronous Execution
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[open-index-execute]
--------------------------------------------------
[[java-rest-high-open-index-async]]
==== Asynchronous Execution
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[open-index-execute-async]
--------------------------------------------------
<1> Called when the execution is successfully completed. The response is
provided as an argument
<2> Called in case of failure. The raised exception is provided as an argument
[[java-rest-high-open-index-response]]
==== Open Index Response
The returned `OpenIndexResponse` allows to retrieve information about the
executed operation as follows:
["source","java",subs="attributes,callouts,macros"]
--------------------------------------------------
include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[open-index-response]
--------------------------------------------------
<1> Indicates whether all of the nodes have acknowledged the request
<2> Indicates whether the requisite number of shard copies were started for
each shard in the index before timing out

View File

@ -6,6 +6,8 @@ The Java High Level REST Client supports the following APIs:
Indices APIs:: Indices APIs::
* <<java-rest-high-create-index>> * <<java-rest-high-create-index>>
* <<java-rest-high-delete-index>> * <<java-rest-high-delete-index>>
* <<java-rest-high-open-index>>
* <<java-rest-high-close-index>>
Single document APIs:: Single document APIs::
* <<java-rest-high-document-index>> * <<java-rest-high-document-index>>

View File

@ -22,13 +22,23 @@ package org.elasticsearch.action.admin.indices.close;
import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException; import java.io.IOException;
/** /**
* A response for a close index action. * A response for a close index action.
*/ */
public class CloseIndexResponse extends AcknowledgedResponse { public class CloseIndexResponse extends AcknowledgedResponse implements ToXContentObject {
private static final ConstructingObjectParser<CloseIndexResponse, Void> PARSER = new ConstructingObjectParser<>("close_index", true,
args -> new CloseIndexResponse((boolean) args[0]));
static {
declareAcknowledgedField(PARSER);
}
CloseIndexResponse() { CloseIndexResponse() {
} }
@ -48,4 +58,16 @@ public class CloseIndexResponse extends AcknowledgedResponse {
super.writeTo(out); super.writeTo(out);
writeAcknowledged(out); writeAcknowledged(out);
} }
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
addAcknowledgedField(builder);
builder.endObject();
return builder;
}
public static CloseIndexResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.apply(parser, null);
}
} }

View File

@ -22,7 +22,6 @@ package org.elasticsearch.action.admin.indices.close;
import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier; import org.apache.logging.log4j.util.Supplier;
import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.open.OpenIndexResponse;
import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.DestructiveOperations; import org.elasticsearch.action.support.DestructiveOperations;
import org.elasticsearch.action.support.master.TransportMasterNodeAction; import org.elasticsearch.action.support.master.TransportMasterNodeAction;

View File

@ -37,7 +37,7 @@ import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constru
/** /**
* A response for a open index action. * A response for a open index action.
*/ */
public class OpenIndexResponse extends AcknowledgedResponse implements ToXContentObject { public class OpenIndexResponse extends AcknowledgedResponse implements ToXContentObject {
private static final String SHARDS_ACKNOWLEDGED = "shards_acknowledged"; private static final String SHARDS_ACKNOWLEDGED = "shards_acknowledged";
private static final ParseField SHARDS_ACKNOWLEDGED_PARSER = new ParseField(SHARDS_ACKNOWLEDGED); private static final ParseField SHARDS_ACKNOWLEDGED_PARSER = new ParseField(SHARDS_ACKNOWLEDGED);

View File

@ -0,0 +1,60 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.admin.indices.close;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
import static org.elasticsearch.test.XContentTestUtils.insertRandomFields;
import static org.hamcrest.CoreMatchers.equalTo;
public class CloseIndexResponseTests extends ESTestCase {
public void testFromToXContent() throws IOException {
final CloseIndexResponse closeIndexResponse = createTestItem();
boolean humanReadable = randomBoolean();
final XContentType xContentType = randomFrom(XContentType.values());
BytesReference originalBytes = toShuffledXContent(closeIndexResponse, xContentType, ToXContent.EMPTY_PARAMS, humanReadable);
BytesReference mutated;
if (randomBoolean()) {
mutated = insertRandomFields(xContentType, originalBytes, null, random());
} else {
mutated = originalBytes;
}
CloseIndexResponse parsedCloseIndexResponse;
try (XContentParser parser = createParser(xContentType.xContent(), mutated)) {
parsedCloseIndexResponse = CloseIndexResponse.fromXContent(parser);
assertNull(parser.nextToken());
}
assertThat(parsedCloseIndexResponse.isAcknowledged(), equalTo(closeIndexResponse.isAcknowledged()));
}
private static CloseIndexResponse createTestItem() {
boolean acknowledged = randomBoolean();
return new CloseIndexResponse(acknowledged);
}
}