org.apache.lucene.search.ConstantScoreScorer Java Examples

The following examples show how to use org.apache.lucene.search.ConstantScoreScorer. 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: ArrayLengthQuery.java    From crate 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 boolean isCacheable(LeafReaderContext ctx) {
            return false;
        }

        @Override
        public Scorer scorer(LeafReaderContext context) {
            return new ConstantScoreScorer(
                this,
                0f,
                scoreMode,
                new NumTermsPerDocTwoPhaseIterator(context.reader(), numTermsPerDocFactory.apply(context), matches));
        }
    };
}
 
Example #2
Source File: AbstractPrefixTreeQuery.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 {
      DocIdSet docSet = getDocIdSet(context);
      if (docSet == null) {
        return null;
      }
      DocIdSetIterator disi = docSet.iterator();
      if (disi == null) {
        return null;
      }
      return new ConstantScoreScorer(this, score(), scoreMode, disi);
    }

    @Override
    public boolean isCacheable(LeafReaderContext ctx) {
      return true;
    }
  };
}
 
Example #3
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 #4
Source File: CompositeVerifyQuery.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 {
  final Weight indexQueryWeight = indexQuery.createWeight(searcher, ScoreMode.COMPLETE_NO_SCORES, boost);//scores aren't unsupported

  return new ConstantScoreWeight(this, boost) {

    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {

      final Scorer indexQueryScorer = indexQueryWeight.scorer(context);
      if (indexQueryScorer == null) {
        return null;
      }

      final TwoPhaseIterator predFuncValues = predicateValueSource.iterator(context, indexQueryScorer.iterator());
      return new ConstantScoreScorer(this, score(), scoreMode, predFuncValues);
    }

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

  };
}
 
Example #5
Source File: DerivedExpressionQuery.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
    if (!scoreMode.needsScores()) {
        // If scores are not needed simply return a constant score on all docs
        return new ConstantScoreWeight(this.query, boost) {
            @Override
            public boolean isCacheable(LeafReaderContext ctx) {
                return true;
            }

            @Override
            public Scorer scorer(LeafReaderContext context) throws IOException {
                return new ConstantScoreScorer(this, score(),
                    scoreMode, DocIdSetIterator.all(context.reader().maxDoc()));
            }
        };
    }

    return new FVWeight(this);
}
 
Example #6
Source File: CrossCollectionJoinQuery.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
  if (filter == null) {
    filter = getDocSet().getTopFilter();
  }

  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);
}
 
Example #7
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 #8
Source File: SolrConstantScoreQuery.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
  DocIdSet docIdSet = filter instanceof SolrFilter ? ((SolrFilter)filter).getDocIdSet(this.context, context, null) : filter.getDocIdSet(context, null);
  if (docIdSet == null) {
    return null;
  }
  DocIdSetIterator iterator = docIdSet.iterator();
  if (iterator == null) {
    return null;
  }
  return new ConstantScoreScorer(this, score(), scoreMode, iterator);
}
 
Example #9
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;
    }
  };
}
 
Example #10
Source File: SolrIndexSplitter.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 {
  return new ConstantScoreWeight(this, boost) {

    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      RTimerTree t = timings.sub("findDocsToDelete");
      t.resume();
      FixedBitSet set = findDocsToDelete(context);
      t.pause();
      if (log.isInfoEnabled()) {
        log.info("### partition={}, leaf={}, maxDoc={}, numDels={}, setLen={}, setCard={}"
        , partition, context, context.reader().maxDoc()
        ,context.reader().numDeletedDocs(), set.length(), set.cardinality());
      }
      Bits liveDocs = context.reader().getLiveDocs();
      if (liveDocs != null) {
        // check that we don't delete already deleted docs
        FixedBitSet dels = FixedBitSet.copyOf(liveDocs);
        dels.flip(0, dels.length());
        dels.and(set);
        if (dels.cardinality() > 0) {
          log.error("### INVALID DELS {}", dels.cardinality());
        }
      }
      return new ConstantScoreScorer(this, score(), scoreMode, new BitSetIterator(set, set.length()));
    }

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

    @Override
    public String toString() {
      return "weight(shardSplittingQuery,part" + partition + ")";
    }
  };
}
 
