org.apache.lucene.search.ConstantScoreWeight#org.apache.lucene.search.DoubleValuesSource源码实例Demo

下面列出了org.apache.lucene.search.ConstantScoreWeight#org.apache.lucene.search.DoubleValuesSource 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: lucene-solr   文件: TestDemoExpressions.java
/** tests expression referring to another expression */
public void testExpressionRefersToExpression() throws Exception {
  Expression expr1 = JavascriptCompiler.compile("_score");
  Expression expr2 = JavascriptCompiler.compile("2*expr1");
  
  SimpleBindings bindings = new SimpleBindings();
  bindings.add("_score", DoubleValuesSource.SCORES);
  bindings.add("expr1", expr1);
  
  Sort sort = new Sort(expr2.getSortField(bindings, true));
  Query query = new TermQuery(new Term("body", "contents"));
  TopFieldDocs td = searcher.search(query, 3, sort, true);
  for (int i = 0; i < 3; i++) {
    FieldDoc d = (FieldDoc) td.scoreDocs[i];
    float expected = 2*d.score;
    float actual = ((Double)d.fields[0]).floatValue();
    assertEquals(expected, actual, 0d);
  }
}
 
源代码2 项目: lucene-solr   文件: TestDemoExpressions.java
/** tests same binding used more than once in an expression */
public void testTwoOfSameBinding() throws Exception {
  Expression expr = JavascriptCompiler.compile("_score + _score");
  
  SimpleBindings bindings = new SimpleBindings();
  bindings.add("_score", DoubleValuesSource.SCORES);
  
  Sort sort = new Sort(expr.getSortField(bindings, true));
  Query query = new TermQuery(new Term("body", "contents"));
  TopFieldDocs td = searcher.search(query, 3, sort, true);
  for (int i = 0; i < 3; i++) {
    FieldDoc d = (FieldDoc) td.scoreDocs[i];
    float expected = 2*d.score;
    float actual = ((Double)d.fields[0]).floatValue();
    assertEquals(expected, actual, 0d);
  }
}
 
源代码3 项目: lucene-solr   文件: TestExpressionValueSource.java
public void testDoubleValuesSourceTypes() throws Exception {
  Expression expr = JavascriptCompiler.compile("2*popularity + count");
  SimpleBindings bindings = new SimpleBindings();
  bindings.add("popularity", DoubleValuesSource.fromLongField("popularity"));
  bindings.add("count", DoubleValuesSource.fromLongField("count"));
  DoubleValuesSource vs = expr.getDoubleValuesSource(bindings);

  assertEquals(1, reader.leaves().size());
  LeafReaderContext leaf = reader.leaves().get(0);
  DoubleValues values = vs.getValues(leaf, null);

  assertTrue(values.advanceExact(0));
  assertEquals(10, values.doubleValue(), 0);
  assertTrue(values.advanceExact(1));
  assertEquals(41, values.doubleValue(), 0);
  assertTrue(values.advanceExact(2));
  assertEquals(4, values.doubleValue(), 0);
}
 
源代码4 项目: lucene-solr   文件: AbstractSpatialFieldType.java
protected Query getQueryFromSpatialArgs(QParser parser, SchemaField field, SpatialArgs spatialArgs) {
  T strategy = getStrategy(field.getName());

  SolrParams localParams = parser.getLocalParams();
  //See SOLR-2883 needScore
  String scoreParam = (localParams == null ? null : localParams.get(SCORE_PARAM));

  //We get the valueSource for the score then the filter and combine them.
  DoubleValuesSource valueSource = getValueSourceFromSpatialArgs(parser, field, spatialArgs, scoreParam, strategy);
  if (valueSource == null) {
    return strategy.makeQuery(spatialArgs); //assumed constant scoring
  }

  FunctionScoreQuery functionQuery = new FunctionScoreQuery(new MatchAllDocsQuery(), valueSource);

  if (localParams != null && !localParams.getBool(FILTER_PARAM, true))
    return functionQuery;

  Query filterQuery = strategy.makeQuery(spatialArgs);
  return new BooleanQuery.Builder()
      .add(functionQuery, Occur.MUST)//matches everything and provides score
      .add(filterQuery, Occur.FILTER)//filters (score isn't used)
      .build();
}
 
