Java Code Examples for org.elasticsearch.search.internal.SearchContext#setCurrent()

The following examples show how to use org.elasticsearch.search.internal.SearchContext#setCurrent() . 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: TransportExistsAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected ShardExistsResponse shardOperation(ShardExistsRequest request) {
    IndexService indexService = indicesService.indexServiceSafe(request.shardId().getIndex());
    IndexShard indexShard = indexService.shardSafe(request.shardId().id());

    SearchShardTarget shardTarget = new SearchShardTarget(clusterService.localNode().id(), request.shardId().getIndex(), request.shardId().id());
    SearchContext context = new DefaultSearchContext(0,
            new ShardSearchLocalRequest(request.types(), request.nowInMillis(), request.filteringAliases()),
            shardTarget, indexShard.acquireSearcher("exists"), indexService, indexShard,
            scriptService, pageCacheRecycler, bigArrays, threadPool.estimatedTimeInMillisCounter(), parseFieldMatcher,
            SearchService.NO_TIMEOUT
    );
    SearchContext.setCurrent(context);

    try {
        if (request.minScore() != DEFAULT_MIN_SCORE) {
            context.minimumScore(request.minScore());
        }
        BytesReference source = request.querySource();
        if (source != null && source.length() > 0) {
            try {
                QueryParseContext.setTypes(request.types());
                context.parsedQuery(indexService.queryParserService().parseQuery(source));
            } finally {
                QueryParseContext.removeTypes();
            }
        }
        context.preProcess();
        try {
            boolean exists;
            try {
                exists = Lucene.exists(context.searcher(), context.query());
            } finally {
                context.clearReleasables(SearchContext.Lifetime.COLLECTION);
            }
            return new ShardExistsResponse(request.shardId(), exists);
        } catch (Exception e) {
            throw new QueryPhaseExecutionException(context, "failed to execute exists", e);
        }
    } finally {
        // this will also release the index searcher
        context.close();
        SearchContext.removeCurrent();
    }
}
 
Example 2
Source File: TransportExplainAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected ExplainResponse shardOperation(ExplainRequest request, ShardId shardId) {
    IndexService indexService = indicesService.indexServiceSafe(shardId.getIndex());
    IndexShard indexShard = indexService.shardSafe(shardId.id());
    Term uidTerm = new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(request.type(), request.id()));
    Engine.GetResult result = indexShard.get(new Engine.Get(false, uidTerm));
    if (!result.exists()) {
        return new ExplainResponse(shardId.getIndex(), request.type(), request.id(), false);
    }

    SearchContext context = new DefaultSearchContext(
            0, new ShardSearchLocalRequest(new String[]{request.type()}, request.nowInMillis, request.filteringAlias()),
            null, result.searcher(), indexService, indexShard,
            scriptService, pageCacheRecycler,
            bigArrays, threadPool.estimatedTimeInMillisCounter(), parseFieldMatcher,
            SearchService.NO_TIMEOUT
    );
    SearchContext.setCurrent(context);

    try {
        context.parsedQuery(indexService.queryParserService().parseQuery(request.source()));
        context.preProcess();
        int topLevelDocId = result.docIdAndVersion().docId + result.docIdAndVersion().context.docBase;
        Explanation explanation = context.searcher().explain(context.query(), topLevelDocId);
        for (RescoreSearchContext ctx : context.rescore()) {
            Rescorer rescorer = ctx.rescorer();
            explanation = rescorer.explain(topLevelDocId, context, ctx, explanation);
        }
        if (request.fields() != null || (request.fetchSourceContext() != null && request.fetchSourceContext().fetchSource())) {
            // Advantage is that we're not opening a second searcher to retrieve the _source. Also
            // because we are working in the same searcher in engineGetResult we can be sure that a
            // doc isn't deleted between the initial get and this call.
            GetResult getResult = indexShard.getService().get(result, request.id(), request.type(), request.fields(), request.fetchSourceContext(), false);
            return new ExplainResponse(shardId.getIndex(), request.type(), request.id(), true, explanation, getResult);
        } else {
            return new ExplainResponse(shardId.getIndex(), request.type(), request.id(), true, explanation);
        }
    } catch (IOException e) {
        throw new ElasticsearchException("Could not explain", e);
    } finally {
        context.close();
        SearchContext.removeCurrent();
    }
}
 