Example #11
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 #12
Source File: ShapeQuery.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private Scorer getContainsDenseScorer(LeafReader reader, Weight weight, final float boost, ScoreMode scoreMode) throws IOException {
  final FixedBitSet result = new FixedBitSet(reader.maxDoc());
  final long[] cost = new long[]{0};
  // Get potential  documents.
  final FixedBitSet excluded = new FixedBitSet(reader.maxDoc());
  values.intersect(getContainsDenseVisitor(query, result, excluded, cost));
  result.andNot(excluded);
  final DocIdSetIterator iterator = new BitSetIterator(result, cost[0]);
  return new ConstantScoreScorer(weight, boost, scoreMode, iterator);
}
 
Example #13
Source File: TestFieldCacheSortRandom.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 {
  return new ConstantScoreWeight(this, boost) {
    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      Random random = new Random(seed ^ context.docBase);
      final int maxDoc = context.reader().maxDoc();
      final NumericDocValues idSource = DocValues.getNumeric(context.reader(), "id");
      assertNotNull(idSource);
      final FixedBitSet bits = new FixedBitSet(maxDoc);
      for(int docID=0;docID<maxDoc;docID++) {
        if (random.nextFloat() <= density) {
          bits.set(docID);
          //System.out.println("  acc id=" + idSource.getInt(docID) + " docID=" + docID);
          assertEquals(docID, idSource.advance(docID));
          matchValues.add(docValues.get((int) idSource.longValue()));
        }
      }

      return new ConstantScoreScorer(this, score(), scoreMode, new BitSetIterator(bits, bits.approximateCardinality()));
    }

    @Override
    public boolean isCacheable(LeafReaderContext ctx) {
      return true;
    }
  };
}
 
Example #14
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 #15
Source File: PointVectorStrategy.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 {
  Weight w = inner.createWeight(searcher, scoreMode, 1f);
  return new ConstantScoreWeight(this, boost) {
    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      Scorer in = w.scorer(context);
      if (in == null)
        return null;
      DoubleValues v = distanceSource.getValues(context, DoubleValuesSource.fromScorer(in));
      DocIdSetIterator approximation = in.iterator();
      TwoPhaseIterator twoPhase = new TwoPhaseIterator(approximation) {
        @Override
        public boolean matches() throws IOException {
          return v.advanceExact(approximation.docID()) && v.doubleValue() <= limit;
        }

        @Override
        public float matchCost() {
          return 100;   // distance calculation can be heavy!
        }
      };
      return new ConstantScoreScorer(this, score(), scoreMode, twoPhase);
    }

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

  };
}
 
Example #16
Source File: JoinQuery.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
  if (filter == null) {
    boolean debug = rb != null && rb.isDebug();
    RTimer timer = (debug ? new RTimer() : null);
    resultSet = getDocSet();
    if (timer != null) timer.stop();

    if (debug) {
      SimpleOrderedMap<Object> dbg = new SimpleOrderedMap<>();
      dbg.add("time", (long) timer.getTime());
      dbg.add("fromSetSize", fromSetSize);  // the input
      dbg.add("toSetSize", resultSet.size());    // the output

      dbg.add("fromTermCount", fromTermCount);
      dbg.add("fromTermTotalDf", fromTermTotalDf);
      dbg.add("fromTermDirectCount", fromTermDirectCount);
      dbg.add("fromTermHits", fromTermHits);
      dbg.add("fromTermHitsTotalDf", fromTermHitsTotalDf);
      dbg.add("toTermHits", toTermHits);
      dbg.add("toTermHitsTotalDf", toTermHitsTotalDf);
      dbg.add("toTermDirectCount", toTermDirectCount);
      dbg.add("smallSetsDeferred", smallSetsDeferred);
      dbg.add("toSetDocsAdded", resultListDocs);

      // TODO: perhaps synchronize  addDebug in the future...
      rb.addDebug(dbg, "join", JoinQuery.this.toString());
    }

    filter = resultSet.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);
}
 