源代码5 项目: lucene-solr   文件: WrappedIntPointField.java
private static DoubleValuesSource fromSortField(SortField field) {
  switch(field.getType()) {
    case INT:
      return DoubleValuesSource.fromIntField(field.getField());
    case LONG:
      return DoubleValuesSource.fromLongField(field.getField());
    case FLOAT:
      return DoubleValuesSource.fromFloatField(field.getField());
    case DOUBLE:
      return DoubleValuesSource.fromDoubleField(field.getField());
    case SCORE:
      return DoubleValuesSource.SCORES;
    default:
      throw new UnsupportedOperationException();
  }
}
 
源代码6 项目: lucene-solr   文件: FunctionScoreQuery.java
@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;
    }
  };
}
 
public void testNoScore() throws Exception {
  Directory indexDir = newDirectory();
  Directory taxoDir = newDirectory();

  DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
  IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(new MockAnalyzer(random())));
  FacetsConfig config = new FacetsConfig();
  for (int i = 0; i < 4; i++) {
    Document doc = new Document();
    doc.add(new NumericDocValuesField("price", (i+1)));
    doc.add(new FacetField("a", Integer.toString(i % 2)));
    iw.addDocument(config.build(taxoWriter, doc));
  }
  
  DirectoryReader r = DirectoryReader.open(iw);
  DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);

  FacetsCollector sfc = new FacetsCollector();
  newSearcher(r).search(new MatchAllDocsQuery(), sfc);
  Facets facets = new TaxonomyFacetSumValueSource(taxoReader, config, sfc, DoubleValuesSource.fromLongField("price"));
  assertEquals("dim=a path=[] value=10.0 childCount=2\n  1 (6.0)\n  0 (4.0)\n", facets.getTopChildren(10, "a").toString());

  iw.close();
  IOUtils.close(taxoWriter, taxoReader, taxoDir, r, indexDir);
}
 
@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);
}
 
源代码9 项目: lucene-solr   文件: TestFunctionScoreQuery.java
public void testScoreModifyingSource() throws Exception {

    BooleanQuery bq = new BooleanQuery.Builder()
        .add(new TermQuery(new Term(TEXT_FIELD, "first")), BooleanClause.Occur.SHOULD)
        .add(new TermQuery(new Term(TEXT_FIELD, "text")), BooleanClause.Occur.SHOULD)
        .build();
    TopDocs plain = searcher.search(bq, 1);

    FunctionScoreQuery fq = FunctionScoreQuery.boostByValue(bq, DoubleValuesSource.fromIntField("iii"));

    QueryUtils.check(random(), fq, searcher, rarely());

    int[] expectedDocs = new int[]{ 4, 7, 9, 8, 12 };
    TopDocs docs = searcher.search(fq, 5);
    assertEquals(plain.totalHits.value, docs.totalHits.value);
    for (int i = 0; i < expectedDocs.length; i++) {
      assertEquals(expectedDocs[i], docs.scoreDocs[i].doc);
    }

    Explanation expl = searcher.explain(fq, 4);
    assertTrue(expl.toString().contains("first"));
    assertTrue(expl.toString().contains("iii"));

  }
 
源代码10 项目: lucene-solr   文件: TestFunctionScoreQuery.java
public void testBoostsAreAppliedLast() throws Exception {

    SimpleBindings bindings = new SimpleBindings();
    bindings.add("score", DoubleValuesSource.SCORES);
    Expression expr = JavascriptCompiler.compile("ln(score + 4)");

    Query q1 = new FunctionScoreQuery(new TermQuery(new Term(TEXT_FIELD, "text")), expr.getDoubleValuesSource(bindings));
    TopDocs plain = searcher.search(q1, 5);

    Query boosted = new BoostQuery(q1, 2);
    TopDocs afterboost = searcher.search(boosted, 5);
    assertEquals(plain.totalHits.value, afterboost.totalHits.value);
    for (int i = 0; i < 5; i++) {
      assertEquals(plain.scoreDocs[i].doc, afterboost.scoreDocs[i].doc);
      assertEquals(plain.scoreDocs[i].score, afterboost.scoreDocs[i].score / 2, 0.0001);
    }

  }
 
源代码11 项目: lucene-solr   文件: TestFunctionScoreQuery.java
public void testTruncateNegativeScores() throws IOException {
  Directory dir = newDirectory();
  IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
  Document doc = new Document();
  doc.add(new NumericDocValuesField("foo", -2));
  w.addDocument(doc);
  IndexReader reader = DirectoryReader.open(w);
  w.close();
  IndexSearcher searcher = newSearcher(reader);
  Query q = new FunctionScoreQuery(new MatchAllDocsQuery(), DoubleValuesSource.fromLongField("foo"));
  QueryUtils.check(random(), q, searcher);
  Explanation expl = searcher.explain(q, 0);
  assertEquals(0, expl.getValue().doubleValue(), 0f);
  assertTrue(expl.toString(), expl.getDetails()[0].getDescription().contains("truncated score"));
  reader.close();
  dir.close();
}
 
