org.apache.lucene.search.Scorer Java Examples

The following examples show how to use org.apache.lucene.search.Scorer. 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: ParentQuery.java    From Elasticsearch with Apache License 2.0 7 votes vote down vote up
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
    DocIdSet childrenDocSet = childrenFilter.getDocIdSet(context, null);
    // we forcefully apply live docs here so that deleted children don't give matching parents
    childrenDocSet = BitsFilteredDocIdSet.wrap(childrenDocSet, context.reader().getLiveDocs());
    if (Lucene.isEmpty(childrenDocSet)) {
        return null;
    }
    final DocIdSetIterator childIterator = childrenDocSet.iterator();
    if (childIterator == null) {
        return null;
    }
    SortedDocValues bytesValues = globalIfd.load(context).getOrdinalsValues(parentType);
    if (bytesValues == null) {
        return null;
    }

    return new ChildScorer(this, parentIdxs, scores, childIterator, bytesValues);
}
 
Example #2
Source File: GroupingLongCollectorBenchmark.java    From crate with Apache License 2.0 6 votes vote down vote up
@Benchmark
public LongObjectHashMap<Long> measureGroupingOnNumericDocValues() throws Exception {
    Weight weight = searcher.createWeight(new MatchAllDocsQuery(), ScoreMode.COMPLETE_NO_SCORES, 1.0f);
    LeafReaderContext leaf = searcher.getTopReaderContext().leaves().get(0);
    Scorer scorer = weight.scorer(leaf);
    NumericDocValues docValues = DocValues.getNumeric(leaf.reader(), "x");
    DocIdSetIterator docIt = scorer.iterator();
    LongObjectHashMap<Long> sumByKey = new LongObjectHashMap<>();
    for (int docId = docIt.nextDoc(); docId != DocIdSetIterator.NO_MORE_DOCS; docId = docIt.nextDoc()) {
        if (docValues.advanceExact(docId)) {
            long number = docValues.longValue();
            sumByKey.compute(number, (key, oldValue) -> {
                if (oldValue == null) {
                    return number;
                } else {
                    return oldValue + number;
                }
            });
        }
    }
    return sumByKey;
}
 
Example #3
Source File: BlockJoinParentQParser.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, org.apache.lucene.search.ScoreMode scoreMode, float boost) throws IOException {
  return new ConstantScoreWeight(BitSetProducerQuery.this, boost) {
    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      BitSet bitSet = bitSetProducer.getBitSet(context);
      if (bitSet == null) {
        return null;
      }
      DocIdSetIterator disi = new BitSetIterator(bitSet, bitSet.approximateCardinality());
      return new ConstantScoreScorer(this, boost, scoreMode, disi);
    }

    @Override
    public boolean isCacheable(LeafReaderContext ctx) {
      return getCache();
    }
  };
}
 
Example #4
Source File: GlobalOrdinalsQuery.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
  SortedDocValues values = DocValues.getSorted(context.reader(), joinField);
  if (values == null) {
    return null;
  }

  Scorer approximationScorer = approximationWeight.scorer(context);
  if (approximationScorer == null) {
    return null;
  }
  if (globalOrds != null) {
    return new OrdinalMapScorer(this, score(), foundOrds, values, approximationScorer.iterator(), globalOrds.getGlobalOrds(context.ord));
  } {
    return new SegmentOrdinalScorer(this, score(), foundOrds, values, approximationScorer.iterator());
  }
}
 
Example #5
Source File: ParentConstantScoreQuery.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
    DocIdSet childrenDocIdSet = childrenFilter.getDocIdSet(context, null);
    if (Lucene.isEmpty(childrenDocIdSet)) {
        return null;
    }

    SortedDocValues globalValues = globalIfd.load(context).getOrdinalsValues(parentType);
    if (globalValues != null) {
        // we forcefully apply live docs here so that deleted children don't give matching parents
        childrenDocIdSet = BitsFilteredDocIdSet.wrap(childrenDocIdSet, context.reader().getLiveDocs());
        DocIdSetIterator innerIterator = childrenDocIdSet.iterator();
        if (innerIterator != null) {
            ChildrenDocIdIterator childrenDocIdIterator = new ChildrenDocIdIterator(
                    innerIterator, parentOrds, globalValues
            );
            return ConstantScorer.create(childrenDocIdIterator, this, queryWeight);
        }
    }
    return null;
}
 