Example #17
Source File: TopLevelJoinQuery.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
  if (! (searcher instanceof SolrIndexSearcher)) {
    log.debug("Falling back to JoinQueryWeight because searcher [{}] is not the required SolrIndexSearcher", searcher);
    return super.createWeight(searcher, scoreMode, boost);
  }

  final SolrIndexSearcher solrSearcher = (SolrIndexSearcher) searcher;
  final JoinQueryWeight weight = new JoinQueryWeight(solrSearcher, ScoreMode.COMPLETE_NO_SCORES, 1.0f);
  final SolrIndexSearcher fromSearcher = weight.fromSearcher;
  final SolrIndexSearcher toSearcher = weight.toSearcher;

  try {
    final SortedSetDocValues topLevelFromDocValues = validateAndFetchDocValues(fromSearcher, fromField, "from");
    final SortedSetDocValues topLevelToDocValues = validateAndFetchDocValues(toSearcher, toField, "to");
    if (topLevelFromDocValues.getValueCount() == 0 || topLevelToDocValues.getValueCount() == 0) {
      return createNoMatchesWeight(boost);
    }

    final LongBitSet fromOrdBitSet = findFieldOrdinalsMatchingQuery(q, fromField, fromSearcher, topLevelFromDocValues);
    final LongBitSet toOrdBitSet = new LongBitSet(topLevelToDocValues.getValueCount());
    final BitsetBounds toBitsetBounds = convertFromOrdinalsIntoToField(fromOrdBitSet, topLevelFromDocValues, toOrdBitSet, topLevelToDocValues);

    final boolean toMultivalued = toSearcher.getSchema().getFieldOrNull(toField).multiValued();
    return new ConstantScoreWeight(this, boost) {
      public Scorer scorer(LeafReaderContext context) throws IOException {
        if (toBitsetBounds.lower == BitsetBounds.NO_MATCHES) {
          return null;
        }

        final DocIdSetIterator toApproximation = (toMultivalued) ? context.reader().getSortedSetDocValues(toField) :
            context.reader().getSortedDocValues(toField);
        if (toApproximation == null) {
          return null;
        }

        final int docBase = context.docBase;
        return new ConstantScoreScorer(this, this.score(), scoreMode, new TwoPhaseIterator(toApproximation) {
          public boolean matches() throws IOException {
            final boolean hasDoc = topLevelToDocValues.advanceExact(docBase + approximation.docID());
            if (hasDoc) {
              for (long ord = topLevelToDocValues.nextOrd(); ord != -1L; ord = topLevelToDocValues.nextOrd()) {
                if (toOrdBitSet.get(ord)) {
                  return true;
                }
              }
            }
            return false;
          }

          public float matchCost() {
            return 10.0F;
          }
        });

      }

      public boolean isCacheable(LeafReaderContext ctx) {
        return false;
      }
    };
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #18
Source File: XYDocValuesPointInGeometryQuery.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {

  return new ConstantScoreWeight(this, boost) {

    final Component2D component2D = XYGeometry.create(geometries);

    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      final SortedNumericDocValues values = context.reader().getSortedNumericDocValues(field);
      if (values == null) {
        return null;
      }

      final TwoPhaseIterator iterator = new TwoPhaseIterator(values) {

        @Override
        public boolean matches() throws IOException {
          for (int i = 0, count = values.docValueCount(); i < count; ++i) {
            final long value = values.nextValue();
            final double x = XYEncodingUtils.decode((int) (value >>> 32));
            final double y = XYEncodingUtils.decode((int) (value & 0xFFFFFFFF));
            if (component2D.contains(x, y)) {
              return true;
            }
          }
          return false;
        }

        @Override
        public float matchCost() {
          return 1000f; // TODO: what should it be?
        }
      };
      return new ConstantScoreScorer(this, boost, scoreMode, iterator);
    }

    @Override
    public boolean isCacheable(LeafReaderContext ctx) {
      return DocValues.isCacheable(ctx, field);
    }
  };
}
 
Example #19
Source File: LatLonDocValuesBoxQuery.java    From lucene-solr with Apache License 2.0 4 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 {
      final SortedNumericDocValues values = context.reader().getSortedNumericDocValues(field);
      if (values == null) {
        return null;
      }

      final TwoPhaseIterator iterator = new TwoPhaseIterator(values) {
        @Override
        public boolean matches() throws IOException {
          for (int i = 0, count = values.docValueCount(); i < count; ++i) {
            final long value = values.nextValue();
            final int lat = (int) (value >>> 32);
            if (lat < minLatitude || lat > maxLatitude) {
              // not within latitude range
              continue;
            }

            final int lon = (int) (value & 0xFFFFFFFF);
            if (crossesDateline) {
              if (lon > maxLongitude && lon < minLongitude) {
                // not within longitude range
                continue;
              }
            } else {
              if (lon < minLongitude || lon > maxLongitude) {
                // not within longitude range
                continue;
              }
            }

            return true;
          }
          return false;
        }

        @Override
        public float matchCost() {
          return 5; // 5 comparisons
        }
      };
      return new ConstantScoreScorer(this, boost, scoreMode, iterator);
    }

    @Override
    public boolean isCacheable(LeafReaderContext ctx) {
      return DocValues.isCacheable(ctx, field);
    }

  };
}
 