源代码12 项目: lucene-solr   文件: TestFunctionScoreQuery.java
public void testNaN() throws IOException {
  Directory dir = newDirectory();
  IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
  Document doc = new Document();
  doc.add(new NumericDocValuesField("foo", Double.doubleToLongBits(Double.NaN)));
  w.addDocument(doc);
  IndexReader reader = DirectoryReader.open(w);
  w.close();
  IndexSearcher searcher = newSearcher(reader);
  Query q = new FunctionScoreQuery(new MatchAllDocsQuery(), DoubleValuesSource.fromDoubleField("foo"));
  QueryUtils.check(random(), q, searcher);
  Explanation expl = searcher.explain(q, 0);
  assertEquals(0, expl.getValue().doubleValue(), 0f);
  assertTrue(expl.toString(), expl.getDetails()[0].getDescription().contains("NaN is an illegal score"));
  reader.close();
  dir.close();
}
 
源代码13 项目: lucene-solr   文件: TestExpressionSorts.java
private DoubleValuesSource fromSortField(SortField field) {
  switch(field.getType()) {
    case INT:
      return DoubleValuesSource.fromIntField(field.getField());
    case LONG:
      return DoubleValuesSource.fromLongField(field.getField());
    case FLOAT:
      return DoubleValuesSource.fromFloatField(field.getField());
    case DOUBLE:
      return DoubleValuesSource.fromDoubleField(field.getField());
    case SCORE:
      return DoubleValuesSource.SCORES;
    default:
      throw new UnsupportedOperationException();
  }
}
 
源代码14 项目: lucene-solr   文件: FastVectorHighlighterTest.java
public void testFunctionScoreQueryHighlight() throws IOException {
  Directory dir = newDirectory();
  IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));
  Document doc = new Document();
  FieldType type = new FieldType(TextField.TYPE_STORED);
  type.setStoreTermVectorOffsets(true);
  type.setStoreTermVectorPositions(true);
  type.setStoreTermVectors(true);
  type.freeze();
  Field field = new Field("field", "This is a test where foo is highlighed and should be highlighted", type);

  doc.add(field);
  writer.addDocument(doc);
  FastVectorHighlighter highlighter = new FastVectorHighlighter();

  IndexReader reader = DirectoryReader.open(writer);
  int docId = 0;
  FieldQuery fieldQuery  = highlighter.getFieldQuery( new FunctionScoreQuery(new TermQuery(new Term("field", "foo")), DoubleValuesSource.constant(1)), reader );
  String[] bestFragments = highlighter.getBestFragments(fieldQuery, reader, docId, "field", 54, 1);
  // highlighted results are centered
  assertEquals("This is a test where <b>foo</b> is highlighed and should be highlighted", bestFragments[0]);
  bestFragments = highlighter.getBestFragments(fieldQuery, reader, docId, "field", 52, 1);
  assertEquals("This is a test where <b>foo</b> is highlighed and should be", bestFragments[0]);
  bestFragments = highlighter.getBestFragments(fieldQuery, reader, docId, "field", 30, 1);
  assertEquals("a test where <b>foo</b> is highlighed", bestFragments[0]);
  reader.close();
  writer.close();
  dir.close();
}
 
源代码15 项目: lucene-solr   文件: TestExpressionValueSource.java
public void testDoubleValuesSourceEquals() throws Exception {
  Expression expr = JavascriptCompiler.compile("sqrt(a) + ln(b)");

  SimpleBindings bindings = new SimpleBindings();
  bindings.add("a", DoubleValuesSource.fromIntField("a"));
  bindings.add("b", DoubleValuesSource.fromIntField("b"));

  DoubleValuesSource vs1 = expr.getDoubleValuesSource(bindings);
  // same instance
  assertEquals(vs1, vs1);
  // null
  assertFalse(vs1.equals(null));
  // other object
  assertFalse(vs1.equals("foobar"));
  // same bindings and expression instances
  DoubleValuesSource vs2 = expr.getDoubleValuesSource(bindings);
  assertEquals(vs1.hashCode(), vs2.hashCode());
  assertEquals(vs1, vs2);
  // equiv bindings (different instance)
  SimpleBindings bindings2 = new SimpleBindings();
  bindings2.add("a", DoubleValuesSource.fromIntField("a"));
  bindings2.add("b", DoubleValuesSource.fromIntField("b"));
  DoubleValuesSource vs3 = expr.getDoubleValuesSource(bindings2);
  assertEquals(vs1, vs3);
  // different bindings (same names, different types)
  SimpleBindings bindings3 = new SimpleBindings();
  bindings3.add("a", DoubleValuesSource.fromLongField("a"));
  bindings3.add("b", DoubleValuesSource.fromFloatField("b"));
  DoubleValuesSource vs4 = expr.getDoubleValuesSource(bindings3);
  assertFalse(vs1.equals(vs4));
}
 
