Java Code Examples for org.elasticsearch.action.ActionFuture#get()

The following examples show how to use org.elasticsearch.action.ActionFuture#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DeleteIT.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
public void testNormalStopDetector() throws ExecutionException, InterruptedException {
    StopDetectorRequest request = new StopDetectorRequest().adID("123");

    ActionFuture<StopDetectorResponse> future = client().execute(StopDetectorAction.INSTANCE, request);

    StopDetectorResponse response = future.get();
    assertTrue(response.success());
}
 
Example 2
Source File: DeleteIT.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
public void testNormalDeleteModel() throws ExecutionException, InterruptedException {
    DeleteModelRequest request = new DeleteModelRequest("123");

    ActionFuture<DeleteModelResponse> future = client().execute(DeleteModelAction.INSTANCE, request);

    DeleteModelResponse response = future.get();
    assertTrue(!response.hasFailures());
}
 
Example 3
Source File: AbstractESTest.java    From elasticsearch-migration with Apache License 2.0 5 votes vote down vote up
@SneakyThrows
protected boolean checkDocumentExists(String indexName, String type, String id) {
    final ActionFuture<GetResponse> response = client.get(new GetRequest(indexName, type, id));
    client.admin().indices().prepareFlush(indexName).setWaitIfOngoing(true).setForce(true).execute().get();
    final GetResponse getFields = response.get();

    assertThat("Response should be done", response.isDone(), is(true));
    return getFields.isExists();
}
 
Example 4
Source File: AbstractESTest.java    From elasticsearch-migration with Apache License 2.0 5 votes vote down vote up
@SneakyThrows
protected boolean checkIndexExists(String indexName) {
    final ActionFuture<GetIndexResponse> response = client.admin().indices().getIndex(new GetIndexRequest().indices(indexName));

    try {
        return response.get() != null;
    } catch (ExecutionException e) {
        return false;
    }
}
 
Example 5
Source File: AbstractESTest.java    From elasticsearch-migration with Apache License 2.0 5 votes vote down vote up
@SneakyThrows
protected String getFromIndex(String indexName, String type, String id) {
    final ActionFuture<GetResponse> response = client.get(new GetRequest(indexName, type, id).fetchSourceContext(FetchSourceContext.FETCH_SOURCE));
    client.admin().indices().prepareFlush(indexName).setWaitIfOngoing(true).setForce(true).execute().get();
    final GetResponse getFields = response.get();

    assertThat("Response should be done", response.isDone(), is(true));
    assertThat("Get " + id + " should exist (" + indexName + ", " + type + ")", getFields.isExists(), is(true));
    assertThat("Source field should not be empty", getFields.isSourceEmpty(), is(false));

    final String sourceAsString = getFields.getSourceAsString();

    assertThat("response source should not be null", sourceAsString, notNullValue());
    return sourceAsString;
}
 
Example 6
Source File: AbstractESTest.java    From elasticsearch-migration with Apache License 2.0 5 votes vote down vote up
@SneakyThrows
protected <T> T getFromIndex(String indexName, String type, String id, Class<T> clazz) {
    final ActionFuture<GetResponse> response = client.get(new GetRequest(indexName, type, id));
    client.admin().indices().prepareFlush(indexName).setWaitIfOngoing(true).setForce(true).execute().get();
    final GetResponse getFields = response.get();

    final String sourceAsString = getFields.getSourceAsString();

    return esObjectMapper.readValue(sourceAsString, clazz);
}
 
Example 7
Source File: QuestionElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * This is a new search that accepts additionalSearchInformation. We need it for our complex question searches.
 * We have duplicated the methods that need this parameter, like prepareSearchRequest
 */
public SearchResponse search(String searchTerms, List<String> references, List<String> siteIds, int start, int end, Map<String,String> additionalSearchInformation) {
    final Pair<SearchRequestBuilder,QueryBuilder> searchBuilders = prepareSearchRequest(searchTerms, references, siteIds, start, end, additionalSearchInformation);
    final SearchRequestBuilder searchRequestBuilder = searchBuilders.getLeft();
    final QueryBuilder queryBuilder = searchBuilders.getRight();

    getLog().debug("Search request from index builder [" + getName() + "]: " + searchRequestBuilder.toString());

    ValidateQueryRequest validateQueryRequest = new ValidateQueryRequest(indexName);
    QuerySourceBuilder querySourceBuilder = new QuerySourceBuilder().setQuery(queryBuilder);
    validateQueryRequest.source(querySourceBuilder);
    validateQueryRequest.explain(true);


    try {
        ActionFuture<ValidateQueryResponse> future = client.admin().indices().validateQuery(validateQueryRequest); // the client is org.elasticsearch.client.Client
        ValidateQueryResponse responseV = future.get(); // typical java future as response

        if (responseV.isValid()) {
            SearchResponse response = searchRequestBuilder.execute().actionGet();
            getLog().debug("Search request from index builder [" + getName() + "] took: " + response.getTook().format());
            eventTrackingService.post(eventTrackingService.newEvent(SearchService.EVENT_SEARCH,
                    SearchService.EVENT_SEARCH_REF + queryBuilder.toString(), true,
                    NotificationService.PREF_IMMEDIATE));

            return response;
        }else{
            return null;
        }
    }catch(Exception ex){
        return null;
    }

}
 
Example 8
Source File: ElasticsearchAsyncIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    List<ActionFuture<GetResponse>> futures = Lists.newArrayList();
    for (int i = 0; i < 100; i++) {
        futures.add(client.prepareGet("testindex", "testtype", documentId)
                .execute());
    }
    for (ActionFuture<GetResponse> future : futures) {
        future.get();
    }
}
 
Example 9
Source File: QuestionElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * This is a new search that accepts additionalSearchInformation. We need it for our complex question searches.
 * We have duplicated the methods that need this parameter, like prepareSearchRequest
 */