Example #20
Source File: GeoDistanceRangeQuery.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, boolean needsScores) throws IOException {
    final Weight boundingBoxWeight;
    if (boundingBoxFilter != null) {
        boundingBoxWeight = searcher.createNormalizedWeight(boundingBoxFilter, false);
    } else {
        boundingBoxWeight = null;
    }
    return new ConstantScoreWeight(this) {
        @Override
        public Scorer scorer(LeafReaderContext context) throws IOException {
            final DocIdSetIterator approximation;
            if (boundingBoxWeight != null) {
                Scorer s = boundingBoxWeight.scorer(context);
                if (s == null) {
                    // if the approximation does not match anything, we're done
                    return null;
                }
                approximation = s.iterator();
            } else {
                approximation = DocIdSetIterator.all(context.reader().maxDoc());
            }
            final MultiGeoPointValues values = indexFieldData.load(context).getGeoPointValues();
            final TwoPhaseIterator twoPhaseIterator = new TwoPhaseIterator(approximation) {
                @Override
                public boolean matches() throws IOException {
                    final int doc = approximation.docID();
                    values.setDocument(doc);
                    final int length = values.count();
                    for (int i = 0; i < length; i++) {
                        GeoPoint point = values.valueAt(i);
                        if (distanceBoundingCheck.isWithin(point.lat(), point.lon())) {
                            double d = fixedSourceDistance.calculate(point.lat(), point.lon());
                            if (d >= inclusiveLowerPoint && d <= inclusiveUpperPoint) {
                                return true;
                            }
                        }
                    }
                    return false;
                }

                @Override
                public float matchCost() {
                    if (distanceBoundingCheck == GeoDistance.ALWAYS_INSTANCE) {
                        return 0.0f;
                    } else {
                        // TODO: is this right (up to 4 comparisons from GeoDistance.SimpleDistanceBoundingCheck)?
                        return 4.0f;
                    }
                }
            };
            return new ConstantScoreScorer(this, score(), twoPhaseIterator);
        }
    };
}
 
Example #21
Source File: LatLonDocValuesDistanceQuery.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
  return new ConstantScoreWeight(this, boost) {

    private final GeoEncodingUtils.DistancePredicate distancePredicate = GeoEncodingUtils.createDistancePredicate(latitude, longitude, radiusMeters);

    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      final SortedNumericDocValues values = context.reader().getSortedNumericDocValues(field);
      if (values == null) {
        return null;
      }

      final TwoPhaseIterator iterator = new TwoPhaseIterator(values) {

        @Override
        public boolean matches() throws IOException {
          for (int i = 0, count = values.docValueCount(); i < count; ++i) {
            final long value = values.nextValue();
            final int lat = (int) (value >>> 32);
            final int lon = (int) (value & 0xFFFFFFFF);
            if (distancePredicate.test(lat, lon)) {
              return true;
            }
          }
          return false;
        }

        @Override
        public float matchCost() {
          return 100f; // TODO: what should it be?
        }

      };
      return new ConstantScoreScorer(this, boost, scoreMode, iterator);
    }

    @Override
    public boolean isCacheable(LeafReaderContext ctx) {
      return DocValues.isCacheable(ctx, field);
    }

  };
}
 
Example #22
Source File: LatLonDocValuesPointInPolygonQuery.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {

  return new ConstantScoreWeight(this, boost) {

    final Component2D tree = LatLonGeometry.create(polygons);
    final GeoEncodingUtils.PolygonPredicate polygonPredicate = GeoEncodingUtils.createComponentPredicate(tree);

    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      final SortedNumericDocValues values = context.reader().getSortedNumericDocValues(field);
      if (values == null) {
        return null;
      }

      final TwoPhaseIterator iterator = new TwoPhaseIterator(values) {

        @Override
        public boolean matches() throws IOException {
          for (int i = 0, count = values.docValueCount(); i < count; ++i) {
            final long value = values.nextValue();
            final int lat = (int) (value >>> 32);
            final int lon = (int) (value & 0xFFFFFFFF);
            if (polygonPredicate.test(lat, lon)) {
              return true;
            }
          }
          return false;
        }

        @Override
        public float matchCost() {
          return 1000f; // TODO: what should it be?
        }
      };
      return new ConstantScoreScorer(this, boost, scoreMode, iterator);
    }

    @Override
    public boolean isCacheable(LeafReaderContext ctx) {
      return DocValues.isCacheable(ctx, field);
    }

  };
}
 