Example #6
Source File: LTRScoringQuery.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public float score() throws IOException {
  reset();
  freq = 0;
  if (targetDoc == activeDoc) {
    for (final Scorer scorer : featureScorers) {
      if (scorer.docID() == activeDoc) {
        freq++;
        Feature.FeatureWeight scFW = (Feature.FeatureWeight) scorer.getWeight();
        final int featureId = scFW.getIndex();
        featuresInfo[featureId].setValue(scorer.score());
        featuresInfo[featureId].setUsed(true);
      }
    }
  }
  return makeNormalizedFeaturesAndScore();
}
 
Example #7
Source File: ToParentBlockJoinQuery.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Matches matches(LeafReaderContext context, int doc) throws IOException {
  // The default implementation would delegate to the joinQuery's Weight, which
  // matches on children.  We need to match on the parent instead
  Scorer scorer = scorer(context);
  if (scorer == null) {
    return null;
  }
  final TwoPhaseIterator twoPhase = scorer.twoPhaseIterator();
  if (twoPhase == null) {
    if (scorer.iterator().advance(doc) != doc) {
      return null;
    }
  }
  else {
    if (twoPhase.approximation().advance(doc) != doc || twoPhase.matches() == false) {
      return null;
    }
  }
  return MatchesUtils.MATCH_WITH_NO_TERMS;
}
 
Example #8
Source File: IncludeNestedDocsQuery.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
IncludeNestedDocsScorer(Weight weight, Scorer parentScorer, BitSet parentBits, int currentParentPointer) {
    super(weight);
    this.parentScorer = parentScorer;
    this.parentBits = parentBits;
    this.currentParentPointer = currentParentPointer;
    if (currentParentPointer == 0) {
        currentChildPointer = 0;
    } else {
        this.currentChildPointer = this.parentBits.prevSetBit(currentParentPointer - 1);
        if (currentChildPointer == -1) {
            // no previous set parent, we delete from doc 0
            currentChildPointer = 0;
        } else {
            currentChildPointer++; // we only care about children
        }
    }

    currentDoc = currentChildPointer;
}
 
Example #9
Source File: ValueSourceRangeFilter.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings({"rawtypes"})
public DocIdSet getDocIdSet(final Map context, final LeafReaderContext readerContext, Bits acceptDocs) throws IOException {
  // NB the IndexSearcher parameter here can be null because Filter Weights don't
  // actually use it.
  Weight weight = createWeight(null, ScoreMode.COMPLETE, 1);
  return BitsFilteredDocIdSet.wrap(new DocIdSet() {
     @Override
     public DocIdSetIterator iterator() throws IOException {
       @SuppressWarnings({"unchecked"})
       Scorer scorer = valueSource.getValues(context, readerContext).getRangeScorer(weight, readerContext, lowerVal, upperVal, includeLower, includeUpper);
       return scorer == null ? null : scorer.iterator();
     }
     @Override
     public Bits bits() {
       return null;  // don't use random access
     }

     @Override
     public long ramBytesUsed() {
       return 0L;
     }
   }, acceptDocs);
}
 
Example #10
Source File: ShapeQuery.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/** Scorer used for WITHIN and DISJOINT **/
private Scorer getDenseScorer(LeafReader reader, Weight weight, final float boost, ScoreMode scoreMode) throws IOException {
  final FixedBitSet result = new FixedBitSet(reader.maxDoc());
  final long[] cost;
  if (values.getDocCount() == reader.maxDoc()) {
    cost = new long[]{values.size()};
    // In this case we can spare one visit to the tree, all documents
    // are potential matches
    result.set(0, reader.maxDoc());
    // Remove false positives
    values.intersect(getInverseDenseVisitor(query, result, cost));
  } else {
    cost = new long[]{0};
    // Get potential  documents.
    final FixedBitSet excluded = new FixedBitSet(reader.maxDoc());
    values.intersect(getDenseVisitor(query, result, excluded, cost));
    result.andNot(excluded);
    // Remove false positives, we only care about the inner nodes as intersecting
    // leaf nodes have been already taken into account. Unfortunately this
    // process still reads the leaf nodes.
    values.intersect(getShallowInverseDenseVisitor(query, result));
  }
  assert cost[0] > 0;
  final DocIdSetIterator iterator = new BitSetIterator(result, cost[0]);
  return new ConstantScoreScorer(weight, boost, scoreMode, iterator);
}
 
