當前位置: 首頁>>代碼示例>>Java>>正文


Java SearchRequest類代碼示例

本文整理匯總了Java中org.elasticsearch.action.search.SearchRequest的典型用法代碼示例。如果您正苦於以下問題:Java SearchRequest類的具體用法?Java SearchRequest怎麽用?Java SearchRequest使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


SearchRequest類屬於org.elasticsearch.action.search包,在下文中一共展示了SearchRequest類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: prepareRequest

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
@Override
public RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    if (request.hasContentOrSourceParam() == false) {
        throw new ElasticsearchException("request body is required");
    }

    // Creates the search request with all required params
    SearchRequest searchRequest = new SearchRequest();
    RestSearchAction.parseSearchRequest(searchRequest, request, null);

    // Creates the search template request
    SearchTemplateRequest searchTemplateRequest;
    try (XContentParser parser = request.contentOrSourceParamParser()) {
        searchTemplateRequest = PARSER.parse(parser, new SearchTemplateRequest(), null);
    }
    searchTemplateRequest.setRequest(searchRequest);

    return channel -> client.execute(SearchTemplateAction.INSTANCE, searchTemplateRequest, new RestStatusToXContentListener<>(channel));
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:RestSearchTemplateAction.java

示例2: DfsOnlyRequest

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
public DfsOnlyRequest(Fields termVectorsFields, String[] indices, String[] types, Set<String> selectedFields) throws IOException {
    super(indices);

    // build a search request with a query of all the terms
    final BoolQueryBuilder boolBuilder = boolQuery();
    for (String fieldName : termVectorsFields) {
        if ((selectedFields != null) && (!selectedFields.contains(fieldName))) {
            continue;
        }
        Terms terms = termVectorsFields.terms(fieldName);
        TermsEnum iterator = terms.iterator();
        while (iterator.next() != null) {
            String text = iterator.term().utf8ToString();
            boolBuilder.should(QueryBuilders.termQuery(fieldName, text));
        }
    }
    // wrap a search request object
    this.searchRequest = new SearchRequest(indices).types(types).source(new SearchSourceBuilder().query(boolBuilder));
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:20,代碼來源:DfsOnlyRequest.java

示例3: selectMatchAll

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
public String selectMatchAll(String indexs,String types,String field,String value){
	try {
		if(StringUtil.isEmpty(indexs))indexs="_all";
		if(xclient==null){
			init();
		}
		SearchSourceBuilder search = new SearchSourceBuilder();
		if(!StringUtil.isEmpty(field)&&!StringUtil.isEmpty(value)&&!(field.matches(regex)||field.matches(value))){
			search.query(QueryBuilders.matchQuery(field, value));
		}
		search.aggregation(AggregationBuilders.terms("data").field(field+".keyword"));
		search.explain(false);
		SearchRequest request = new SearchRequest();
		request.searchType(SearchType.DFS_QUERY_THEN_FETCH);
		request.source(search);
		request.indices(indexs.split(","));
		request.types(types.split(","));
		SearchResponse response = xclient.search(request);
		return response.toString();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
開發者ID:dev-share,項目名稱:database-transform-tool,代碼行數:26,代碼來源:ElasticsearchHighRestFactory.java

示例4: selectTermAll

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
public String selectTermAll(String indexs,String types,String field,String value){
	try {
		if(StringUtil.isEmpty(indexs))indexs="_all";
		if(xclient==null){
			init();
		}
		SearchSourceBuilder search = new SearchSourceBuilder();
		if(!StringUtil.isEmpty(field)&&!StringUtil.isEmpty(value)&&!(field.matches(regex)||field.matches(value))){
			search.query(QueryBuilders.termQuery(field, value));
		}
		search.aggregation(AggregationBuilders.terms("data").field(field+".keyword"));
		search.explain(false);
		SearchRequest request = new SearchRequest();
		request.searchType(SearchType.DFS_QUERY_THEN_FETCH);
		request.source(search);
		request.indices(indexs.split(","));
		request.types(types.split(","));
		SearchResponse response = xclient.search(request);
		return response.toString();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
開發者ID:dev-share,項目名稱:css-elasticsearch,代碼行數:26,代碼來源:ElasticsearchExtendHighRestFactory.java

示例5: execute

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
/**
 * Execute the ActionRequest and returns the REST response using the channel.
 */
public void execute() throws Exception {
       ActionRequest request = requestBuilder.request();

       //todo: maby change to instanceof multi?
       if(requestBuilder instanceof JoinRequestBuilder){
           executeJoinRequestAndSendResponse();
       }
	else if (request instanceof SearchRequest) {
		client.search((SearchRequest) request, new RestStatusToXContentListener<SearchResponse>(channel));
	} else if (requestBuilder instanceof SqlElasticDeleteByQueryRequestBuilder) {
           throw new UnsupportedOperationException("currently not support delete on elastic 2.0.0");
       }
       else if(request instanceof GetIndexRequest) {
           this.requestBuilder.getBuilder().execute( new GetIndexRequestRestListener(channel, (GetIndexRequest) request));
       }


	else {
		throw new Exception(String.format("Unsupported ActionRequest provided: %s", request.getClass().getName()));
	}
}
 
開發者ID:mazhou,項目名稱:es-sql,代碼行數:25,代碼來源:ActionRequestRestExecuter.java

示例6: testTemplateQueryAsEscapedStringStartingWithConditionalClause

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
/**
 * Test that template can contain conditional clause. In this case it is at
 * the beginning of the string.
 */
public void testTemplateQueryAsEscapedStringStartingWithConditionalClause() throws Exception {
    SearchRequest searchRequest = new SearchRequest();
    searchRequest.indices("_all");
    String templateString =
              "{"
            + "  \"inline\" : \"{ {{#use_size}} \\\"size\\\": \\\"{{size}}\\\", {{/use_size}} \\\"query\\\":{\\\"match_all\\\":{}}}\","
            + "  \"params\":{"
            + "    \"size\": 1,"
            + "    \"use_size\": true"
            + "  }"
            + "}";
    SearchTemplateRequest request = RestSearchTemplateAction.parse(createParser(JsonXContent.jsonXContent, templateString));
    request.setRequest(searchRequest);
    SearchTemplateResponse searchResponse = client().execute(SearchTemplateAction.INSTANCE, request).get();
    assertThat(searchResponse.getResponse().getHits().getHits().length, equalTo(1));
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:21,代碼來源:SearchTemplateIT.java

示例7: testTemplateQueryAsEscapedStringWithConditionalClauseAtEnd

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
/**
 * Test that template can contain conditional clause. In this case it is at
 * the end of the string.
 */
public void testTemplateQueryAsEscapedStringWithConditionalClauseAtEnd() throws Exception {
    SearchRequest searchRequest = new SearchRequest();
    searchRequest.indices("_all");
    String templateString =
              "{"
            + "  \"inline\" : \"{ \\\"query\\\":{\\\"match_all\\\":{}} {{#use_size}}, \\\"size\\\": \\\"{{size}}\\\" {{/use_size}} }\","
            + "  \"params\":{"
            + "    \"size\": 1,"
            + "    \"use_size\": true"
            + "  }"
            + "}";
    SearchTemplateRequest request = RestSearchTemplateAction.parse(createParser(JsonXContent.jsonXContent, templateString));
    request.setRequest(searchRequest);
    SearchTemplateResponse searchResponse = client().execute(SearchTemplateAction.INSTANCE, request).get();
    assertThat(searchResponse.getResponse().getHits().getHits().length, equalTo(1));
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:21,代碼來源:SearchTemplateIT.java

示例8: buildRequest

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
@Override
@SuppressWarnings("unchecked")
protected UpdateByQueryRequest buildRequest(RestRequest request) throws IOException {
    /*
     * Passing the search request through UpdateByQueryRequest first allows
     * it to set its own defaults which differ from SearchRequest's
     * defaults. Then the parse can override them.
     */
    UpdateByQueryRequest internal = new UpdateByQueryRequest(new SearchRequest());

    Map<String, Consumer<Object>> consumers = new HashMap<>();
    consumers.put("conflicts", o -> internal.setConflicts((String) o));
    consumers.put("script", o -> internal.setScript(parseScript((Map<String, Object>)o)));

    parseInternalRequest(internal, request, consumers);

    internal.setPipeline(request.param("pipeline"));
    return internal;
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:RestUpdateByQueryAction.java

示例9: validateAgainstAliases

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
/**
 * Throws an ActionRequestValidationException if the request tries to index
 * back into the same index or into an index that points to two indexes.
 * This cannot be done during request validation because the cluster state
 * isn't available then. Package private for testing.
 */
static void validateAgainstAliases(SearchRequest source, IndexRequest destination, RemoteInfo remoteInfo,
                                     IndexNameExpressionResolver indexNameExpressionResolver, AutoCreateIndex autoCreateIndex,
                                     ClusterState clusterState) {
    if (remoteInfo != null) {
        return;
    }
    String target = destination.index();
    if (false == autoCreateIndex.shouldAutoCreate(target, clusterState)) {
        /*
         * If we're going to autocreate the index we don't need to resolve
         * it. This is the same sort of dance that TransportIndexRequest
         * uses to decide to autocreate the index.
         */
        target = indexNameExpressionResolver.concreteIndexNames(clusterState, destination)[0];
    }
    for (String sourceIndex : indexNameExpressionResolver.concreteIndexNames(clusterState, source)) {
        if (sourceIndex.equals(target)) {
            ActionRequestValidationException e = new ActionRequestValidationException();
            e.addValidationError("reindex cannot write into an index its reading from [" + target + ']');
            throw e;
        }
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:30,代碼來源:TransportReindexAction.java

示例10: sendFreeContext

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
public void sendFreeContext(DiscoveryNode node, final long contextId, SearchRequest request) {
    transportService.sendRequest(node, FREE_CONTEXT_ACTION_NAME, new SearchFreeContextRequest(request, contextId), new ActionListenerResponseHandler<SearchFreeContextResponse>(new ActionListener<SearchFreeContextResponse>() {
        @Override
        public void onResponse(SearchFreeContextResponse response) {
            // no need to respond if it was freed or not
        }

        @Override
        public void onFailure(Throwable e) {

        }
    }) {
        @Override
        public SearchFreeContextResponse newInstance() {
            return new SearchFreeContextResponse();
        }
    });
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:19,代碼來源:SearchServiceTransportAction.java

示例11: toSearchRequest

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
public SearchRequest toSearchRequest() {
    SearchRequest searchRequest = new SearchRequest(indices());
    searchRequest.indicesOptions(indicesOptions());
    searchRequest.types(types());
    searchRequest.routing(routing());
    searchRequest.preference(preference());
    searchRequest.source(source());
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.size(0);
    if (minScore() != DEFAULT_MIN_SCORE) {
        searchSourceBuilder.minScore(minScore());
    }
    if (terminateAfter() != DEFAULT_TERMINATE_AFTER) {
        searchSourceBuilder.terminateAfter(terminateAfter());
    }
    searchRequest.extraSource(searchSourceBuilder);
    return searchRequest;
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:19,代碼來源:CountRequest.java

示例12: testDeleteByQueryRequest

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
public void testDeleteByQueryRequest() throws IOException {
    DeleteByQueryRequest delete = new DeleteByQueryRequest(new SearchRequest());
    randomRequest(delete);
    DeleteByQueryRequest tripped = new DeleteByQueryRequest();
    roundTrip(delete, tripped);
    assertRequestEquals(delete, tripped);

    // Try slices with a version that doesn't support slices. That should fail.
    delete.setSlices(between(2, 1000));
    Exception e = expectThrows(IllegalArgumentException.class, () -> roundTrip(Version.V_5_0_0_rc1, delete, null));
    assertEquals("Attempting to send sliced reindex-style request to a node that doesn't support it. "
            + "Version is [5.0.0-rc1] but must be [5.1.1]", e.getMessage());

    // Try without slices with a version that doesn't support slices. That should work.
    tripped = new DeleteByQueryRequest();
    delete.setSlices(1);
    roundTrip(Version.V_5_0_0_rc1, delete, tripped);
    assertRequestEquals(delete, tripped);
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:RoundTripTests.java

示例13: setUp

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
@Before
@Override
public void setUp() throws Exception {
    super.setUp();
    final ExecutorService directExecutor = EsExecutors.newDirectExecutorService();
    threadPool = new TestThreadPool(getTestName()) {
        @Override
        public ExecutorService executor(String name) {
            return directExecutor;
        }

        @Override
        public ScheduledFuture<?> schedule(TimeValue delay, String name, Runnable command) {
            command.run();
            return null;
        }
    };
    retries = 0;
    searchRequest = new SearchRequest();
    searchRequest.scroll(timeValueMinutes(5));
    searchRequest.source(new SearchSourceBuilder().size(10).version(true).sort("_doc").size(123));
    retriesAllowed = 0;
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:24,代碼來源:RemoteScrollableHitSourceTests.java

示例14: testInitialSearchParamsSort

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
public void testInitialSearchParamsSort() {
    SearchRequest searchRequest = new SearchRequest().source(new SearchSourceBuilder());

    // Test sort:_doc for versions that support it.
    Version remoteVersion = Version.fromId(between(Version.V_2_1_0_ID, Version.CURRENT.id));
    searchRequest.source().sort("_doc");
    assertThat(initialSearchParams(searchRequest, remoteVersion), hasEntry("sort", "_doc:asc"));

    // Test search_type scan for versions that don't support sort:_doc.
    remoteVersion = Version.fromId(between(0, Version.V_2_1_0_ID - 1));
    assertThat(initialSearchParams(searchRequest, remoteVersion), hasEntry("search_type", "scan"));

    // Test sorting by some field. Version doesn't matter.
    remoteVersion = Version.fromId(between(0, Version.CURRENT.id));
    searchRequest.source().sorts().clear();
    searchRequest.source().sort("foo");
    assertThat(initialSearchParams(searchRequest, remoteVersion), hasEntry("sort", "foo:asc"));
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:19,代碼來源:RemoteRequestBuildersTests.java

示例15: testInitialSearchParamsFields

import org.elasticsearch.action.search.SearchRequest; //導入依賴的package包/類
public void testInitialSearchParamsFields() {
    SearchRequest searchRequest = new SearchRequest().source(new SearchSourceBuilder());

    // Test request without any fields
    Version remoteVersion = VersionUtils.randomVersion(random());
    assertThat(initialSearchParams(searchRequest, remoteVersion),
            not(either(hasKey("stored_fields")).or(hasKey("fields"))));

    // Setup some fields for the next two tests
    searchRequest.source().storedField("_source").storedField("_id");

    // Test stored_fields for versions that support it
    remoteVersion = VersionUtils.randomVersionBetween(random(), Version.V_5_0_0_alpha4, null);
    assertThat(initialSearchParams(searchRequest, remoteVersion), hasEntry("stored_fields", "_source,_id"));

    // Test fields for versions that support it
    remoteVersion = VersionUtils.randomVersionBetween(random(), null, Version.V_5_0_0_alpha3);
    assertThat(initialSearchParams(searchRequest, remoteVersion), hasEntry("fields", "_source,_id"));
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:RemoteRequestBuildersTests.java


注:本文中的org.elasticsearch.action.search.SearchRequest類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。