源代码16 项目: lucene-solr   文件: PrefixTreeStrategy.java
@Override
public DoubleValuesSource makeDistanceValueSource(Point queryPoint, double multiplier) {
  PointPrefixTreeFieldCacheProvider p = provider.get( getFieldName() );
  if( p == null ) {
    synchronized (this) {//double checked locking idiom is okay since provider is threadsafe
      p = provider.get( getFieldName() );
      if (p == null) {
        p = new PointPrefixTreeFieldCacheProvider(grid, getFieldName(), defaultFieldValuesArrayLen);
        provider.put(getFieldName(),p);
      }
    }
  }

  return new ShapeFieldCacheDistanceValueSource(ctx, p, queryPoint, multiplier);
}
 
源代码17 项目: lucene-solr   文件: TestExpressionRescorer.java
public void testBasic() throws Exception {

    // create a sort field and sort by it (reverse order)
    Query query = new TermQuery(new Term("body", "contents"));
    IndexReader r = searcher.getIndexReader();

    // Just first pass query
    TopDocs hits = searcher.search(query, 10);
    assertEquals(3, hits.totalHits.value);
    assertEquals("3", r.document(hits.scoreDocs[0].doc).get("id"));
    assertEquals("1", r.document(hits.scoreDocs[1].doc).get("id"));
    assertEquals("2", r.document(hits.scoreDocs[2].doc).get("id"));

    // Now, rescore:

    Expression e = JavascriptCompiler.compile("sqrt(_score) + ln(popularity)");
    SimpleBindings bindings = new SimpleBindings();
    bindings.add("popularity", DoubleValuesSource.fromIntField("popularity"));
    bindings.add("_score", DoubleValuesSource.SCORES);
    Rescorer rescorer = e.getRescorer(bindings);

    hits = rescorer.rescore(searcher, hits, 10);
    assertEquals(3, hits.totalHits.value);
    assertEquals("2", r.document(hits.scoreDocs[0].doc).get("id"));
    assertEquals("1", r.document(hits.scoreDocs[1].doc).get("id"));
    assertEquals("3", r.document(hits.scoreDocs[2].doc).get("id"));

    String expl = rescorer.explain(searcher,
                                   searcher.explain(query, hits.scoreDocs[0].doc),
                                   hits.scoreDocs[0].doc).toString();

    // Confirm the explanation breaks out the individual
    // variables:
    assertTrue(expl.contains("= double(popularity)"));

    // Confirm the explanation includes first pass details:
    assertTrue(expl.contains("= first pass score"));
    assertTrue(expl.contains("body:contents in"));
  }
 
源代码18 项目: lucene-solr   文件: PointVectorStrategy.java
@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);
    }

  };
}
 
源代码19 项目: lucene-solr   文件: ExpressionValueSource.java
@Override
public DoubleValuesSource rewrite(IndexSearcher searcher) throws IOException {
  boolean changed = false;
  DoubleValuesSource[] rewritten = new DoubleValuesSource[variables.length];
  for (int i = 0; i < variables.length; i++) {
    rewritten[i] = variables[i].rewrite(searcher);
    changed |= (rewritten[i] != variables[i]);
  }
  if (changed) {
    return new ExpressionValueSource(rewritten, expression, needsScores);
  }
  return this;
}
 