Example #11
Source File: TestLTRScoringQuery.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private LTRScoringQuery.ModelWeight performQuery(TopDocs hits,
    IndexSearcher searcher, int docid, LTRScoringQuery model) throws IOException,
    ModelException {
  final List<LeafReaderContext> leafContexts = searcher.getTopReaderContext()
      .leaves();
  final int n = ReaderUtil.subIndex(hits.scoreDocs[0].doc, leafContexts);
  final LeafReaderContext context = leafContexts.get(n);
  final int deBasedDoc = hits.scoreDocs[0].doc - context.docBase;

  final Weight weight = searcher.createWeight(searcher.rewrite(model), ScoreMode.COMPLETE, 1);
  final Scorer scorer = weight.scorer(context);

  // rerank using the field final-score
  scorer.iterator().advance(deBasedDoc);
  scorer.score();

  // assertEquals(42.0f, score, 0.0001);
  // assertTrue(weight instanceof AssertingWeight);
  // (AssertingIndexSearcher)
  assertTrue(weight instanceof LTRScoringQuery.ModelWeight);
  final LTRScoringQuery.ModelWeight modelWeight = (LTRScoringQuery.ModelWeight) weight;
  return modelWeight;

}
 
Example #12
Source File: MatchedQueriesFetchSubPhase.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private void addMatchedQueries(HitContext hitContext, ImmutableMap<String, Query> namedQueries, List<String> matchedQueries) throws IOException {
    for (Map.Entry<String, Query> entry : namedQueries.entrySet()) {
        String name = entry.getKey();
        Query filter = entry.getValue();

        final Weight weight = hitContext.topLevelSearcher().createNormalizedWeight(filter, false);
        final Scorer scorer = weight.scorer(hitContext.readerContext());
        if (scorer == null) {
            continue;
        }
        final TwoPhaseIterator twoPhase = scorer.twoPhaseIterator();
        if (twoPhase == null) {
            if (scorer.iterator().advance(hitContext.docId()) == hitContext.docId()) {
                matchedQueries.add(name);
            }
        } else {
            if (twoPhase.approximation().advance(hitContext.docId()) == hitContext.docId() && twoPhase.matches()) {
                matchedQueries.add(name);
            }
        }
    }
}
 
Example #13
Source File: SecureRealTimeGetComponent.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
/**
 * @param doc SolrDocument to check
 * @param idField field where the id is stored
 * @param fieldType type of id field
 * @param filterQuery Query to filter by
 * @param searcher SolrIndexSearcher on which to apply the filter query
 * @returns the internal docid, or -1 if doc is not found or doesn't match filter
 */
private static int getFilteredInternalDocId(SolrDocument doc, SchemaField idField, FieldType fieldType,
      Query filterQuery, SolrIndexSearcher searcher) throws IOException {
  int docid = -1;
  Field f = (Field)doc.getFieldValue(idField.getName());
  String idStr = f.stringValue();
  BytesRef idBytes = new BytesRef();
  fieldType.readableToIndexed(idStr, idBytes);
  // get the internal document id
  long segAndId = searcher.lookupId(idBytes);

    // if docid is valid, run it through the filter
  if (segAndId >= 0) {
    int segid = (int) segAndId;
    AtomicReaderContext ctx = searcher.getTopReaderContext().leaves().get((int) (segAndId >> 32));
    docid = segid + ctx.docBase;
    Weight weight = filterQuery.createWeight(searcher);
    Scorer scorer = weight.scorer(ctx, null);
    if (scorer == null || segid != scorer.advance(segid)) {
      // filter doesn't match.
      docid = -1;
    }
  }
  return docid;
}
 
Example #14
Source File: IncludeNestedDocsQuery.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
    final Scorer parentScorer = parentWeight.scorer(context);

    // no matches
    if (parentScorer == null) {
        return null;
    }

    BitSet parents = parentsFilter.getBitSet(context);
    if (parents == null) {
        // No matches
        return null;
    }

    int firstParentDoc = parentScorer.iterator().nextDoc();
    if (firstParentDoc == DocIdSetIterator.NO_MORE_DOCS) {
        // No matches
        return null;
    }
    return new IncludeNestedDocsScorer(this, parentScorer, parents, firstParentDoc);
}
 
