org.apache.lucene.queries.function.FunctionScoreQuery Java Examples

The following examples show how to use org.apache.lucene.queries.function.FunctionScoreQuery. 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: LuceneIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected Iterable<? extends DocumentDistance> geoQuery(final IRI geoProperty, Point p, final IRI units,
		double distance, String distanceVar, Var contextVar) throws MalformedQueryException, IOException {
	double degs = GeoUnits.toDegrees(distance, units);
	final String geoField = SearchFields.getPropertyField(geoProperty);
	SpatialStrategy strategy = getSpatialStrategyMapper().apply(geoField);
	final Shape boundingCircle = strategy.getSpatialContext().getShapeFactory().circle(p, degs);
	Query q = strategy.makeQuery(new SpatialArgs(SpatialOperation.Intersects, boundingCircle));
	if (contextVar != null) {
		q = addContextTerm(q, (Resource) contextVar.getValue());
	}

	TopDocs docs = search(new FunctionScoreQuery(q, strategy.makeRecipDistanceValueSource(boundingCircle)));
	final boolean requireContext = (contextVar != null && !contextVar.hasValue());
	return Iterables.transform(Arrays.asList(docs.scoreDocs), new Function<ScoreDoc, DocumentDistance>() {

		@Override
		public DocumentDistance apply(ScoreDoc doc) {
			return new LuceneDocumentDistance(doc, geoField, units, boundingCircle.getCenter(), requireContext,
					LuceneIndex.this);
		}
	});
}
 
Example #2
Source File: AbstractSpatialFieldType.java    From lucene-solr with 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 #3
Source File: FastVectorHighlighterTest.java    From lucene-solr with 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 #4
Source File: SpatialFileQueryMaker.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
protected Query makeQueryFromShape(Shape shape) {
  SpatialArgs args = new SpatialArgs(operation, shape);
  if (!Double.isNaN(distErrPct))
    args.setDistErrPct(distErrPct);

  Query filterQuery = strategy.makeQuery(args);
  if (score) {
    //wrap with distance computing query
    DoubleValuesSource valueSource = strategy.makeDistanceValueSource(shape.getCenter());
    return new FunctionScoreQuery(filterQuery, valueSource);
  } else {
    return filterQuery; // assume constant scoring
  }
}
 
Example #5
Source File: BoostQParserPlugin.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
  return new QParser(qstr, localParams, params, req) {
    QParser baseParser;
    ValueSource vs;
    String b;

    @Override
    public Query parse() throws SyntaxError {
      b = localParams.get(BOOSTFUNC);
      baseParser = subQuery(localParams.get(QueryParsing.V), null);
      Query q = baseParser.getQuery();

      if (b == null) return q;
      Query bq = subQuery(b, FunctionQParserPlugin.NAME).getQuery();
      if (bq instanceof FunctionQuery) {
        vs = ((FunctionQuery)bq).getValueSource();
      } else {
        vs = new QueryValueSource(bq, 0.0f);
      }
      return FunctionScoreQuery.boostByValue(q, vs.asDoubleValuesSource());
    }


    @Override
    public String[] getDefaultHighlightFields() {
      return baseParser.getDefaultHighlightFields();
    }
                                         
    @Override
    public Query getHighlightQuery() throws SyntaxError {
      return baseParser.getHighlightQuery();
    }

    @Override
    public void addDebugInfo(NamedList<Object> debugInfo) {
      // encapsulate base debug info in a sub-list?
      baseParser.addDebugInfo(debugInfo);
      debugInfo.add("boost_str",b);
      debugInfo.add("boost_parsed",vs);
    }
  };
}
 
Example #6
Source File: ValueSourceParser.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public ValueSource parse(FunctionQParser fp) throws SyntaxError {
  Query q = fp.parseNestedQuery();
  ValueSource vs = fp.parseValueSource();
  return new QueryValueSource(FunctionScoreQuery.boostByValue(q, vs.asDoubleValuesSource()), 0.0f);
}
 
Example #7
Source File: LuceneQueryUtil.java    From querqy with Apache License 2.0 4 votes vote down vote up
public static DoubleValuesSource queryToDoubleValueSource(final Query query) {
    return (query instanceof FunctionScoreQuery)
            ? ((FunctionScoreQuery)query).getSource()
            : DoubleValuesSource.fromQuery(query);
}
 
Example #8
Source File: SearchQueryFactoryImpl.java    From yes-cart with Apache License 2.0 3 votes vote down vote up
private Query productBoost(final Query query) {

        if (query == null) {
            return null;
        }

        return FunctionScoreQuery.boostByValue(query, PRODUCT_BOOST_FIELDS);

    }
 
Example #9
Source File: SearchQueryFactoryImpl.java    From yes-cart with Apache License 2.0 3 votes vote down vote up
private Query skuBoost(final Query query) {

        if (query == null) {
            return null;
        }

        return FunctionScoreQuery.boostByValue(query, SKU_BOOST_FIELDS);

    }