当前位置: 首页>>代码示例>>Java>>正文


Java SearchAction类代码示例

本文整理汇总了Java中org.elasticsearch.action.search.SearchAction的典型用法代码示例。如果您正苦于以下问题:Java SearchAction类的具体用法?Java SearchAction怎么用?Java SearchAction使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


SearchAction类属于org.elasticsearch.action.search包,在下文中一共展示了SearchAction类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: apply

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
@Override
public <Request extends ActionRequest, Response extends ActionResponse> void apply(Task task, String action,
        Request request, ActionListener<Response> listener, ActionFilterChain<Request, Response> chain) {
    if (false == action.equals(SearchAction.NAME)) {
        chain.proceed(task, action, request, listener);
        return;
    }
    if (context.getHeader(EXAMPLE_HEADER) != null) {
        throw new IllegalArgumentException("Hurray! Sent the header!");
    }
    String auth = context.getHeader(AUTHORIZATION_HEADER);
    if (auth == null) {
        ElasticsearchSecurityException e = new ElasticsearchSecurityException("Authentication required",
                RestStatus.UNAUTHORIZED);
        e.addHeader("WWW-Authenticate", "Basic realm=auth-realm");
        throw e;
    }
    if (false == REQUIRED_AUTH.equals(auth)) {
        throw new ElasticsearchSecurityException("Bad Authorization", RestStatus.FORBIDDEN);
    }
    chain.proceed(task, action, request, listener);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:23,代码来源:ReindexFromRemoteWithAuthTests.java

示例2: testCancellationDuringQueryPhase

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
public void testCancellationDuringQueryPhase() throws Exception {

        List<ScriptedBlockPlugin> plugins = initBlockFactory();
        indexTestData();

        logger.info("Executing search");
        ListenableActionFuture<SearchResponse> searchResponse = client().prepareSearch("test").setQuery(
            scriptQuery(new Script(
                ScriptType.INLINE, "native", NativeTestScriptedBlockFactory.TEST_NATIVE_BLOCK_SCRIPT, Collections.emptyMap())))
            .execute();

        awaitForBlock(plugins);
        cancelSearch(SearchAction.NAME);
        disableBlocks(plugins);
        logger.info("Segments {}", XContentHelper.toString(client().admin().indices().prepareSegments("test").get(), FORMAT_PARAMS));
        ensureSearchWasCancelled(searchResponse);
    }
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:18,代码来源:SearchCancellationIT.java

示例3: testCancellationDuringFetchPhase

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
public void testCancellationDuringFetchPhase() throws Exception {

        List<ScriptedBlockPlugin> plugins = initBlockFactory();
        indexTestData();

        logger.info("Executing search");
        ListenableActionFuture<SearchResponse> searchResponse = client().prepareSearch("test")
            .addScriptField("test_field",
                new Script(ScriptType.INLINE, "native", NativeTestScriptedBlockFactory.TEST_NATIVE_BLOCK_SCRIPT, Collections.emptyMap())
            ).execute();

        awaitForBlock(plugins);
        cancelSearch(SearchAction.NAME);
        disableBlocks(plugins);
        logger.info("Segments {}", XContentHelper.toString(client().admin().indices().prepareSegments("test").get(), FORMAT_PARAMS));
        ensureSearchWasCancelled(searchResponse);
    }
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:18,代码来源:SearchCancellationIT.java

示例4: testCancellationOfScrollSearches

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
public void testCancellationOfScrollSearches() throws Exception {

        List<ScriptedBlockPlugin> plugins = initBlockFactory();
        indexTestData();

        logger.info("Executing search");
        ListenableActionFuture<SearchResponse> searchResponse = client().prepareSearch("test")
            .setScroll(TimeValue.timeValueSeconds(10))
            .setSize(5)
            .setQuery(
                scriptQuery(new Script(
                    ScriptType.INLINE, "native", NativeTestScriptedBlockFactory.TEST_NATIVE_BLOCK_SCRIPT, Collections.emptyMap())))
            .execute();

        awaitForBlock(plugins);
        cancelSearch(SearchAction.NAME);
        disableBlocks(plugins);
        SearchResponse response = ensureSearchWasCancelled(searchResponse);
        if (response != null) {
            // The response might not have failed on all shards - we need to clean scroll
            logger.info("Cleaning scroll with id {}", response.getScrollId());
            client().prepareClearScroll().addScrollId(response.getScrollId()).get();
        }
    }
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:25,代码来源:SearchCancellationIT.java

示例5: testActions

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
public void testActions() {

        // TODO this is a really shitty way to test it, we need to figure out a way to test all the client methods
        //      without specifying each one (reflection doesn't as each action needs its own special settings, without
        //      them, request validation will fail before the test is executed. (one option is to enable disabling the
        //      validation in the settings??? - ugly and conceptually wrong)

        // choosing arbitrary top level actions to test
        client.prepareGet("idx", "type", "id").execute().addListener(new AssertingActionListener<>(GetAction.NAME, client.threadPool()));
        client.prepareSearch().execute().addListener(new AssertingActionListener<>(SearchAction.NAME, client.threadPool()));
        client.prepareDelete("idx", "type", "id").execute().addListener(new AssertingActionListener<>(DeleteAction.NAME, client.threadPool()));
        client.admin().cluster().prepareDeleteStoredScript("lang", "id").execute().addListener(new AssertingActionListener<>(DeleteStoredScriptAction.NAME, client.threadPool()));
        client.prepareIndex("idx", "type", "id").setSource("source", XContentType.JSON).execute().addListener(new AssertingActionListener<>(IndexAction.NAME, client.threadPool()));

        // choosing arbitrary cluster admin actions to test
        client.admin().cluster().prepareClusterStats().execute().addListener(new AssertingActionListener<>(ClusterStatsAction.NAME, client.threadPool()));
        client.admin().cluster().prepareCreateSnapshot("repo", "bck").execute().addListener(new AssertingActionListener<>(CreateSnapshotAction.NAME, client.threadPool()));
        client.admin().cluster().prepareReroute().execute().addListener(new AssertingActionListener<>(ClusterRerouteAction.NAME, client.threadPool()));

        // choosing arbitrary indices admin actions to test
        client.admin().indices().prepareCreate("idx").execute().addListener(new AssertingActionListener<>(CreateIndexAction.NAME, client.threadPool()));
        client.admin().indices().prepareStats().execute().addListener(new AssertingActionListener<>(IndicesStatsAction.NAME, client.threadPool()));
        client.admin().indices().prepareClearCache("idx1", "idx2").execute().addListener(new AssertingActionListener<>(ClearIndicesCacheAction.NAME, client.threadPool()));
        client.admin().indices().prepareFlush().execute().addListener(new AssertingActionListener<>(FlushAction.NAME, client.threadPool()));
    }
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:26,代码来源:AbstractClientHeadersTestCase.java

示例6: validate

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
/**
 * Perform a test search request to validate the element prior to storing it.
 *
 * @param validation validation info
 * @param element the element stored
 * @param task the parent task
 * @param listener the action listener to write to
 * @param onSuccess action ro run when the validation is successfull
 */
private void validate(FeatureValidation validation,
                      StorableElement element,
                      Task task,
                      ActionListener<FeatureStoreResponse> listener,
                      Runnable onSuccess) {
    ValidatingLtrQueryBuilder ltrBuilder = new ValidatingLtrQueryBuilder(element,
            validation, factory);
    SearchRequestBuilder builder = SearchAction.INSTANCE.newRequestBuilder(client);
    builder.setIndices(validation.getIndex());
    builder.setQuery(ltrBuilder);
    builder.setFrom(0);
    builder.setSize(20);
    // Bail out early and don't score the whole index.
    builder.setTerminateAfter(1000);
    builder.request().setParentTask(clusterService.localNode().getId(), task.getId());
    builder.execute(wrap((r) -> {
            if (r.getFailedShards() > 0) {
                ShardSearchFailure failure = r.getShardFailures()[0];
                throw new IllegalArgumentException("Validating the element caused " + r.getFailedShards() +
                        " shard failures, see root cause: " + failure.reason(), failure.getCause());
            }
            onSuccess.run();
        },
        (e) -> listener.onFailure(new IllegalArgumentException("Cannot store element, validation failed.", e))));
}
 
开发者ID:o19s,项目名称:elasticsearch-learning-to-rank,代码行数:35,代码来源:TransportFeatureStoreAction.java

示例7: executeCardinalityRequest

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
protected void executeCardinalityRequest(final NodeTaskContext context, final NodeTaskReporter reporter) {
  logger.debug("Executing async cardinality action");
  final SearchRequest cardinalityRequest = this.getCardinalityRequest(context.getNode(), context.getVisitor().getParentRequest());
  context.getClient().execute(SearchAction.INSTANCE, cardinalityRequest, new ActionListener<SearchResponse>() {

    @Override
    public void onResponse(SearchResponse searchResponse) {
      Cardinality c = searchResponse.getAggregations().get(context.getNode().getLookupPath());
      context.getNode().setCardinality(c.getValue());
      reporter.success(context);
    }

    @Override
    public void onFailure(Throwable e) {
      reporter.failure(e);
    }

  });
}
 
开发者ID:sirensolutions,项目名称:siren-join,代码行数:20,代码来源:CardinalityEstimationTask.java

示例8: search

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
public String search(List<String> indices, List<String> types, QueryBuilder queryBuilder, Sort sort, Page page) {
    SearchRequestBuilder requestBuilder = new SearchRequestBuilder(client, SearchAction.INSTANCE)
            .setIndices(toArray(indices))
            .setTypes(toArray(types))
            .setQuery(queryBuilder)
            .setFrom(page.offset())
            .setSize(page.size());

    sort.stream().forEach(sf -> requestBuilder.addSort(sf.field(), sf.order()));
    boolean indexExits = indices.stream().allMatch(obj -> {
        if (!indexExists(obj)) {
            return false;
        }
        return true;
    });
    SearchResponse searchResponse = null;
    if (indexExits) {
        searchResponse = client.search(requestBuilder.request())
                .actionGet();
    }
    return searchResponse != null ? searchResponse.toString() : "";

}
 
开发者ID:egovernments,项目名称:egov-search,代码行数:24,代码来源:ElasticSearchClient.java

示例9: HttpInvoker

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
public HttpInvoker(Settings settings, ThreadPool threadPool, Headers headers, URL url) {
    super(settings, threadPool, headers);
    this.contexts = new HashMap<>();
    this.bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool()));
    bootstrap.setPipelineFactory(new HttpInvoker.HttpClientPipelineFactory());
    bootstrap.setOption("tcpNoDelay", true);

    registerAction(BulkAction.INSTANCE, HttpBulkAction.class);
    registerAction(CreateIndexAction.INSTANCE, HttpCreateIndexAction.class);
    registerAction(RefreshAction.INSTANCE, HttpRefreshIndexAction.class);
    registerAction(ClusterUpdateSettingsAction.INSTANCE, HttpClusterUpdateSettingsAction.class);
    registerAction(UpdateSettingsAction.INSTANCE, HttpUpdateSettingsAction.class);
    registerAction(SearchAction.INSTANCE, HttpSearchAction.class);

    this.url = url;
}
 
