Java Code Examples for org.apache.lucene.search.DoubleValuesSource

The following examples show how to use org.apache.lucene.search.DoubleValuesSource. These examples are extracted from open source projects. 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 Project: lucene-solr   Source File: TestDemoExpressions.java    License: Apache License 2.0 6 votes vote down vote up
/** 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);
  }
}
 
Example 2
Source Project: lucene-solr   Source File: TestDemoExpressions.java    License: Apache License 2.0 6 votes vote down vote up
/** 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);
  }
}
 
Example 3
Source Project: lucene-solr   Source File: TestExpressionValueSource.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 4
Source Project: lucene-solr   Source File: AbstractSpatialFieldType.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 5
Source Project: lucene-solr   Source File: WrappedIntPointField.java    License: Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example 6
Source Project: lucene-solr   Source File: FunctionScoreQuery.java    License: 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 7
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);
}
 
Example 8
@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 9
Source Project: lucene-solr   Source File: TestFunctionScoreQuery.java    License: Apache License 2.0 6 votes vote down vote up
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"));

  }
 
Example 10
Source Project: lucene-solr   Source File: TestFunctionScoreQuery.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }

  }
 
Example 11
Source Project: lucene-solr   Source File: TestFunctionScoreQuery.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 12
Source Project: lucene-solr   Source File: TestFunctionScoreQuery.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 13
Source Project: lucene-solr   Source File: TestExpressionSorts.java    License: Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example 14
Source Project: lucene-solr   Source File: FastVectorHighlighterTest.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 15
Source Project: lucene-solr   Source File: TestExpressionValueSource.java    License: Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 16
Source Project: lucene-solr   Source File: PrefixTreeStrategy.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 17
Source Project: lucene-solr   Source File: TestExpressionRescorer.java    License: Apache License 2.0 5 votes vote down vote up
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"));
  }
 
Example 18
Source Project: lucene-solr   Source File: PointVectorStrategy.java    License: 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 19
Source Project: lucene-solr   Source File: ExpressionValueSource.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 20
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);
}
 
Example 21
Source Project: lucene-solr   Source File: StrategyTestCase.java    License: Apache License 2.0 5 votes vote down vote up
/** 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);
    }
  }

}
 
Example 22
Source Project: lucene-solr   Source File: TestFeatureDoubleValues.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 23
Source Project: lucene-solr   Source File: ExpressionValueSource.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isCacheable(LeafReaderContext ctx) {
  for (DoubleValuesSource v : variables) {
    if (v.isCacheable(ctx) == false)
      return false;
  }
  return true;
}
 
Example 24
Source Project: lucene-solr   Source File: ExpressionValueSource.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 25
Source Project: lucene-solr   Source File: TaxonomyFacetSumValueSource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 26
Source Project: lucene-solr   Source File: TestExpressionValidation.java    License: Apache License 2.0 5 votes vote down vote up
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"));
}
 
Example 27
Source Project: lucene-solr   Source File: AbstractSpatialFieldType.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 28
Source Project: lucene-solr   Source File: SimpleBindings.java    License: Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 29
Source Project: lucene-solr   Source File: TestExpressionValueSource.java    License: Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 30
Source Project: lucene-solr   Source File: BBoxField.java    License: Apache License 2.0 5 votes vote down vote up
@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);
  }
}