Example #15
Source File: SerializedDVStrategy.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
  return new ConstantScoreWeight(this, boost) {
    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      DocIdSetIterator approximation = DocIdSetIterator.all(context.reader().maxDoc());
      TwoPhaseIterator it = predicateValueSource.iterator(context, approximation);
      return new ConstantScoreScorer(this, score(), scoreMode, it);
    }

    @Override
    public boolean isCacheable(LeafReaderContext ctx) {
      return predicateValueSource.isCacheable(ctx);
    }

  };
}
 
Example #16
Source File: DerivedExpressionQuery.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
    Bindings bindings = new Bindings(){
        @Override
        public DoubleValuesSource getDoubleValuesSource(String name) {
            Double queryParamValue  = queryParamValues.get(name);
            if (queryParamValue != null) {
                return DoubleValuesSource.constant(queryParamValue);
            }
            return new FVDoubleValuesSource(vectorSupplier, features.featureOrdinal(name));
        }
    };

    DocIdSetIterator iterator = DocIdSetIterator.all(context.reader().maxDoc());
    DoubleValuesSource src = expression.getDoubleValuesSource(bindings);
    DoubleValues values = src.getValues(context, null);

    return new DValScorer(this, iterator, values);
}
 
Example #17
Source File: FunctionScoreQuery.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
  Scorer in = inner.scorer(context);
  if (in == null)
    return null;
  DoubleValues scores = valueSource.getValues(context, DoubleValuesSource.fromScorer(in));
  return new FilterScorer(in) {
    @Override
    public float score() throws IOException {
      if (scores.advanceExact(docID())) {
        double factor = scores.doubleValue();
        if (factor >= 0) {
          return (float) (factor * boost);
        }
      }
      // default: missing value, negative value or NaN
      return 0;
    }
    @Override
    public float getMaxScore(int upTo) throws IOException {
      return Float.POSITIVE_INFINITY;
    }
  };
}
 
Example #18
Source File: FiltersFunctionScoreQuery.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private FiltersFunctionFactorScorer functionScorer(LeafReaderContext context) throws IOException {
    Scorer subQueryScorer = subQueryWeight.scorer(context);
    if (subQueryScorer == null) {
        return null;
    }
    final LeafScoreFunction[] functions = new LeafScoreFunction[filterFunctions.length];
    final Bits[] docSets = new Bits[filterFunctions.length];
    for (int i = 0; i < filterFunctions.length; i++) {
        FilterFunction filterFunction = filterFunctions[i];
        functions[i] = filterFunction.function.getLeafScoreFunction(context);
        Scorer filterScorer = filterWeights[i].scorer(context);
        docSets[i] = Lucene.asSequentialAccessBits(context.reader().maxDoc(), filterScorer);
    }
    return new FiltersFunctionFactorScorer(this, subQueryScorer, scoreMode, filterFunctions, maxBoost, functions, docSets, combineFunction, needsScores);
}
 
Example #19
Source File: ScriptFeature.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
    LeafScoreFunction leafScoreFunction = function.getLeafScoreFunction(context);
    DocIdSetIterator iterator = DocIdSetIterator.all(context.reader().maxDoc());
    return new Scorer(this) {
        @Override
        public int docID() {
            return iterator.docID();
        }

        @Override
        public float score() throws IOException {
            return (float) leafScoreFunction.score(iterator.docID(), 0F);
        }

        @Override
        public DocIdSetIterator iterator() {
            return iterator;
        }

        /**
         * Return the maximum score that documents between the last {@code target}
         * that this iterator was {@link #advanceShallow(int) shallow-advanced} to
         * included and {@code upTo} included.
         */
        @Override
        public float getMaxScore(int upTo) throws IOException {
            //TODO??
            return Float.POSITIVE_INFINITY;
        }
    };
}
 
Example #20
Source File: FunctionScoreQuery.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private FunctionFactorScorer functionScorer(LeafReaderContext context) throws IOException {
    Scorer subQueryScorer = subQueryWeight.scorer(context);
    if (subQueryScorer == null) {
        return null;
    }
    LeafScoreFunction leafFunction = null;
    if (function != null) {
        leafFunction = function.getLeafScoreFunction(context);
    }
    return new FunctionFactorScorer(this, subQueryScorer, leafFunction, maxBoost, combineFunction, needsScores);
}
 
