Package org.elasticsearch.search.internal

Examples of org.elasticsearch.search.internal.SearchContext


    }

    @Override
    public Weight createWeight(IndexSearcher searcher) throws IOException {
        ObjectObjectOpenHashMap<Object, ParentDoc[]> parentDocs = new ObjectObjectOpenHashMap<>();
        SearchContext searchContext = SearchContext.current();

        int parentHitsResolved;
        int requestedDocs = (searchContext.from() + searchContext.size());
        if (requestedDocs <= 0) {
            requestedDocs = 1;
        }
        int numChildDocs = requestedDocs * factor;

        Query childQuery;
        if (rewrittenChildQuery == null) {
            childQuery = rewrittenChildQuery = searcher.rewrite(originalChildQuery);
        } else {
            assert rewriteIndexReader == searcher.getIndexReader() : "not equal, rewriteIndexReader=" + rewriteIndexReader + " searcher.getIndexReader()=" + searcher.getIndexReader();
            childQuery = rewrittenChildQuery;
        }

        IndexSearcher indexSearcher = new IndexSearcher(searcher.getIndexReader());
        indexSearcher.setSimilarity(searcher.getSimilarity());
        while (true) {
            parentDocs.clear();
            TopDocs topChildDocs = indexSearcher.search(childQuery, numChildDocs);
            try {
                parentHitsResolved = resolveParentDocuments(topChildDocs, searchContext, parentDocs);
            } catch (Exception e) {
                throw new IOException(e);
            }

            // check if we found enough docs, if so, break
            if (parentHitsResolved >= requestedDocs) {
                break;
            }
            // if we did not find enough docs, check if it make sense to search further
            if (topChildDocs.totalHits <= numChildDocs) {
                break;
            }
            // if not, update numDocs, and search again
            numChildDocs *= incrementalFactor;
            if (numChildDocs > topChildDocs.totalHits) {
                numChildDocs = topChildDocs.totalHits;
            }
        }

        ParentWeight parentWeight =  new ParentWeight(rewrittenChildQuery.createWeight(searcher), parentDocs);
        searchContext.addReleasable(parentWeight, Lifetime.COLLECTION);
        return parentWeight;
    }
View Full Code Here


        return q;
    }

    @Override
    public Weight createWeight(IndexSearcher searcher) throws IOException {
        SearchContext sc = SearchContext.current();
        ChildWeight childWeight;
        boolean releaseCollectorResource = true;
        ParentOrdAndScoreCollector collector = null;
        IndexParentChildFieldData globalIfd = parentChildIndexFieldData.loadGlobal(searcher.getIndexReader());
        if (globalIfd == null) {
            // No docs of the specified type don't exist on this shard
            return Queries.newMatchNoDocsQuery().createWeight(searcher);
        }

        try {
            assert rewrittenParentQuery != null;
            assert rewriteIndexReader == searcher.getIndexReader() : "not equal, rewriteIndexReader=" + rewriteIndexReader + " searcher.getIndexReader()=" + searcher.getIndexReader();
            final Query  parentQuery = rewrittenParentQuery;
            collector = new ParentOrdAndScoreCollector(sc, globalIfd, parentType);
            IndexSearcher indexSearcher = new IndexSearcher(sc.searcher().getIndexReader());
            indexSearcher.setSimilarity(searcher.getSimilarity());
            indexSearcher.search(parentQuery, collector);
            if (collector.parentCount() == 0) {
                return Queries.newMatchNoDocsQuery().createWeight(searcher);
            }
            childWeight = new ChildWeight(parentQuery.createWeight(searcher), childrenFilter, collector, globalIfd);
            releaseCollectorResource = false;
        } finally {
            if (releaseCollectorResource) {
                // either if we run into an exception or if we return early
                Releasables.close(collector);
            }
        }
        sc.addReleasable(collector, Lifetime.COLLECTION);
        return childWeight;
    }
