use of org.opensearch.action.LatchedActionListener in project OpenSearch by opensearch-project.
the class ClusterClientDocumentationIT method testDeleteComponentTemplate.
public void testDeleteComponentTemplate() throws Exception {
RestHighLevelClient client = highLevelClient();
{
PutComponentTemplateRequest request = new PutComponentTemplateRequest().name("ct1");
Settings settings = Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 1).build();
String mappingJson = "{\n" + " \"properties\": {\n" + " \"message\": {\n" + " \"type\": \"text\"\n" + " }\n" + " }\n" + "}";
AliasMetadata twitterAlias = AliasMetadata.builder("twitter_alias").build();
Map<String, AliasMetadata> aliases = new HashMap<>();
aliases.put("twitter_alias", twitterAlias);
Template template = new Template(settings, new CompressedXContent(mappingJson), aliases);
request.componentTemplate(new ComponentTemplate(template, null, null));
assertTrue(client.cluster().putComponentTemplate(request, RequestOptions.DEFAULT).isAcknowledged());
}
// tag::delete-component-template-request
// <1>
DeleteComponentTemplateRequest deleteRequest = new DeleteComponentTemplateRequest("ct1");
// end::delete-component-template-request
// tag::delete-component-template-request-masterTimeout
// <1>
deleteRequest.setMasterTimeout(TimeValue.timeValueMinutes(1));
// end::delete-component-template-request-masterTimeout
// tag::delete-component-template-execute
AcknowledgedResponse deleteTemplateAcknowledge = client.cluster().deleteComponentTemplate(deleteRequest, RequestOptions.DEFAULT);
// end::delete-component-template-execute
// tag::delete-component-template-response
// <1>
boolean acknowledged = deleteTemplateAcknowledge.isAcknowledged();
// end::delete-component-template-response
assertThat(acknowledged, equalTo(true));
{
PutComponentTemplateRequest request = new PutComponentTemplateRequest().name("ct1");
Settings settings = Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 1).build();
Template template = new Template(settings, null, null);
request.componentTemplate(new ComponentTemplate(template, null, null));
assertTrue(client.cluster().putComponentTemplate(request, RequestOptions.DEFAULT).isAcknowledged());
}
// tag::delete-component-template-execute-listener
ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-component-template-execute-listener
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::delete-component-template-execute-async
// <1>
client.cluster().deleteComponentTemplateAsync(deleteRequest, RequestOptions.DEFAULT, listener);
// end::delete-component-template-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
use of org.opensearch.action.LatchedActionListener in project OpenSearch by opensearch-project.
the class SearchDocumentationIT method testSearch.
@SuppressWarnings({ "unused", "unchecked" })
public void testSearch() throws Exception {
indexSearchTestData();
RestHighLevelClient client = highLevelClient();
{
// tag::search-request-basic
// <1>
SearchRequest searchRequest = new SearchRequest();
// <2>
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// <3>
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
// <4>
searchRequest.source(searchSourceBuilder);
// end::search-request-basic
}
{
// tag::search-request-indices
// <1>
SearchRequest searchRequest = new SearchRequest("posts");
// end::search-request-indices
// tag::search-request-routing
// <1>
searchRequest.routing("routing");
// end::search-request-routing
// tag::search-request-indicesOptions
// <1>
searchRequest.indicesOptions(IndicesOptions.lenientExpandOpen());
// end::search-request-indicesOptions
// tag::search-request-preference
// <1>
searchRequest.preference("_local");
// end::search-request-preference
assertNotNull(client.search(searchRequest, RequestOptions.DEFAULT));
}
{
// tag::search-source-basics
// <1>
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// <2>
sourceBuilder.query(QueryBuilders.termQuery("user", "foobar"));
// <3>
sourceBuilder.from(0);
// <4>
sourceBuilder.size(5);
// <5>
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
// end::search-source-basics
// tag::search-source-sorting
// <1>
sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));
// <2>
sourceBuilder.sort(new FieldSortBuilder("id").order(SortOrder.ASC));
// end::search-source-sorting
// tag::search-source-filtering-off
sourceBuilder.fetchSource(false);
// end::search-source-filtering-off
// tag::search-source-filtering-includes
String[] includeFields = new String[] { "title", "innerObject.*" };
String[] excludeFields = new String[] { "user" };
sourceBuilder.fetchSource(includeFields, excludeFields);
// end::search-source-filtering-includes
sourceBuilder.fetchSource(true);
// tag::search-source-setter
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("posts");
searchRequest.source(sourceBuilder);
// end::search-source-setter
// tag::search-execute
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// end::search-execute
// tag::search-execute-listener
ActionListener<SearchResponse> listener = new ActionListener<SearchResponse>() {
@Override
public void onResponse(SearchResponse searchResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::search-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::search-execute-async
// <1>
client.searchAsync(searchRequest, RequestOptions.DEFAULT, listener);
// end::search-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
// tag::search-response-1
RestStatus status = searchResponse.status();
TimeValue took = searchResponse.getTook();
Boolean terminatedEarly = searchResponse.isTerminatedEarly();
boolean timedOut = searchResponse.isTimedOut();
// end::search-response-1
// tag::search-response-2
int totalShards = searchResponse.getTotalShards();
int successfulShards = searchResponse.getSuccessfulShards();
int failedShards = searchResponse.getFailedShards();
for (ShardSearchFailure failure : searchResponse.getShardFailures()) {
// failures should be handled here
}
// end::search-response-2
assertNotNull(searchResponse);
// tag::search-hits-get
SearchHits hits = searchResponse.getHits();
// end::search-hits-get
// tag::search-hits-info
TotalHits totalHits = hits.getTotalHits();
// the total number of hits, must be interpreted in the context of totalHits.relation
long numHits = totalHits.value;
// whether the number of hits is accurate (EQUAL_TO) or a lower bound of the total (GREATER_THAN_OR_EQUAL_TO)
TotalHits.Relation relation = totalHits.relation;
float maxScore = hits.getMaxScore();
// end::search-hits-info
// tag::search-hits-singleHit
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
// do something with the SearchHit
}
// end::search-hits-singleHit
for (SearchHit hit : searchHits) {
// tag::search-hits-singleHit-properties
String index = hit.getIndex();
String id = hit.getId();
float score = hit.getScore();
// end::search-hits-singleHit-properties
// tag::search-hits-singleHit-source
String sourceAsString = hit.getSourceAsString();
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
String documentTitle = (String) sourceAsMap.get("title");
List<Object> users = (List<Object>) sourceAsMap.get("user");
Map<String, Object> innerObject = (Map<String, Object>) sourceAsMap.get("innerObject");
// end::search-hits-singleHit-source
}
assertEquals(3, numHits);
assertEquals(TotalHits.Relation.EQUAL_TO, relation);
assertNotNull(hits.getHits()[0].getSourceAsString());
assertNotNull(hits.getHits()[0].getSourceAsMap().get("title"));
assertNotNull(hits.getHits()[0].getSourceAsMap().get("innerObject"));
assertNull(hits.getHits()[0].getSourceAsMap().get("user"));
}
}
use of org.opensearch.action.LatchedActionListener in project OpenSearch by opensearch-project.
the class CRUDDocumentationIT method testExists.
public void testExists() throws Exception {
RestHighLevelClient client = highLevelClient();
// tag::exists-request
GetRequest getRequest = new GetRequest(// <1>
"posts", // <2>
"1");
// <3>
getRequest.fetchSourceContext(new FetchSourceContext(false));
// <4>
getRequest.storedFields("_none_");
// end::exists-request
{
// tag::exists-execute
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
// end::exists-execute
assertFalse(exists);
}
{
// tag::exists-execute-listener
ActionListener<Boolean> listener = new ActionListener<Boolean>() {
@Override
public void onResponse(Boolean exists) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::exists-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::exists-execute-async
// <1>
client.existsAsync(getRequest, RequestOptions.DEFAULT, listener);
// end::exists-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
use of org.opensearch.action.LatchedActionListener in project OpenSearch by opensearch-project.
the class TransportShardBulkActionTests method testExecuteBulkIndexRequestWithErrorWhileUpdatingMapping.
public void testExecuteBulkIndexRequestWithErrorWhileUpdatingMapping() throws Exception {
IndexShard shard = newStartedShard(true);
BulkItemRequest[] items = new BulkItemRequest[1];
DocWriteRequest<IndexRequest> writeRequest = new IndexRequest("index").id("id").source(Requests.INDEX_CONTENT_TYPE, "foo", "bar");
items[0] = new BulkItemRequest(0, writeRequest);
BulkShardRequest bulkShardRequest = new BulkShardRequest(shardId, RefreshPolicy.NONE, items);
// Return an exception when trying to update the mapping, or when waiting for it to come
RuntimeException err = new RuntimeException("some kind of exception");
boolean errorOnWait = randomBoolean();
randomlySetIgnoredPrimaryResponse(items[0]);
BulkPrimaryExecutionContext context = new BulkPrimaryExecutionContext(bulkShardRequest, shard);
final CountDownLatch latch = new CountDownLatch(1);
TransportShardBulkAction.executeBulkItemRequest(context, null, threadPool::absoluteTimeInMillis, errorOnWait == false ? new ThrowingMappingUpdatePerformer(err) : new NoopMappingUpdatePerformer(), errorOnWait ? listener -> listener.onFailure(err) : listener -> listener.onResponse(null), new LatchedActionListener<>(new ActionListener<Void>() {
@Override
public void onResponse(Void aVoid) {
}
@Override
public void onFailure(final Exception e) {
assertEquals(err, e);
}
}, latch));
latch.await();
assertFalse(context.hasMoreOperationsToExecute());
// Translog shouldn't be synced, as there were conflicting mappings
assertThat(context.getLocationToSync(), nullValue());
BulkItemResponse primaryResponse = bulkShardRequest.items()[0].getPrimaryResponse();
// Since this was not a conflict failure, the primary response
// should be filled out with the failure information
assertThat(primaryResponse.getItemId(), equalTo(0));
assertThat(primaryResponse.getId(), equalTo("id"));
assertThat(primaryResponse.getOpType(), equalTo(DocWriteRequest.OpType.INDEX));
assertTrue(primaryResponse.isFailed());
assertThat(primaryResponse.getFailureMessage(), containsString("some kind of exception"));
BulkItemResponse.Failure failure = primaryResponse.getFailure();
assertThat(failure.getIndex(), equalTo("index"));
assertThat(failure.getId(), equalTo("id"));
assertThat(failure.getCause(), equalTo(err));
closeShards(shard);
}
use of org.opensearch.action.LatchedActionListener in project OpenSearch by opensearch-project.
the class ClearScrollControllerTests method testClearAll.
public void testClearAll() throws InterruptedException {
DiscoveryNode node1 = new DiscoveryNode("node_1", buildNewFakeTransportAddress(), Version.CURRENT);
DiscoveryNode node2 = new DiscoveryNode("node_2", buildNewFakeTransportAddress(), Version.CURRENT);
DiscoveryNode node3 = new DiscoveryNode("node_3", buildNewFakeTransportAddress(), Version.CURRENT);
DiscoveryNodes nodes = DiscoveryNodes.builder().add(node1).add(node2).add(node3).build();
CountDownLatch latch = new CountDownLatch(1);
ActionListener<ClearScrollResponse> listener = new LatchedActionListener<>(new ActionListener<ClearScrollResponse>() {
@Override
public void onResponse(ClearScrollResponse clearScrollResponse) {
assertEquals(3, clearScrollResponse.getNumFreed());
assertTrue(clearScrollResponse.isSucceeded());
}
@Override
public void onFailure(Exception e) {
throw new AssertionError(e);
}
}, latch);
List<DiscoveryNode> nodesInvoked = new CopyOnWriteArrayList<>();
SearchTransportService searchTransportService = new SearchTransportService(null, null) {
@Override
public void sendClearAllScrollContexts(Transport.Connection connection, ActionListener<TransportResponse> listener) {
nodesInvoked.add(connection.getNode());
// response is unused
Thread t = new Thread(() -> listener.onResponse(TransportResponse.Empty.INSTANCE));
t.start();
}
@Override
public Transport.Connection getConnection(String clusterAlias, DiscoveryNode node) {
return new SearchAsyncActionTests.MockConnection(node);
}
};
ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
clearScrollRequest.scrollIds(Arrays.asList("_all"));
ClearScrollController controller = new ClearScrollController(clearScrollRequest, listener, nodes, logger, searchTransportService);
controller.run();
latch.await();
assertEquals(3, nodesInvoked.size());
Collections.sort(nodesInvoked, Comparator.comparing(DiscoveryNode::getId));
assertEquals(nodesInvoked, Arrays.asList(node1, node2, node3));
}
Aggregations