public void testWithScore() throws Exception {
  Directory indexDir = newDirectory();
  Directory taxoDir = newDirectory();

  DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
  IndexWriter iw = new IndexWriter(indexDir, newIndexWriterConfig(new MockAnalyzer(random())));

  FacetsConfig config = new FacetsConfig();
  for (int i = 0; i < 4; i++) {
    Document doc = new Document();
    doc.add(new NumericDocValuesField("price", (i+1)));
    doc.add(new FacetField("a", Integer.toString(i % 2)));
    iw.addDocument(config.build(taxoWriter, doc));
  }
  
  DirectoryReader r = DirectoryReader.open(iw);
  DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
  
  FacetsCollector fc = new FacetsCollector(true);
  // score documents by their 'price' field - makes asserting the correct counts for the categories easier
  Query q = new FunctionQuery(new LongFieldSource("price"));
  FacetsCollector.search(newSearcher(r), q, 10, fc);
  Facets facets = new TaxonomyFacetSumValueSource(taxoReader, config, fc, DoubleValuesSource.SCORES);
  
  assertEquals("dim=a path=[] value=10.0 childCount=2\n  1 (6.0)\n  0 (4.0)\n", facets.getTopChildren(10, "a").toString());

  iw.close();
  IOUtils.close(taxoWriter, taxoReader, taxoDir, r, indexDir);
}
 
源代码21 项目: lucene-solr   文件: StrategyTestCase.java
/** scores[] are in docId order */
protected void checkValueSource(DoubleValuesSource vs, float scores[], float delta) throws IOException {

  for (LeafReaderContext ctx : indexSearcher.getTopReaderContext().leaves()) {
    DoubleValues v = vs.getValues(ctx, null);
    int count = ctx.reader().maxDoc();
    for (int i = 0; i < count; i++) {
      assertTrue(v.advanceExact(i));
      int doc = i + ctx.docBase;
      assertEquals("Not equal for doc " + doc, v.doubleValue(), (double) scores[doc], delta);
    }
  }

}
 
源代码22 项目: lucene-solr   文件: TestFeatureDoubleValues.java
public void testFeatureMissing() throws IOException {
  Directory dir = newDirectory();
  IndexWriterConfig config = newIndexWriterConfig().setMergePolicy(newLogMergePolicy(random().nextBoolean()));
  RandomIndexWriter writer = new RandomIndexWriter(random(), dir, config);
  Document doc = new Document();
  writer.addDocument(doc);
  doc = new Document();
  doc.add(new FeatureField("field", "name", 1F));
  writer.addDocument(doc);
  doc = new Document();
  doc.add(new FeatureField("field", "name", 4F));
  writer.addDocument(doc);
  writer.forceMerge(1);
  IndexReader ir = writer.getReader();
  writer.close();

  assertEquals(1, ir.leaves().size());
  LeafReaderContext context = ir.leaves().get(0);
  DoubleValuesSource valuesSource = FeatureField.newDoubleValues("field", "name");
  DoubleValues values = valuesSource.getValues(context, null);

  assertFalse(values.advanceExact(0));
  assertTrue(values.advanceExact(1));
  assertEquals(1, values.doubleValue(), 0f);
  assertTrue(values.advanceExact(2));
  assertEquals(4, values.doubleValue(), 0f);
  assertFalse(values.advanceExact(3));

  ir.close();
  dir.close();
}
 
源代码23 项目: lucene-solr   文件: ExpressionValueSource.java
@Override
public boolean isCacheable(LeafReaderContext ctx) {
  for (DoubleValuesSource v : variables) {
    if (v.isCacheable(ctx) == false)
      return false;
  }
  return true;
}
 
源代码24 项目: lucene-solr   文件: ExpressionValueSource.java
@Override
public Explanation explain(LeafReaderContext ctx, int docId, Explanation scoreExplanation) throws IOException {
  Explanation[] explanations = new Explanation[variables.length];
  DoubleValues dv = getValues(ctx, DoubleValuesSource.constant(scoreExplanation.getValue().doubleValue()).getValues(ctx, null));
  if (dv.advanceExact(docId) == false) {
    return Explanation.noMatch(expression.sourceText);
  }
  int i = 0;
  for (DoubleValuesSource var : variables) {
    explanations[i++] = var.explain(ctx, docId, scoreExplanation);
  }
  return Explanation.match(dv.doubleValue(), expression.sourceText + ", computed from:", explanations);
}
 
源代码25 项目: lucene-solr   文件: TaxonomyFacetSumValueSource.java
/**
 * Aggreggates float facet values from the provided
 *  {@link DoubleValuesSource}, and pulls ordinals from the
 *  provided {@link OrdinalsReader}.
 */
public TaxonomyFacetSumValueSource(OrdinalsReader ordinalsReader, TaxonomyReader taxoReader,
                                   FacetsConfig config, FacetsCollector fc, DoubleValuesSource vs) throws IOException {
  super(ordinalsReader.getIndexFieldName(), taxoReader, config);
  this.ordinalsReader = ordinalsReader;
  sumValues(fc.getMatchingDocs(), fc.getKeepScores(), vs);
}
 