开发者ID:jprante,项目名称:elasticsearch-helper,代码行数:19,代码来源:HttpInvoker.java

示例10: build

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
public HttpElasticsearchClient build() {
    if (url == null && host != null && port != null) {
        try {
            url = new URL("http://" + host + ":" + port);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("malformed url: " + host + ":" + port);
        }
    }
    if (url == null) {
        throw new IllegalArgumentException("no base URL given");
    }
    ThreadPool threadpool = new ThreadPool("http_client_pool");
    client = new HttpElasticsearchClient(settings, threadpool, Headers.EMPTY, url);

    client.registerAction(BulkAction.INSTANCE, HttpBulkAction.class);
    client.registerAction(CreateIndexAction.INSTANCE, HttpCreateIndexAction.class);
    client.registerAction(RefreshAction.INSTANCE, HttpRefreshIndexAction.class);
    client.registerAction(ClusterUpdateSettingsAction.INSTANCE, HttpClusterUpdateSettingsAction.class);
    client.registerAction(UpdateSettingsAction.INSTANCE, HttpUpdateSettingsAction.class);
    client.registerAction(SearchAction.INSTANCE, HttpSearchAction.class);

    return client;
}
 
开发者ID:jprante,项目名称:elasticsearch-helper,代码行数:24,代码来源:HttpElasticsearchClient.java