Example #21
Source File: FiltersFunctionScoreQuery.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private FiltersFunctionFactorScorer(CustomBoostFactorWeight w, Scorer scorer, ScoreMode scoreMode, FilterFunction[] filterFunctions,
                                    float maxBoost, LeafScoreFunction[] functions, Bits[] docSets, CombineFunction scoreCombiner, boolean needsScores) throws IOException {
    super(scorer, w);
    this.scoreMode = scoreMode;
    this.filterFunctions = filterFunctions;
    this.functions = functions;
    this.docSets = docSets;
    this.scoreCombiner = scoreCombiner;
    this.maxBoost = maxBoost;
    this.needsScores = needsScores;
}
 
Example #22
Source File: PostingsExplorerQuery.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
@Override
public Explanation explain(LeafReaderContext context, int doc) throws IOException {
    Scorer scorer = this.scorer(context);
    int newDoc = scorer.iterator().advance(doc);
    if (newDoc == doc) {
        return Explanation
                .match(scorer.score(), "weight(" + this.getQuery() + " in doc " + newDoc + ")");
    }
    return Explanation.noMatch("no matching term");
}
 
Example #23
Source File: DocValuesAggregates.java    From crate with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private static Iterable<Row> getRow(AtomicReference<Throwable> killed,
                                    Searcher searcher,
                                    Query query,
                                    List<DocValueAggregator> aggregators) throws IOException {
    IndexSearcher indexSearcher = searcher.searcher();
    Weight weight = indexSearcher.createWeight(indexSearcher.rewrite(query), ScoreMode.COMPLETE_NO_SCORES, 1f);
    List<LeafReaderContext> leaves = indexSearcher.getTopReaderContext().leaves();
    Object[] cells = new Object[aggregators.size()];
    for (int i = 0; i < aggregators.size(); i++) {
        cells[i] = aggregators.get(i).initialState();
    }
    for (var leaf : leaves) {
        Scorer scorer = weight.scorer(leaf);
        if (scorer == null) {
            continue;
        }
        for (int i = 0; i < aggregators.size(); i++) {
            aggregators.get(i).loadDocValues(leaf.reader());
        }
        DocIdSetIterator docs = scorer.iterator();
        Bits liveDocs = leaf.reader().getLiveDocs();
        for (int doc = docs.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = docs.nextDoc()) {
            if (liveDocs != null && !liveDocs.get(doc)) {
                continue;
            }
            Throwable killCause = killed.get();
            if (killCause != null) {
                Exceptions.rethrowUnchecked(killCause);
            }
            for (int i = 0; i < aggregators.size(); i++) {
                aggregators.get(i).apply(cells[i], doc);
            }
        }
    }
    for (int i = 0; i < aggregators.size(); i++) {
        cells[i] = aggregators.get(i).partialResult(cells[i]);
    }
    return List.of(new RowN(cells));
}
 
Example #24
Source File: GraphQuery.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
  if (filter == null) {
    resultSet = getDocSet();
    filter = resultSet.getTopFilter();
  }
  DocIdSet readerSet = filter.getDocIdSet(context,context.reader().getLiveDocs());
  // create a scrorer on the result set, if results from right query are empty, use empty iterator.
  return new GraphScorer(this, readerSet == null ? DocIdSetIterator.empty() : readerSet.iterator(), 1);
}
 
Example #25
Source File: FunctionMatchQuery.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
  DoubleValuesSource vs = source.rewrite(searcher);
  return new ConstantScoreWeight(this, boost) {
    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      DoubleValues values = vs.getValues(context, null);
      DocIdSetIterator approximation = DocIdSetIterator.all(context.reader().maxDoc());
      TwoPhaseIterator twoPhase = new TwoPhaseIterator(approximation) {
        @Override
        public boolean matches() throws IOException {
          return values.advanceExact(approximation.docID()) && filter.test(values.doubleValue());
        }

        @Override
        public float matchCost() {
          return 100; // TODO maybe DoubleValuesSource should have a matchCost?
        }
      };
      return new ConstantScoreScorer(this, score(), scoreMode, twoPhase);
    }

    @Override
    public boolean isCacheable(LeafReaderContext ctx) {
      return source.isCacheable(ctx);
    }

  };
}
 
Example #26
Source File: SolrRangeQuery.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private Scorer scorer(DocIdSet set) throws IOException {
  if (set == null) {
    return null;
  }
  final DocIdSetIterator disi = set.iterator();
  if (disi == null) {
    return null;
  }
  return new ConstantScoreScorer(this, score(), scoreMode, disi);
}
 