源代码26 项目: lucene-solr   文件: TestExpressionValidation.java
public void testInvalidExternal() throws Exception {
  SimpleBindings bindings = new SimpleBindings();
  bindings.add("valid", DoubleValuesSource.fromIntField("valid"));
  bindings.add("invalid", JavascriptCompiler.compile("badreference"));
  IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {
    bindings.validate();
  });
  assertTrue(expected.getMessage().contains("Invalid reference"));
}
 
源代码27 项目: lucene-solr   文件: AbstractSpatialFieldType.java
protected DoubleValuesSource getValueSourceFromSpatialArgs(QParser parser, SchemaField field, SpatialArgs spatialArgs, String score, T strategy) {
  if (score == null) {
    return null;
  }

  final double multiplier; // default multiplier for degrees

  switch(score) {
    case "":
    case NONE:
      return null;
    case RECIP_DISTANCE:
      return strategy.makeRecipDistanceValueSource(spatialArgs.getShape());
    case DISTANCE:
      multiplier = distanceUnits.multiplierFromDegreesToThisUnit();
      break;
    default:
      DistanceUnits du = parseDistanceUnits(score);
      if (du != null) {
        multiplier = du.multiplierFromDegreesToThisUnit();
      } else {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                                "'score' local-param must be one of " + supportedScoreModes + ", it was: " + score);
      }
  }

  return strategy.makeDistanceValueSource(spatialArgs.getShape().getCenter(), multiplier);
}
 
源代码28 项目: lucene-solr   文件: SimpleBindings.java
@Override
public DoubleValuesSource getDoubleValuesSource(String name) {
  if (seenFields.contains(name)) {
    throw new IllegalArgumentException("Recursion error: Cycle detected " + seenFields + "->" + name);
  }
  if (map.containsKey(name) == false) {
    throw new IllegalArgumentException("Invalid reference '" + name + "'");
  }
  return map.get(name).apply(new CycleDetectionBindings(seenFields, name));
}
 
源代码29 项目: lucene-solr   文件: TestExpressionValueSource.java
public void testRewrite() throws Exception {
  Expression expr = JavascriptCompiler.compile("a");

  ExpressionValueSource rewritingExpressionSource = new ExpressionValueSource(
          new DoubleValuesSource[]{createDoubleValuesSourceMock(true)},
          expr,
          false);
  ExpressionValueSource notRewritingExpressionSource = new ExpressionValueSource(
          new DoubleValuesSource[]{createDoubleValuesSourceMock(false)},
          expr,
          false);

  assertNotSame(rewritingExpressionSource, rewritingExpressionSource.rewrite(null));
  assertSame(notRewritingExpressionSource, notRewritingExpressionSource.rewrite(null));
}
 
源代码30 项目: lucene-solr   文件: BBoxField.java
@Override
protected DoubleValuesSource getValueSourceFromSpatialArgs(QParser parser, SchemaField field, SpatialArgs spatialArgs, String scoreParam, BBoxStrategy strategy) {
  if (scoreParam == null) {
    return null;
  }

  switch (scoreParam) {
    //TODO move these to superclass after LUCENE-5804 ?
    case OVERLAP_RATIO:
      double queryTargetProportion = 0.25;//Suggested default; weights towards target area

      String v = parser.getParam(PARAM_QUERY_TARGET_PROPORTION);
      if (v != null)
        queryTargetProportion = Double.parseDouble(v);

      double minSideLength = 0.0;
      v = parser.getParam(PARAM_MIN_SIDE_LENGTH);
      if (v != null)
        minSideLength = Double.parseDouble(v);

      return new BBoxOverlapRatioValueSource(
          strategy.makeShapeValueSource(), ctx.isGeo(),
          (Rectangle) spatialArgs.getShape(),
          queryTargetProportion, minSideLength);

    case AREA:
      return new ShapeAreaValueSource(strategy.makeShapeValueSource(), ctx, ctx.isGeo(),
          distanceUnits.multiplierFromDegreesToThisUnit() * distanceUnits.multiplierFromDegreesToThisUnit());

    case AREA2D:
      return new ShapeAreaValueSource(strategy.makeShapeValueSource(), ctx, false,
          distanceUnits.multiplierFromDegreesToThisUnit() * distanceUnits.multiplierFromDegreesToThisUnit());

    default:
      return super.getValueSourceFromSpatialArgs(parser, field, spatialArgs, scoreParam, strategy);
  }
}