示例11: mostRecentDocument

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
public Long mostRecentDocument(String index) {
    if (client() == null) {
        return null;
    }
    SearchRequestBuilder searchRequestBuilder = new SearchRequestBuilder(client(), SearchAction.INSTANCE);
    SortBuilder sort = SortBuilders.fieldSort("_timestamp").order(SortOrder.DESC);
    SearchResponse searchResponse = searchRequestBuilder.setIndices(index).addField("_timestamp").setSize(1).addSort(sort).execute().actionGet();
    if (searchResponse.getHits().getHits().length == 1) {
        SearchHit hit = searchResponse.getHits().getHits()[0];
        if (hit.getFields().get("_timestamp") != null) {
            return hit.getFields().get("_timestamp").getValue();
        } else {
            return 0L;
        }
    }
    return null;
}
 
开发者ID:jprante,项目名称:elasticsearch-helper,代码行数:18,代码来源:BaseClient.java

示例12: execute

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
@Override
public void execute(ActionListener<CountResponse> listener) {
    CountRequest countRequest = beforeExecute(request);
    client.execute(SearchAction.INSTANCE, countRequest.toSearchRequest(), new DelegatingActionListener<SearchResponse, CountResponse>(listener) {
        @Override
        protected CountResponse getDelegatedFromInstigator(SearchResponse response) {
            return new CountResponse(response);
        }
    });
}
 