public SearchResponse search(String searchTerms, List<String> references, List<String> siteIds, int start, int end, Map<String,String> additionalSearchInformation) {
    final Pair<SearchRequestBuilder,QueryBuilder> searchBuilders = prepareSearchRequest(searchTerms, references, siteIds, start, end, additionalSearchInformation);
    final SearchRequestBuilder searchRequestBuilder = searchBuilders.getLeft();
    final QueryBuilder queryBuilder = searchBuilders.getRight();

    getLog().debug("Search request from index builder [" + getName() + "]: " + searchRequestBuilder.toString());

    ValidateQueryRequest validateQueryRequest = new ValidateQueryRequest(indexName);
    QuerySourceBuilder querySourceBuilder = new QuerySourceBuilder().setQuery(queryBuilder);
    validateQueryRequest.source(querySourceBuilder);
    validateQueryRequest.explain(true);


    try {
        ActionFuture<ValidateQueryResponse> future = client.admin().indices().validateQuery(validateQueryRequest); // the client is org.elasticsearch.client.Client
        ValidateQueryResponse responseV = future.get(); // typical java future as response

        if (responseV.isValid()) {
            SearchResponse response = searchRequestBuilder.execute().actionGet();
            getLog().debug("Search request from index builder [" + getName() + "] took: " + response.getTook().format());
            eventTrackingService.post(eventTrackingService.newEvent(SearchService.EVENT_SEARCH,
                    SearchService.EVENT_SEARCH_REF + queryBuilder.toString(), true,
                    NotificationService.PREF_IMMEDIATE));

            return response;
        }else{
            return null;
        }
    }catch(Exception ex){
        return null;
    }

}
 
Example 10
Source File: KillIntegrationTest.java    From crate with Apache License 2.0 5 votes vote down vote up
private void assertGotCancelled(final String statement, @Nullable final Object[] params, boolean killAll) throws Exception {
    try {
        ActionFuture<SQLResponse> future = sqlExecutor.execute(statement, params);
        String jobId = waitForJobEntry(statement);
        if (jobId == null) {
            // query finished too fast
            return;
        }
        if (killAll) {
            execute("kill all");
        } else {
            execute("kill ?", $(jobId));
        }
        try {
            future.get(10, TimeUnit.SECONDS);
        } catch (Throwable exception) {
            exception = SQLExceptions.unwrap(exception); // wrapped in ExecutionException
            assertThat(exception, instanceOf(SQLActionException.class));
            assertThat(exception.toString(), anyOf(
                containsString("Job killed"), // CancellationException
                containsString("RootTask for job"), // TaskMissing when root task not found
                containsString("Task for job") // TaskMissing when task not found
            ));
        }
    } finally {
        waitUntilThreadPoolTasksFinished(ThreadPool.Names.SEARCH);
    }
}
 
Example 11
Source File: TransportExample.java    From found-shield-example with Apache License 2.0 4 votes vote down vote up
public void run(String[] args) {
    String host = System.getProperty("host");
    int port = Integer.parseInt(System.getProperty("port", "9343"));

    String hostBasedClusterName = host.split("\\.", 2)[0];
    String clusterName = System.getProperty("cluster", hostBasedClusterName);

    boolean enableSsl = Boolean.parseBoolean(System.getProperty("ssl", "true"));
    // Note: If enabling IPv6, then you should ensure that your host and network can route it to the Cloud endpoint.
    // (eg Docker disables IPv6 routing by default) - see also the initialization code at the top of this file.
    ip6Enabled = Boolean.parseBoolean(System.getProperty("ip6", "true"));
    ip4Enabled = Boolean.parseBoolean(System.getProperty("ip4", "true"));

    // For testing in dev environments, similar to `curl -k` option
    boolean insecure = Boolean.parseBoolean(System.getProperty("insecure", "false"));

    logger.info("Connecting to cluster: [{}] via [{}:{}] using ssl:[{}]", clusterName, host, port, enableSsl);

    // Build the settings for our client.
    Settings settings = Settings.builder()
        .put("client.transport.nodes_sampler_interval", "5s")
        .put("client.transport.sniff", false)
        .put("transport.tcp.compress", true)
        .put("cluster.name", clusterName)
        .put("xpack.security.transport.ssl.enabled", enableSsl)
        .put("request.headers.X-Found-Cluster", "${cluster.name}")
        .put("xpack.security.user", System.getProperty("xpack.security.user"))
        .put("xpack.security.transport.ssl.verification_mode", insecure ? "none" : "full")
        .build();

    // Instantiate a TransportClient and add the cluster to the list of addresses to connect to.
    // Only port 9343 (SSL-encrypted) is currently supported. The use of x-pack security features is required.
    TransportClient client = new PreBuiltXPackTransportClient(settings);
    try {
        for (InetAddress address : InetAddress.getAllByName(host)) {
            if ((ip6Enabled && address instanceof Inet6Address)
                    || (ip4Enabled && address instanceof Inet4Address)) {
                client.addTransportAddress(new TransportAddress(address, port));
            }
        }
    } catch (UnknownHostException e) {
        logger.error("Unable to get the host", e.getMessage());
    }

    while(true) {
        try {
            logger.info("Getting cluster health... ");
            ActionFuture<ClusterHealthResponse> healthFuture = client.admin().cluster().health(Requests.clusterHealthRequest());
            ClusterHealthResponse healthResponse = healthFuture.get(5, TimeUnit.SECONDS);
            logger.info("Got cluster health response: [{}]", healthResponse.getStatus());
        } catch(Throwable t) {
            logger.error("Unable to get cluster health response: [{}]", t.getMessage());
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ie) { ie.printStackTrace(); }
    }
}