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

The following examples show how to use org.elasticsearch.action.search.SearchRequestBuilder#toString() . 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: ScanBuilder.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public void setup(List<ElasticsearchPrel> stack, FunctionLookupContext functionLookupContext) {

    validate(stack);

    try {
      final SearchRequestBuilder searchRequest = buildRequestBuilder();


      final Map<Class<?>, ElasticsearchPrel> map = validate(stack);

      final ElasticIntermediateScanPrel scan = (ElasticIntermediateScanPrel) map.get(ElasticIntermediateScanPrel.class);
      final ElasticTableXattr tableAttributes = scan.getExtendedAttributes();
      final ElasticsearchFilter filter = (ElasticsearchFilter) map.get(ElasticsearchFilter.class);
      final ElasticsearchSample sample = (ElasticsearchSample) map.get(ElasticsearchSample.class);
      final ElasticsearchLimit limit = (ElasticsearchLimit) map.get(ElasticsearchLimit.class);

      applyEdgeProjection(searchRequest, scan);
      applyFilter(searchRequest, scan, filter, tableAttributes);
      final int fetch = applyFetch(searchRequest,
        ElasticsearchConf.createElasticsearchConf(scan.getPluginId().getConnectionConf()),
        limit, filter, sample);

      ElasticsearchScanSpec scanSpec = new ElasticsearchScanSpec(
          tableAttributes.getResource(),
          searchRequest.toString(),
          fetch,
          filter != null || sample != null || limit != null);

      this.spec = scanSpec;
      this.scan = scan;
    } catch (ExpressionNotAnalyzableException e) {
      throw UserException.dataReadError(e).message("Elastic pushdown failed. Too late to recover query.").build(logger);
    }
  }
 
Example 2
Source File: SqlElasticDeleteByQueryRequestBuilder.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
@Override
public String explain() {
    try {
        SearchRequestBuilder source = deleteByQueryRequestBuilder.source();
        return source.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 3
Source File: EsEntityIndexImpl.java    From usergrid with Apache License 2.0 4 votes vote down vote up
public CandidateResults search( final SearchEdge searchEdge, final SearchTypes searchTypes, final ParsedQuery parsedQuery,
                                final int limit, final int offset, final Map<String, Class> fieldsWithType,
                                final boolean analyzeOnly, final boolean returnQuery ) {

    IndexValidationUtils.validateSearchEdge(searchEdge);
    Preconditions.checkNotNull(searchTypes, "searchTypes cannot be null");
    Preconditions.checkArgument( limit > 0, "limit must be > 0" );


    SearchResponse searchResponse;

    if ( parsedQuery == null ){
        throw new IllegalArgumentException("a null query string cannot be parsed");
    }

    if (parsedQuery.isDirectQuery() && parsedQuery.getDirectQueryItemCount() > indexFig.directQueryMaxItems()) {
        throw new TooManyDirectEntitiesException(parsedQuery.getDirectQueryItemCount(), indexFig.directQueryMaxItems());
    }

    final QueryVisitor visitor = visitParsedQuery(parsedQuery);

    List<Identifier> directIdentifiers = visitor.getDirectIdentifiers();
    if (directIdentifiers != null && directIdentifiers.size() > 0) {
        // this is a direct query
        return buildCandidateResultsForDirectQuery(directIdentifiers, parsedQuery, searchTypes);
    }

    boolean hasGeoSortPredicates = false;

    for (SortPredicate sortPredicate : parsedQuery.getSortPredicates() ){
        hasGeoSortPredicates = visitor.getGeoSorts().contains(sortPredicate.getPropertyName());
    }

    final String cacheKey = applicationScope.getApplication().getUuid().toString()+"_"+searchEdge.getEdgeName();
    final Object totalEdgeSizeFromCache = sizeCache.getIfPresent(cacheKey);
    long totalEdgeSizeInBytes;
    if (totalEdgeSizeFromCache == null){
        totalEdgeSizeInBytes = getTotalEntitySizeInBytes(searchEdge);
        sizeCache.put(cacheKey, totalEdgeSizeInBytes);
    }else{
        totalEdgeSizeInBytes = (long) totalEdgeSizeFromCache;
    }

    final Object totalIndexSizeFromCache = sizeCache.getIfPresent(indexLocationStrategy.getIndexRootName());
    long totalIndexSizeInBytes;
    if (totalIndexSizeFromCache == null){
        totalIndexSizeInBytes = getIndexSize();
        sizeCache.put(indexLocationStrategy.getIndexRootName(), totalIndexSizeInBytes);
    }else{
        totalIndexSizeInBytes = (long) totalIndexSizeFromCache;
    }

    List<Map<String, Object>> violations = QueryAnalyzer.analyze(parsedQuery, totalEdgeSizeInBytes, totalIndexSizeInBytes, indexFig);
    if(indexFig.enforceQueryBreaker() && violations.size() > 0){
        throw new QueryAnalyzerEnforcementException(violations, parsedQuery.getOriginalQuery());
    }else if (violations.size() > 0){
        logger.warn( QueryAnalyzer.violationsAsString(violations, parsedQuery.getOriginalQuery()) );
    }

    if(analyzeOnly){
        throw new QueryAnalyzerException(violations, parsedQuery.getOriginalQuery(), applicationScope.getApplication().getUuid());
    }

    final SearchRequestBuilder srb = searchRequest
        .getBuilder( searchEdge, searchTypes, visitor, limit, offset, parsedQuery.getSortPredicates(), fieldsWithType )
        .setTimeout(TimeValue.timeValueMillis(queryTimeout));

    if ( logger.isDebugEnabled() ) {
        logger.debug( "Searching index (read alias): {}\n  nodeId: {}, edgeType: {},  \n type: {}\n   query: {} ",
            this.alias.getReadAlias(), searchEdge.getNodeId(), searchEdge.getEdgeName(),
            searchTypes.getTypeNames( applicationScope ), srb );
    }

    if (returnQuery) {
        throw new QueryReturnException(parsedQuery.getOriginalQuery(), srb.toString(), applicationScope.getApplication().getUuid());
    }

    //Added For Graphite Metrics
    final Timer.Context timerContext = searchTimer.time();

    try {

        searchResponse = srb.execute().actionGet();
    }
    catch ( Throwable t ) {
        logger.error( "Unable to communicate with Elasticsearch: {}", t.getMessage() );
        failureMonitor.fail( "Unable to execute batch", t );
        throw t;
    }
    finally{
        timerContext.stop();
    }

    failureMonitor.success();

    return parseResults( searchResponse, parsedQuery, limit, offset, hasGeoSortPredicates);
}