开发者ID:baidu,项目名称:Elasticsearch,代码行数:11,代码来源:CountRequestBuilder.java

示例13: constructSearchRequestBuilder

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
public static SearchRequestBuilder constructSearchRequestBuilder(String query, Pageable p, int numberOfFragments, Client client) {

        return new SearchRequestBuilder(client, SearchAction.INSTANCE)
            .setHighlighterEncoder("html")
            .setHighlighterFragmentSize(150)
            .setHighlighterPreTags("<mark>")
            .setHighlighterPostTags("</mark>")
            .addHighlightedField("content")
            .setQuery(queryBuilder(query))
            .setFetchSource(null, "content");
    }
 
开发者ID:klask-io,项目名称:klask-io,代码行数:12,代码来源:Queries.java

示例14: testSingleDocHttpClient

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
@Test
public void testSingleDocHttpClient() throws Exception {
    try (HttpClient client = HttpClient.builder()
            .url(new URL("http://127.0.0.1:9200"))
            .build()) {
        CreateIndexRequestBuilder createIndexRequestBuilder =
                new CreateIndexRequestBuilder(client, CreateIndexAction.INSTANCE).setIndex("test");
        createIndexRequestBuilder.execute().actionGet();
        IndexRequestBuilder indexRequestBuilder =
                new IndexRequestBuilder(client, IndexAction.INSTANCE)
                        .setIndex("test")
                        .setType("type")
                        .setId("1")
                        .setSource(jsonBuilder().startObject().field("name", "Hello World").endObject());
        indexRequestBuilder.execute().actionGet();
        RefreshRequestBuilder refreshRequestBuilder =
                new RefreshRequestBuilder(client, RefreshAction.INSTANCE)
                        .setIndices("test");
        refreshRequestBuilder.execute().actionGet();
        SearchRequestBuilder searchRequestBuilder = new SearchRequestBuilder(client, SearchAction.INSTANCE)
                .setIndices("test")
                .setQuery(QueryBuilders.matchAllQuery()).setSize(0);
        assertTrue(searchRequestBuilder.execute().actionGet().getHits().getTotalHits() > 0);
    } catch (NoNodeAvailableException e) {
        logger.warn("skipping, no node available");
    }
}
 
开发者ID:jprante,项目名称:elasticsearch-client-http,代码行数:28,代码来源:HttpBulkClientTest.java

示例15: testRandomDocs

import org.elasticsearch.action.search.SearchAction; //导入依赖的package包/类
@Test
public void testRandomDocs() throws Exception {
    final HttpBulkClient client = HttpBulkClient.builder()
            .url(new URL("http://127.0.0.1:9200"))
            .maxActionsPerRequest(MAX_ACTIONS)
            .flushIngestInterval(TimeValue.timeValueSeconds(60))
            .build();
    try {
        client.newIndex("test");
        for (int i = 0; i < NUM_ACTIONS; i++) {
            client.index("test", "test", null, "{ \"name\" : \"" + randomString(32) + "\"}");
        }
        client.flushIngest();
        client.waitForResponses(TimeValue.timeValueSeconds(30));
        if (client.hasException()) {
            logger.error("error", client.getException());
        }
        assertFalse(client.hasException());
        client.refreshIndex("test");
        SearchRequestBuilder searchRequestBuilder = new SearchRequestBuilder(client.client(), SearchAction.INSTANCE)
                .setIndices("test")
                .setQuery(QueryBuilders.matchAllQuery()).setSize(0);
        assertTrue(searchRequestBuilder.execute().actionGet().getHits().getTotalHits() > 0) ;
    } catch (NoNodeAvailableException e) {
        logger.warn("skipping, no node available");
    } finally {
        client.shutdown();
    }
}
 
开发者ID:jprante,项目名称:elasticsearch-client-http,代码行数:30,代码来源:HttpBulkClientTest.java


注:本文中的org.elasticsearch.action.search.SearchAction类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。