Example #27
Source File: DrillSidewaysScorer.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
DocsAndCost(Scorer scorer, Collector sidewaysCollector) {
  final TwoPhaseIterator twoPhase = scorer.twoPhaseIterator();
  if (twoPhase == null) {
    this.approximation = scorer.iterator();
    this.twoPhase = null;
  } else {
    this.approximation = twoPhase.approximation();
    this.twoPhase = twoPhase;
  }
  this.sidewaysCollector = sidewaysCollector;
}
 
Example #28
Source File: ChildrenConstantScoreQuery.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
    if (remaining == 0) {
        return null;
    }

    if (shortCircuitFilter != null) {
        DocIdSet docIdSet = shortCircuitFilter.getDocIdSet(context, null);
        if (!Lucene.isEmpty(docIdSet)) {
            DocIdSetIterator iterator = docIdSet.iterator();
            if (iterator != null) {
                return ConstantScorer.create(iterator, this, queryWeight);
            }
        }
        return null;
    }

    DocIdSet parentDocIdSet = this.parentFilter.getDocIdSet(context, null);
    if (!Lucene.isEmpty(parentDocIdSet)) {
        // We can't be sure of the fact that liveDocs have been applied, so we apply it here. The "remaining"
        // count down (short circuit) logic will then work as expected.
        parentDocIdSet = BitsFilteredDocIdSet.wrap(parentDocIdSet, context.reader().getLiveDocs());
        DocIdSetIterator innerIterator = parentDocIdSet.iterator();
        if (innerIterator != null) {
            LongBitSet parentOrds = collector.parentOrds;
            SortedDocValues globalValues = globalIfd.load(context).getOrdinalsValues(parentType);
            if (globalValues != null) {
                DocIdSetIterator parentIdIterator = new ParentOrdIterator(innerIterator, parentOrds, globalValues, this);
                return ConstantScorer.create(parentIdIterator, this, queryWeight);
            }
        }
    }
    return null;
}
 
Example #29
Source File: ChildrenQuery.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
    DocIdSet parentsSet = parentFilter.getDocIdSet(context, null);
    if (Lucene.isEmpty(parentsSet) || remaining == 0) {
        return null;
    }

    // We can't be sure of the fact that liveDocs have been applied, so we apply it here. The "remaining"
    // count down (short circuit) logic will then work as expected.
    DocIdSetIterator parents = BitsFilteredDocIdSet.wrap(parentsSet, context.reader().getLiveDocs()).iterator();

    if (parents != null) {
        SortedDocValues bytesValues = collector.globalIfd.load(context).getOrdinalsValues(parentType);
        if (bytesValues == null) {
            return null;
        }

        if (minChildren > 0 || maxChildren != 0 || scoreType == ScoreType.NONE) {
            switch (scoreType) {
            case NONE:
                DocIdSetIterator parentIdIterator = new CountParentOrdIterator(this, parents, collector, bytesValues,
                        minChildren, maxChildren);
                return ConstantScorer.create(parentIdIterator, this, queryWeight);
            case AVG:
                return new AvgParentCountScorer(this, parents, collector, bytesValues, minChildren, maxChildren);
            default:
                return new ParentCountScorer(this, parents, collector, bytesValues, minChildren, maxChildren);
            }
        }
        switch (scoreType) {
        case AVG:
            return new AvgParentScorer(this, parents, collector, bytesValues);
        default:
            return new ParentScorer(this, parents, collector, bytesValues);
        }
    }
    return null;
}
 
Example #30
Source File: GraphTermsQParserPlugin.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public final Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
  return new ConstantScoreWeight(this, boost) {
    Filter filter;

    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      if (filter == null) {
        DocSet set = getDocSet(searcher);
        filter = set.getTopFilter();
      }

      // Although this set only includes live docs, other filters can be pushed down to queries.
      DocIdSet readerSet = filter.getDocIdSet(context, null);
      if (readerSet == null) {
        return null;
      }
      DocIdSetIterator readerSetIterator = readerSet.iterator();
      if (readerSetIterator == null) {
        return null;
      }
      return new ConstantScoreScorer(this, score(), scoreMode, readerSetIterator);
    }

    @Override
    public boolean isCacheable(LeafReaderContext ctx) {
      return true;
    }
  };
}