Example #23
Source File: DoubleRange.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
  final Weight fastMatchWeight = fastMatchQuery == null
      ? null
      : searcher.createWeight(fastMatchQuery, ScoreMode.COMPLETE_NO_SCORES, 1f);

  return new ConstantScoreWeight(this, boost) {
    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      final int maxDoc = context.reader().maxDoc();

      final DocIdSetIterator approximation;
      if (fastMatchWeight == null) {
        approximation = DocIdSetIterator.all(maxDoc);
      } else {
        Scorer s = fastMatchWeight.scorer(context);
        if (s == null) {
          return null;
        }
        approximation = s.iterator();
      }

      final DoubleValues values = valueSource.getValues(context, null);
      final TwoPhaseIterator twoPhase = new TwoPhaseIterator(approximation) {
        @Override
        public boolean matches() throws IOException {
          return values.advanceExact(approximation.docID()) && range.accept(values.doubleValue());
        }

        @Override
        public float matchCost() {
          return 100; // TODO: use cost of range.accept()
        }
      };
      return new ConstantScoreScorer(this, score(), scoreMode, twoPhase);
    }

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

  };
}
 
Example #24
Source File: LongRange.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
  final Weight fastMatchWeight = fastMatchQuery == null
      ? null
      : searcher.createWeight(fastMatchQuery, ScoreMode.COMPLETE_NO_SCORES, 1f);

  return new ConstantScoreWeight(this, boost) {
    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      final int maxDoc = context.reader().maxDoc();

      final DocIdSetIterator approximation;
      if (fastMatchWeight == null) {
        approximation = DocIdSetIterator.all(maxDoc);
      } else {
        Scorer s = fastMatchWeight.scorer(context);
        if (s == null) {
          return null;
        }
        approximation = s.iterator();
      }

      final LongValues values = valueSource.getValues(context, null);
      final TwoPhaseIterator twoPhase = new TwoPhaseIterator(approximation) {
        @Override
        public boolean matches() throws IOException {
          return values.advanceExact(approximation.docID()) && range.accept(values.longValue());
        }

        @Override
        public float matchCost() {
          return 100; // TODO: use cost of range.accept()
        }
      };
      return new ConstantScoreScorer(this, score(), scoreMode, twoPhase);
    }

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

  };
}
 
Example #25
Source File: PointInGeo3DShapeQuery.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {

  // I don't use RandomAccessWeight here: it's no good to approximate with "match all docs"; this is an inverted structure and should be
  // used in the first pass:

  return new ConstantScoreWeight(this, boost) {

    @Override
    public Scorer scorer(LeafReaderContext context) throws IOException {
      LeafReader reader = context.reader();
      PointValues values = reader.getPointValues(field);
      if (values == null) {
        return null;
      }

      /*
      XYZBounds bounds = new XYZBounds();
      shape.getBounds(bounds);

      final double planetMax = planetModel.getMaximumMagnitude();
      if (planetMax != treeDV.planetMax) {
        throw new IllegalStateException(planetModel + " is not the same one used during indexing: planetMax=" + planetMax + " vs indexing planetMax=" + treeDV.planetMax);
      }
      */

      /*
      GeoArea xyzSolid = GeoAreaFactory.makeGeoArea(planetModel,
                                                    bounds.getMinimumX(),
                                                    bounds.getMaximumX(),
                                                    bounds.getMinimumY(),
                                                    bounds.getMaximumY(),
                                                    bounds.getMinimumZ(),
                                                    bounds.getMaximumZ());

      assert xyzSolid.getRelationship(shape) == GeoArea.WITHIN || xyzSolid.getRelationship(shape) == GeoArea.OVERLAPS: "expected WITHIN (1) or OVERLAPS (2) but got " + xyzSolid.getRelationship(shape) + "; shape="+shape+"; XYZSolid="+xyzSolid;
      */

      DocIdSetBuilder result = new DocIdSetBuilder(reader.maxDoc(), values, field);

      values.intersect(new PointInShapeIntersectVisitor(result, shape, shapeBounds));

      return new ConstantScoreScorer(this, score(), scoreMode, result.build().iterator());
    }

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

  };
}