View Full Code Here

        rewrittenChildQuery.extractTerms(terms);
    }

    @Override
    public Weight createWeight(IndexSearcher searcher) throws IOException {
        SearchContext sc = SearchContext.current();
        assert rewrittenChildQuery != null;
        assert rewriteIndexReader == searcher.getIndexReader() : "not equal, rewriteIndexReader=" + rewriteIndexReader
                + " searcher.getIndexReader()=" + searcher.getIndexReader();
        final Query childQuery = rewrittenChildQuery;

        IndexParentChildFieldData globalIfd = ifd.loadGlobal(searcher.getIndexReader());
        if (globalIfd == null) {
            // No docs of the specified type exist on this shard
            return Queries.newMatchNoDocsQuery().createWeight(searcher);
        }
        IndexSearcher indexSearcher = new IndexSearcher(searcher.getIndexReader());
        indexSearcher.setSimilarity(searcher.getSimilarity());

        boolean abort = true;
        long numFoundParents;
        ParentCollector collector = null;
        try {
            if (minChildren == 0 && maxChildren == 0 && scoreType != ScoreType.NONE) {
                switch (scoreType) {
                case MIN:
                    collector = new MinCollector(globalIfd, sc, parentType);
                    break;
                case MAX:
                    collector = new MaxCollector(globalIfd, sc, parentType);
                    break;
                case SUM:
                    collector = new SumCollector(globalIfd, sc, parentType);
                    break;
                }
            }
            if (collector == null) {
                switch (scoreType) {
                case MIN:
                    collector = new MinCountCollector(globalIfd, sc, parentType);
                    break;
                case MAX:
                    collector = new MaxCountCollector(globalIfd, sc, parentType);
                    break;
                case SUM:
                case AVG:
                    collector = new SumCountAndAvgCollector(globalIfd, sc, parentType);
                    break;
                case NONE:
                    collector = new CountCollector(globalIfd, sc, parentType);
                    break;
                default:
                    throw new RuntimeException("Are we missing a score type here? -- " + scoreType);
                }
            }

            indexSearcher.search(childQuery, collector);
            numFoundParents = collector.foundParents();
            if (numFoundParents == 0) {
                return Queries.newMatchNoDocsQuery().createWeight(searcher);
            }
            abort = false;
        } finally {
            if (abort) {
                Releasables.close(collector);
            }
        }
        sc.addReleasable(collector, Lifetime.COLLECTION);
        final Filter parentFilter;
        if (numFoundParents <= shortCircuitParentDocSet) {
            parentFilter = ParentIdsFilter.createShortCircuitFilter(nonNestedDocsFilter, sc, parentType, collector.values,
                    collector.parentIdxs, numFoundParents);
        } else {
View Full Code Here

        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()
        );
        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();
        }
    }
View Full Code Here

        return query;
    }

    @Override
    public DocIdSet getDocIdSet(final LeafReaderContext context, final Bits acceptDocs) throws IOException {
        final SearchContext searchContext = SearchContext.current();
        if (docIdSets == null) {
            assert searcher == null;
            IndexSearcher searcher = searchContext.searcher();
            docIdSets = new IdentityHashMap<>();
            this.searcher = searcher;
            searchContext.addReleasable(this, Lifetime.COLLECTION);

            final Weight weight = searcher.createNormalizedWeight(query);
            for (final LeafReaderContext leaf : searcher.getTopReaderContext().leaves()) {
                final DocIdSet set = new DocIdSet() {
                    @Override
View Full Code Here

    protected ShardExistsResponse shardOperation(ShardExistsRequest request) throws ElasticsearchException {
        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());
        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 {
                Lucene.EarlyTerminatingCollector existsCollector = Lucene.createExistsCollector();
                Lucene.exists(context.searcher(), context.query(), existsCollector);
                return new ShardExistsResponse(request.shardId(), existsCollector.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();
        }
    }
View Full Code Here

        return q;
    }

    @Override
    public Weight createWeight(IndexSearcher searcher) throws IOException {
        SearchContext sc = SearchContext.current();
        IndexParentChildFieldData globalIfd = parentChildIndexFieldData.loadGlobal(searcher.getIndexReader());
        assert rewrittenChildQuery != null;
        assert rewriteIndexReader == searcher.getIndexReader()  : "not equal, rewriteIndexReader=" + rewriteIndexReader + " searcher.getIndexReader()=" + searcher.getIndexReader();

        final long valueCount;
View Full Code Here

    protected ShardCountResponse shardOperation(ShardCountRequest request) throws ElasticsearchException {
        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("count"), indexService, indexShard,
                scriptService, pageCacheRecycler, bigArrays, threadPool.estimatedTimeInMillisCounter());
        SearchContext.setCurrent(context);

        try {
            // TODO: min score should move to be "null" as a value that is not initialized...
            if (request.minScore() != -1) {
                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();
                }
            }
            final boolean hasTerminateAfterCount = request.terminateAfter() != DEFAULT_TERMINATE_AFTER;
            boolean terminatedEarly = false;
            context.preProcess();
            try {
                long count;
                if (hasTerminateAfterCount) {
                    final Lucene.EarlyTerminatingCollector countCollector =
                            Lucene.createCountBasedEarlyTerminatingCollector(request.terminateAfter());
                    terminatedEarly = Lucene.countWithEarlyTermination(context.searcher(), context.query(), countCollector);
                    count = countCollector.count();
                } else {
                    count = Lucene.count(context.searcher(), context.query());
                }
                return new ShardCountResponse(request.shardId(), count, terminatedEarly);
            } catch (Exception e) {
                throw new QueryPhaseExecutionException(context, "failed to execute count", e);
            }
        } finally {
            // this will also release the index searcher
            context.close();
            SearchContext.removeCurrent();
        }
    }
View Full Code Here

TOP

Related Classes of org.elasticsearch.search.internal.SearchContext

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.