Java Code Examples for org.elasticsearch.action.search.SearchRequestBuilder#setTimeout()

The following examples show how to use org.elasticsearch.action.search.SearchRequestBuilder#setTimeout() . 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: Job.java    From zentity with Apache License 2.0 6 votes vote down vote up
/**
 * Submit a search query to Elasticsearch.
 *
 * @param indexName The name of the index to search.
 * @param query     The query to search.
 * @return The search response returned by Elasticsearch.
 * @throws IOException
 */
private SearchResponse search(String indexName, String query) throws IOException {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    SearchModule searchModule = new SearchModule(Settings.EMPTY, false, Collections.emptyList());
    try (XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(new NamedXContentRegistry(searchModule
            .getNamedXContents()), DeprecationHandler.THROW_UNSUPPORTED_OPERATION, query)) {
        searchSourceBuilder.parseXContent(parser);
    }
    SearchRequestBuilder searchRequestBuilder = new SearchRequestBuilder(client, SearchAction.INSTANCE);
    searchRequestBuilder.setIndices(indexName).setSource(searchSourceBuilder);
    if (this.searchAllowPartialSearchResults != null)
        searchRequestBuilder.setAllowPartialSearchResults(this.searchAllowPartialSearchResults);
    if (this.searchBatchedReduceSize != null)
        searchRequestBuilder.setBatchedReduceSize(this.searchBatchedReduceSize);
    if (this.searchMaxConcurrentShardRequests != null)
        searchRequestBuilder.setMaxConcurrentShardRequests(this.searchMaxConcurrentShardRequests);
    if (this.searchPreFilterShardSize != null)
        searchRequestBuilder.setPreFilterShardSize(this.searchPreFilterShardSize);
    if (this.searchPreference != null)
        searchRequestBuilder.setPreference(this.searchPreference);
    if (this.searchRequestCache != null)
        searchRequestBuilder.setRequestCache(this.searchRequestCache);
    if (this.maxTimePerQuery != null)
        searchRequestBuilder.setTimeout(TimeValue.parseTimeValue(this.maxTimePerQuery, "timeout"));
    return searchRequestBuilder.execute().actionGet();
}
 
Example 2
Source File: SearchQueryServiceImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private SearchResponse executeSearch(final RepositoryQueryBuilder repoQuery,
                                     final String[] searchableIndexes,
                                     final int from, final int size,
                                     @Nullable final QueryBuilder postFilter)
{
  SearchRequestBuilder searchRequestBuilder = client.get().prepareSearch(searchableIndexes)
      .setTypes(TYPE)
      .setQuery(repoQuery)
      .setFrom(from)
      .setSize(size)
      .setProfile(profile);

  if (repoQuery.sort != null) {
    for (SortBuilder entry : repoQuery.sort) {
      searchRequestBuilder.addSort(entry);
    }
  }

  if (postFilter != null) {
    searchRequestBuilder.setPostFilter(postFilter);
  }

  if (repoQuery.timeout != null) {
    searchRequestBuilder.setTimeout(repoQuery.timeout.getSeconds() + "s");
  }

  SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();

  if (profile) {
    logProfileResults(searchResponse);
  }

  return searchResponse;
}
 
Example 3
Source File: SearchQueryServiceImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private SearchResponse executeSearch(final RepositoryQueryBuilder repoQuery,
                                     final String[] searchableIndexes,
                                     final List<AggregationBuilder> aggregations,
                                     @Nullable final QueryBuilder postFilter)
{
  SearchRequestBuilder searchRequestBuilder = client.get().prepareSearch(searchableIndexes)
      .setTypes(TYPE)
      .setQuery(repoQuery)
      .setFrom(0)
      .setSize(0)
      .setProfile(profile)
      .setTrackScores(true);

  for (AggregationBuilder aggregation : aggregations) {
    searchRequestBuilder.addAggregation(aggregation);
  }

  if (repoQuery.sort != null) {
    for (SortBuilder entry : repoQuery.sort) {
      searchRequestBuilder.addSort(entry);
    }
  }

  if (postFilter != null) {
    searchRequestBuilder.setPostFilter(postFilter);
  }

  if (repoQuery.timeout != null) {
    searchRequestBuilder.setTimeout(repoQuery.timeout.getSeconds() + "s");
  }

  SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();

  if (profile) {
    logProfileResults(searchResponse);
  }

  return searchResponse;
}
 
Example 4
Source File: QueryAction.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
protected void updateRequestWithTimeout(Select select, SearchRequestBuilder request) {
    for (Hint hint : select.getHints()) {
        if (hint.getType() == HintType.TIMEOUT && hint.getParams() != null && 0 < hint.getParams().length) {
            String param = hint.getParams()[0].toString();
            request.setTimeout(TimeValue.parseTimeValue(param, SearchSourceBuilder.TIMEOUT_FIELD.getPreferredName()));
        }
    }
}
 
Example 5
Source File: EsAbstractConditionBean.java    From fess with Apache License 2.0 5 votes vote down vote up
public void build(SearchRequestBuilder builder) {
    if (explain != null) {
        builder.setExplain(explain);
    }
    if (minScore != null) {
        builder.setMinScore(minScore);
    }
    if (preference != null) {
        builder.setPreference(preference);
    }
    if (routing != null) {
        builder.setRouting(routing);
    }
    if (searchType != null) {
        builder.setSearchType(searchType);
    }
    if (timeoutInMillis != -1) {
        builder.setTimeout(new TimeValue(timeoutInMillis));
    }
    if (version != null) {
        builder.setVersion(version);
    }
    if (seqNoAndPrimaryTerm != null) {
        builder.seqNoAndPrimaryTerm(seqNoAndPrimaryTerm);
    }
    if (terminateAfter > 0) {
        builder.setTerminateAfter(terminateAfter);
    }
}
 