Example 3
Source File: TransportTermsByQueryAction.java    From siren-join with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * The operation that executes the query and generates a {@link TermsByQueryShardResponse} for each shard.
 */
@Override
protected TermsByQueryShardResponse shardOperation(TermsByQueryShardRequest shardRequest) throws ElasticsearchException {
  IndexService indexService = indicesService.indexServiceSafe(shardRequest.shardId().getIndex());
  IndexShard indexShard = indexService.shardSafe(shardRequest.shardId().id());
  TermsByQueryRequest request = shardRequest.request();
  OrderByShardOperation orderByOperation = OrderByShardOperation.get(request.getOrderBy(), request.maxTermsPerShard());

  SearchShardTarget shardTarget = new SearchShardTarget(clusterService.localNode().id(),
                                                        shardRequest.shardId().getIndex(),
                                                        shardRequest.shardId().id());

  ShardSearchRequest shardSearchRequest = new ShardSearchLocalRequest(request.types(), request.nowInMillis(),
                                                                      shardRequest.filteringAliases());

  SearchContext context = new DefaultSearchContext(0, shardSearchRequest, shardTarget,
    indexShard.acquireSearcher("termsByQuery"), indexService, indexShard, scriptService,
    pageCacheRecycler, bigArrays, threadPool.estimatedTimeInMillisCounter(), parseFieldMatcher,
    SearchService.NO_TIMEOUT);
  SearchContext.setCurrent(context);

  try {
    MappedFieldType fieldType = context.smartNameFieldType(request.field());
    if (fieldType == null) {
      throw new SearchContextException(context, "[termsByQuery] field '" + request.field() +
              "' not found for types " + Arrays.toString(request.types()));
    }

    IndexFieldData indexFieldData = context.fieldData().getForField(fieldType);

    BytesReference querySource = request.querySource();
    if (querySource != null && querySource.length() > 0) {
      XContentParser queryParser = null;
      try {
        queryParser = XContentFactory.xContent(querySource).createParser(querySource);
        QueryParseContext.setTypes(request.types());
        ParsedQuery parsedQuery = orderByOperation.getParsedQuery(queryParser, indexService);
        if (parsedQuery != null) {
          context.parsedQuery(parsedQuery);
        }
      }
      finally {
        QueryParseContext.removeTypes();
        if (queryParser != null) {
          queryParser.close();
        }
      }
    }

    context.preProcess();

    // execute the search only gathering the hit count and bitset for each segment
    logger.debug("{}: Executes search for collecting terms {}", Thread.currentThread().getName(),
      shardRequest.shardId());

    TermsCollector termsCollector = this.getTermsCollector(request.termsEncoding(), indexFieldData, context);
    if (request.expectedTerms() != null) termsCollector.setExpectedTerms(request.expectedTerms());
    if (request.maxTermsPerShard() != null) termsCollector.setMaxTerms(request.maxTermsPerShard());
    HitStream hitStream = orderByOperation.getHitStream(context);
    TermsSet terms = termsCollector.collect(hitStream);

    logger.debug("{}: Returns terms response with {} terms for shard {}", Thread.currentThread().getName(),
      terms.size(), shardRequest.shardId());

    return new TermsByQueryShardResponse(shardRequest.shardId(), terms);
  }
  catch (Throwable e) {
    logger.error("[termsByQuery] Error executing shard operation", e);
    throw new QueryPhaseExecutionException(context, "[termsByQuery] Failed to execute query", e);
  }
  finally {
    // this will also release the index searcher
    context.close();
    SearchContext.removeCurrent();
  }
}