Example 6
Source File: EsAbstractConditionBean.java    From fess with Apache License 2.0 5 votes vote down vote up
public void build(SearchRequestBuilder builder) {
    if (explain != null) {
        builder.setExplain(explain);
    }
    if (minScore != null) {
        builder.setMinScore(minScore);
    }
    if (preference != null) {
        builder.setPreference(preference);
    }
    if (routing != null) {
        builder.setRouting(routing);
    }
    if (searchType != null) {
        builder.setSearchType(searchType);
    }
    if (timeoutInMillis != -1) {
        builder.setTimeout(new TimeValue(timeoutInMillis));
    }
    if (version != null) {
        builder.setVersion(version);
    }
    if (seqNoAndPrimaryTerm != null) {
        builder.seqNoAndPrimaryTerm(seqNoAndPrimaryTerm);
    }
    if (terminateAfter > 0) {
        builder.setTerminateAfter(terminateAfter);
    }
}
 
Example 7
Source File: FessEsClient.java    From fess with Apache License 2.0 5 votes vote down vote up
public <T> T search(final String index, final SearchCondition<SearchRequestBuilder> condition,
        final SearchResult<T, SearchRequestBuilder, SearchResponse> searchResult) {
    final long startTime = System.currentTimeMillis();

    SearchResponse searchResponse = null;
    final SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index);
    if (condition.build(searchRequestBuilder)) {

        final FessConfig fessConfig = ComponentUtil.getFessConfig();
        final long queryTimeout = fessConfig.getQueryTimeoutAsInteger().longValue();
        if (queryTimeout >= 0) {
            searchRequestBuilder.setTimeout(TimeValue.timeValueMillis(queryTimeout));
        }

        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Query DSL:\n{}", searchRequestBuilder);
            }
            searchResponse = searchRequestBuilder.execute().actionGet(ComponentUtil.getFessConfig().getIndexSearchTimeout());
        } catch (final SearchPhaseExecutionException e) {
            throw new InvalidQueryException(messages -> messages.addErrorsInvalidQueryParseError(UserMessages.GLOBAL_PROPERTY_KEY),
                    "Invalid query: " + searchRequestBuilder, e);
        }
    }
    final long execTime = System.currentTimeMillis() - startTime;

    return searchResult.build(searchRequestBuilder, execTime, OptionalEntity.ofNullable(searchResponse, () -> {}));
}
 
Example 8
Source File: EsAbstractConditionBean.java    From fess with Apache License 2.0 5 votes vote down vote up
public void build(SearchRequestBuilder builder) {
    if (explain != null) {
        builder.setExplain(explain);
    }
    if (minScore != null) {
        builder.setMinScore(minScore);
    }
    if (preference != null) {
        builder.setPreference(preference);
    }
    if (routing != null) {
        builder.setRouting(routing);
    }
    if (searchType != null) {
        builder.setSearchType(searchType);
    }
    if (timeoutInMillis != -1) {
        builder.setTimeout(new TimeValue(timeoutInMillis));
    }
    if (version != null) {
        builder.setVersion(version);
    }
    if (seqNoAndPrimaryTerm != null) {
        builder.seqNoAndPrimaryTerm(seqNoAndPrimaryTerm);
    }
    if (terminateAfter > 0) {
        builder.setTerminateAfter(terminateAfter);
    }
}
 
Example 9
Source File: ESQueryState.java    From sql4es with Apache License 2.0 4 votes vote down vote up
/**
 * Builds the Elasticsearch query object based on the parsed information from the SQL query
 * @param searchReq
 * @param info
 */
private void buildQuery(SearchRequestBuilder searchReq, ParseResult info) {
	String[] types = new String[info.getSources().size()];
	for(int i=0; i<info.getSources().size(); i++) types[i] = info.getSources().get(i).getSource(); 
	SearchRequestBuilder req = searchReq.setTypes(types);
	
	// add filters and aggregations
	if(info.getAggregation() != null){
		// when aggregating the query must be a query and not a filter
		if(info.getQuery() != null)	req.setQuery(info.getQuery());
		req.addAggregation(info.getAggregation());
		
	// ordering does not work on aggregations (has to be done in client)
	}else if(info.getQuery() != null){
		if(info.getRequestScore()) req.setQuery(info.getQuery()); // use query instead of filter to get a score
		else req.setPostFilter(info.getQuery());
		
		// add order
		for(OrderBy ob : info.getSorts()){
			req.addSort(ob.getField(), ob.getOrder());
		}
	} else req.setQuery(QueryBuilders.matchAllQuery());
	
	this.limit = info.getLimit();
	if(splitRS) maxRowsRS = fetchSize;
	
	//System.out.println("fetch: "+fetchSize+" limit: "+limit+" split: "+splitRS);
	
	// add limit and determine to use scroll
	if(info.getAggregation() != null) {
		req = req.setSize(0);
	} else{
		if(limit > 0 && limit < fetchSize){ // no scroll needed
			req.setSize(limit);
		} else{ // use scrolling
			req.setSize(fetchSize);
			req.setScroll(new TimeValue(Utils.getIntProp(props, Utils.PROP_SCROLL_TIMEOUT_SEC, 60)*1000));
			if (info.getSorts().isEmpty()) req.addSort("_doc", SortOrder.ASC); // scroll works fast with sort on _doc
		}
	}
	
	// use query cache when this was indicated in FROM clause
	if(info.getUseCache()) req.setRequestCache(true);
	req.setTimeout(TimeValue.timeValueMillis(Utils.getIntProp(props, Utils.PROP_QUERY_TIMEOUT_MS, 10000)));
}