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

The following examples show how to use org.apache.lucene.search.BoostQuery. 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: FieldQuery.java    License: Apache License 2.0 6 votes vote down vote up
public FieldQuery(Query query, IndexReader reader, boolean phraseHighlight, boolean fieldMatch) throws IOException {
  this.fieldMatch = fieldMatch;
  Set<Query> flatQueries = new LinkedHashSet<>();
  flatten( query, reader, flatQueries, 1f );
  saveTerms( flatQueries, reader );
  Collection<Query> expandQueries = expand( flatQueries );

  for( Query flatQuery : expandQueries ){
    QueryPhraseMap rootMap = getRootMap( flatQuery );
    rootMap.add( flatQuery, reader );
    float boost = 1f;
    while (flatQuery instanceof BoostQuery) {
      BoostQuery bq = (BoostQuery) flatQuery;
      flatQuery = bq.getQuery();
      boost *= bq.getBoost();
    }
    if( !phraseHighlight && flatQuery instanceof PhraseQuery ){
      PhraseQuery pq = (PhraseQuery)flatQuery;
      if( pq.getTerms().length > 1 ){
        for( Term term : pq.getTerms() )
          rootMap.addTerm( term, boost );
      }
    }
  }
}
 
Example 2
Source Project: lucene-solr   Source File: FieldQuery.java    License: Apache License 2.0 6 votes vote down vote up
private String getKey( Query query ){
  if( !fieldMatch ) return null;
  while (query instanceof BoostQuery) {
    query = ((BoostQuery) query).getQuery();
  }
  if( query instanceof TermQuery )
    return ((TermQuery)query).getTerm().field();
  else if ( query instanceof PhraseQuery ){
    PhraseQuery pq = (PhraseQuery)query;
    Term[] terms = pq.getTerms();
    return terms[0].field();
  }
  else if (query instanceof MultiTermQuery) {
    return ((MultiTermQuery)query).getField();
  }
  else
    throw new RuntimeException( "query \"" + query.toString() + "\" must be flatten first." );
}
 
Example 3
Source Project: lucene-solr   Source File: FieldQuery.java    License: Apache License 2.0 6 votes vote down vote up
void saveTerms( Collection<Query> flatQueries, IndexReader reader ) throws IOException{
  for( Query query : flatQueries ){
    while (query instanceof BoostQuery) {
      query = ((BoostQuery) query).getQuery();
    }
    Set<String> termSet = getTermSet( query );
    if( query instanceof TermQuery )
      termSet.add( ((TermQuery)query).getTerm().text() );
    else if( query instanceof PhraseQuery ){
      for( Term term : ((PhraseQuery)query).getTerms() )
        termSet.add( term.text() );
    }
    else if (query instanceof MultiTermQuery && reader != null) {
      BooleanQuery mtqTerms = (BooleanQuery) query.rewrite(reader);
      for (BooleanClause clause : mtqTerms) {
        termSet.add (((TermQuery) clause.getQuery()).getTerm().text());
      }
    }
    else
      throw new RuntimeException( "query \"" + query.toString() + "\" must be flatten first." );
  }
}
 
Example 4
Source Project: lucene-solr   Source File: FieldQuery.java    License: Apache License 2.0 6 votes vote down vote up
void add( Query query, IndexReader reader ) {
  float boost = 1f;
  while (query instanceof BoostQuery) {
    BoostQuery bq = (BoostQuery) query;
    query = bq.getQuery();
    boost = bq.getBoost();
  }
  if( query instanceof TermQuery ){
    addTerm( ((TermQuery)query).getTerm(), boost );
  }
  else if( query instanceof PhraseQuery ){
    PhraseQuery pq = (PhraseQuery)query;
    Term[] terms = pq.getTerms();
    Map<String, QueryPhraseMap> map = subMap;
    QueryPhraseMap qpm = null;
    for( Term term : terms ){
      qpm = getOrNewMap( map, term.text() );
      map = qpm.subMap;
    }
    qpm.markTerminal( pq.getSlop(), boost );
  }
  else
    throw new RuntimeException( "query \"" + query.toString() + "\" must be flatten first." );
}
 
Example 5
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 6
Source Project: lucene-solr   Source File: QueryDecomposer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Split a query up into individual parts that can be indexed and run separately
 *
 * @param q the query
 * @return a collection of subqueries
 */
public Set<Query> decompose(Query q) {

  if (q instanceof BooleanQuery)
    return decomposeBoolean((BooleanQuery) q);

  if (q instanceof DisjunctionMaxQuery) {
    Set<Query> subqueries = new HashSet<>();
    for (Query subq : ((DisjunctionMaxQuery) q).getDisjuncts()) {
      subqueries.addAll(decompose(subq));
    }
    return subqueries;
  }

  if (q instanceof BoostQuery) {
    return decomposeBoostQuery((BoostQuery) q);
  }

  return Collections.singleton(q);
}
 
Example 7
Source Project: lucene-solr   Source File: UserInputQueryBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Query getQuery(Element e) throws ParserException {
  String text = DOMUtils.getText(e);
  try {
    Query q = null;
    if (unSafeParser != null) {
      //synchronize on unsafe parser
      synchronized (unSafeParser) {
        q = unSafeParser.parse(text);
      }
    } else {
      String fieldName = DOMUtils.getAttribute(e, "fieldName", defaultField);
      //Create new parser
      QueryParser parser = createQueryParser(fieldName, analyzer);
      q = parser.parse(text);
    }
    float boost = DOMUtils.getAttribute(e, "boost", 1.0f);
    return new BoostQuery(q, boost);
  } catch (ParseException e1) {
    throw new ParserException(e1.getMessage());
  }
}
 
Example 8
Source Project: lucene-solr   Source File: TestPrecedenceQueryParser.java    License: Apache License 2.0 6 votes vote down vote up
public void testBoost() throws Exception {
  CharacterRunAutomaton stopSet = new CharacterRunAutomaton(Automata.makeString("on"));
  Analyzer oneStopAnalyzer = new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, stopSet);

  PrecedenceQueryParser qp = new PrecedenceQueryParser();
  qp.setAnalyzer(oneStopAnalyzer);
  Query q = qp.parse("on^1.0", "field");
  assertNotNull(q);
  q = qp.parse("\"hello\"^2.0", "field");
  assertNotNull(q);
  assertEquals(((BoostQuery) q).getBoost(), (float) 2.0, (float) 0.5);
  q = qp.parse("hello^2.0", "field");
  assertNotNull(q);
  assertEquals(((BoostQuery) q).getBoost(), (float) 2.0, (float) 0.5);
  q = qp.parse("\"on\"^1.0", "field");
  assertNotNull(q);

  q = getParser(new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET)).parse("the^3",
      "field");
  assertNotNull(q);
}
 
Example 9
Source Project: lucene-solr   Source File: TestQPHelper.java    License: Apache License 2.0 6 votes vote down vote up
public void testBoost() throws Exception {
  CharacterRunAutomaton stopSet = new CharacterRunAutomaton(Automata.makeString("on"));
  Analyzer oneStopAnalyzer = new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, stopSet);
  StandardQueryParser qp = new StandardQueryParser();
  qp.setAnalyzer(oneStopAnalyzer);

  Query q = qp.parse("on^1.0", "field");
  assertNotNull(q);
  q = qp.parse("\"hello\"^2.0", "field");
  assertNotNull(q);
  assertEquals(((BoostQuery) q).getBoost(), (float) 2.0, (float) 0.5);
  q = qp.parse("hello^2.0", "field");
  assertNotNull(q);
  assertEquals(((BoostQuery) q).getBoost(), (float) 2.0, (float) 0.5);
  q = qp.parse("\"on\"^1.0", "field");
  assertNotNull(q);

  StandardQueryParser qp2 = new StandardQueryParser();
  qp2.setAnalyzer(new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET));

  q = qp2.parse("the^3", "field");
  // "the" is a stop word so the result is an empty query:
  assertNotNull(q);
  assertMatchNoDocsQuery(q);
  assertFalse(q instanceof BoostQuery);
}
 
Example 10
Source Project: lucene-solr   Source File: QueryParserTestBase.java    License: Apache License 2.0 6 votes vote down vote up
public void testBoost()
  throws Exception {
  CharacterRunAutomaton stopWords = new CharacterRunAutomaton(Automata.makeString("on"));
  Analyzer oneStopAnalyzer = new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, stopWords);
  CommonQueryParserConfiguration qp = getParserConfig(oneStopAnalyzer);
  Query q = getQuery("on^1.0",qp);
  assertNotNull(q);
  q = getQuery("\"hello\"^2.0",qp);
  assertNotNull(q);
  assertEquals(((BoostQuery) q).getBoost(), (float) 2.0, (float) 0.5);
  q = getQuery("hello^2.0",qp);
  assertNotNull(q);
  assertEquals(((BoostQuery) q).getBoost(), (float) 2.0, (float) 0.5);
  q = getQuery("\"on\"^1.0",qp);
  assertNotNull(q);

  Analyzer a2 = new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET); 
  CommonQueryParserConfiguration qp2 = getParserConfig(a2);
  q = getQuery("the^3", qp2);
  // "the" is a stop word so the result is an empty query:
  assertNotNull(q);
  assertMatchNoDocsQuery(q);
  assertFalse(q instanceof BoostQuery);
}
 
Example 11
Source Project: lucene-solr   Source File: QueryParserTestBase.java    License: Apache License 2.0 6 votes vote down vote up
public void testStopwords() throws Exception {
  CharacterRunAutomaton stopSet = new CharacterRunAutomaton(new RegExp("the|foo").toAutomaton());
  CommonQueryParserConfiguration qp = getParserConfig(new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, stopSet));
  Query result = getQuery("field:the OR field:foo",qp);
  assertNotNull("result is null and it shouldn't be", result);
  assertTrue("result is not a BooleanQuery", result instanceof BooleanQuery || result instanceof MatchNoDocsQuery);
  if (result instanceof BooleanQuery) {
    assertEquals(0, ((BooleanQuery) result).clauses().size());
  }
  result = getQuery("field:woo OR field:the",qp);
  assertNotNull("result is null and it shouldn't be", result);
  assertTrue("result is not a TermQuery", result instanceof TermQuery);
  result = getQuery("(fieldX:xxxxx OR fieldy:xxxxxxxx)^2 AND (fieldx:the OR fieldy:foo)",qp);
  assertNotNull("result is null and it shouldn't be", result);
  assertTrue("result is not a BoostQuery", result instanceof BoostQuery);
  result = ((BoostQuery) result).getQuery();
  assertTrue("result is not a BooleanQuery", result instanceof BooleanQuery);
  if (VERBOSE) System.out.println("Result: " + result);
  assertTrue(((BooleanQuery) result).clauses().size() + " does not equal: " + 2, ((BooleanQuery) result).clauses().size() == 2);
}
 
Example 12
Source Project: lucene-solr   Source File: QueryBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/** 
 * Creates simple phrase query from the cached tokenstream contents 
 */
protected Query analyzePhrase(String field, TokenStream stream, int slop) throws IOException {
  PhraseQuery.Builder builder = new PhraseQuery.Builder();
  builder.setSlop(slop);
  
  TermToBytesRefAttribute termAtt = stream.getAttribute(TermToBytesRefAttribute.class);
  BoostAttribute boostAtt = stream.addAttribute(BoostAttribute.class);
  PositionIncrementAttribute posIncrAtt = stream.getAttribute(PositionIncrementAttribute.class);
  int position = -1;
  float phraseBoost = DEFAULT_BOOST;
  stream.reset();
  while (stream.incrementToken()) {
    if (enablePositionIncrements) {
      position += posIncrAtt.getPositionIncrement();
    } else {
      position += 1;
    }
    builder.add(new Term(field, termAtt.getBytesRef()), position);
    phraseBoost *= boostAtt.getBoost();
  }
  PhraseQuery query = builder.build();
  if (phraseBoost == DEFAULT_BOOST) {
    return query;
  }
  return new BoostQuery(query, phraseBoost);
}
 
Example 13
Source Project: lucene-solr   Source File: TestBooleanSimilarity.java    License: Apache License 2.0 6 votes vote down vote up
public void testPhraseScoreIsEqualToBoost() throws IOException {
  Directory dir = newDirectory();
  RandomIndexWriter w = new RandomIndexWriter(random(), dir,
      newIndexWriterConfig().setSimilarity(new BooleanSimilarity()));
  Document doc = new Document();
  doc.add(new TextField("foo", "bar baz quux", Store.NO));
  w.addDocument(doc);

  DirectoryReader reader = w.getReader();
  w.close();
  IndexSearcher searcher = newSearcher(reader);
  searcher.setSimilarity(new BooleanSimilarity());

  PhraseQuery query = new PhraseQuery(2, "foo", "bar", "quux");

  TopDocs topDocs = searcher.search(query, 2);
  assertEquals(1, topDocs.totalHits.value);
  assertEquals(1f, topDocs.scoreDocs[0].score, 0f);

  topDocs = searcher.search(new BoostQuery(query, 7), 2);
  assertEquals(1, topDocs.totalHits.value);
  assertEquals(7f, topDocs.scoreDocs[0].score, 0f);

  reader.close();
  dir.close();
}
 
Example 14
Source Project: lucene-solr   Source File: MoreLikeThisHandler.java    License: Apache License 2.0 6 votes vote down vote up
private Query getBoostedQuery(Query mltquery) {
  BooleanQuery boostedQuery = (BooleanQuery)mltquery;
  if (boostFields.size() > 0) {
    BooleanQuery.Builder newQ = new BooleanQuery.Builder();
    newQ.setMinimumNumberShouldMatch(boostedQuery.getMinimumNumberShouldMatch());
    for (BooleanClause clause : boostedQuery) {
      Query q = clause.getQuery();
      float originalBoost = 1f;
      if (q instanceof BoostQuery) {
        BoostQuery bq = (BoostQuery) q;
        q = bq.getQuery();
        originalBoost = bq.getBoost();
      }
      Float fieldBoost = boostFields.get(((TermQuery) q).getTerm().field());
      q = ((fieldBoost != null) ? new BoostQuery(q, fieldBoost * originalBoost) : clause.getQuery());
      newQ.add(q, clause.getOccur());
    }
    boostedQuery = newQ.build();
  }
  return boostedQuery;
}
 
Example 15
Source Project: lucene-solr   Source File: MoreLikeThisHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void fillInterestingTermsFromMLTQuery( Query query, List<InterestingTerm> terms )
{ 
  Collection<BooleanClause> clauses = ((BooleanQuery)query).clauses();
  for( BooleanClause o : clauses ) {
    Query q = o.getQuery();
    float boost = 1f;
    if (q instanceof BoostQuery) {
      BoostQuery bq = (BoostQuery) q;
      q = bq.getQuery();
      boost = bq.getBoost();
    }
    InterestingTerm it = new InterestingTerm();
    it.boost = boost;
    it.term = ((TermQuery) q).getTerm();
    terms.add( it );
  } 
  // alternatively we could use
  // mltquery.extractTerms( terms );
}
 
Example 16
Source Project: lucene-solr   Source File: QueryElevationComponent.java    License: Apache License 2.0 6 votes vote down vote up
private void setQuery(ResponseBuilder rb, Elevation elevation) {
  rb.req.getContext().put(BOOSTED, elevation.elevatedIds);

  // Change the query to insert forced documents
  SolrParams params = rb.req.getParams();
  if (params.getBool(QueryElevationParams.EXCLUSIVE, false)) {
    // We only want these elevated results
    rb.setQuery(new BoostQuery(elevation.includeQuery, 0f));
  } else {
    BooleanQuery.Builder queryBuilder = new BooleanQuery.Builder();
    queryBuilder.add(rb.getQuery(), BooleanClause.Occur.SHOULD);
    queryBuilder.add(new BoostQuery(elevation.includeQuery, 0f), BooleanClause.Occur.SHOULD);
    if (elevation.excludeQueries != null) {
      if (params.getBool(QueryElevationParams.MARK_EXCLUDES, false)) {
        // We are only going to mark items as excluded, not actually exclude them.
        // This works with the EditorialMarkerFactory.
        rb.req.getContext().put(EXCLUDED, elevation.excludedIds);
      } else {
        for (TermQuery tq : elevation.excludeQueries) {
          queryBuilder.add(tq, BooleanClause.Occur.MUST_NOT);
        }
      }
    }
    rb.setQuery(queryBuilder.build());
  }
}
 
Example 17
Source Project: lucene-solr   Source File: SolrPluginUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static void flattenBooleanQuery(BooleanQuery.Builder to, BooleanQuery from, float fromBoost) {

    for (BooleanClause clause : from.clauses()) {

      Query cq = clause.getQuery();
      float boost = fromBoost;
      while (cq instanceof BoostQuery) {
        BoostQuery bq = (BoostQuery) cq;
        cq = bq.getQuery();
        boost *= bq.getBoost();
      }

      if (cq instanceof BooleanQuery
          && !clause.isRequired()
          && !clause.isProhibited()) {

        /* we can recurse */
        flattenBooleanQuery(to, (BooleanQuery)cq, boost);

      } else {
        to.add(clause);
      }
    }
  }
 
Example 18
Source Project: crate   Source File: ToMatchQuery.java    License: Apache License 2.0 6 votes vote down vote up
private static Query singleMatchQuery(QueryShardContext queryShardContext,
                                      Map.Entry<String, Object> entry,
                                      String queryString,
                                      String matchType,
                                      Map<String, Object> options) throws IOException {
    Query query = MatchQueries.singleMatch(
        queryShardContext,
        entry.getKey(),
        queryString,
        matchType,
        options
    );
    Object boost = entry.getValue();
    if (boost instanceof Number) {
        return new BoostQuery(query, ((Number) boost).floatValue());
    }
    return query;
}
 
Example 19
Source Project: lucene-solr   Source File: QueryTermExtractor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public QueryVisitor getSubVisitor(BooleanClause.Occur occur, Query parent) {
  if (parent instanceof BoostQuery) {
    float newboost = boost * ((BoostQuery)parent).getBoost();
    return new BoostedTermExtractor(newboost, terms, includeProhibited, fieldSelector);
  }
  if (occur == BooleanClause.Occur.MUST_NOT && includeProhibited == false) {
    return QueryVisitor.EMPTY_VISITOR;
  }
  return this;
}
 
Example 20
Source Project: lucene-solr   Source File: HighlightCustomQueryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void extractUnknownQuery(Query query,
    Map<String, WeightedSpanTerm> terms) throws IOException {
  float boost = 1f;
  while (query instanceof BoostQuery) {
    BoostQuery bq = (BoostQuery) query;
    boost *= bq.getBoost();
    query = bq.getQuery();
  }
  if (query instanceof CustomQuery) {
    extractWeightedTerms(terms, new TermQuery(((CustomQuery) query).term), boost);
  }
}
 
Example 21
public void testPreSpanQueryRewrite() throws IOException {
  indexWriter.addDocument(newDoc("There is no accord and satisfaction with this - Consideration of the accord is arbitrary."));
  initReaderSearcherHighlighter();

  highlighter = new UnifiedHighlighter(searcher, indexAnalyzer) {
    @Override
    protected Set<HighlightFlag> getFlags(String field) {
      final Set<HighlightFlag> flags = super.getFlags(field);
      flags.remove(HighlightFlag.WEIGHT_MATCHES);//unsupported
      return flags;
    }

    @Override
    protected Collection<Query> preSpanQueryRewrite(Query query) {
      if (query instanceof MyQuery) {
        return Collections.singletonList(((MyQuery)query).wrapped);
      }
      return null;
    }
  };
  highlighter.setHighlightPhrasesStrictly(true);

  BooleanQuery.Builder bqBuilder = new BooleanQuery.Builder();
  Query phraseQuery = new BoostQuery(new PhraseQuery("body", "accord", "and", "satisfaction"), 2.0f);
  Query oredTerms = new BooleanQuery.Builder()
      .setMinimumNumberShouldMatch(2)
      .add(new TermQuery(new Term("body", "accord")), BooleanClause.Occur.SHOULD)
      .add(new TermQuery(new Term("body", "satisfaction")), BooleanClause.Occur.SHOULD)
      .add(new TermQuery(new Term("body", "consideration")), BooleanClause.Occur.SHOULD)
      .build();
  Query proximityBoostingQuery = new MyQuery(oredTerms);
  Query totalQuery = bqBuilder
      .add(phraseQuery, BooleanClause.Occur.SHOULD)
      .add(proximityBoostingQuery, BooleanClause.Occur.SHOULD)
      .build();
  TopDocs topDocs = searcher.search(totalQuery, 10, Sort.INDEXORDER);
  assertEquals(1, topDocs.totalHits.value);
  String[] snippets = highlighter.highlight("body", totalQuery, topDocs);
  assertArrayEquals(new String[]{"There is no <b>accord</b> <b>and</b> <b>satisfaction</b> with this - <b>Consideration</b> of the <b>accord</b> is arbitrary."}, snippets);
}
 
Example 22
Source Project: lucene-solr   Source File: TestFunctionScoreExplanations.java    License: Apache License 2.0 5 votes vote down vote up
public void testTopLevelBoost() throws Exception {
  Query q = new TermQuery(new Term(FIELD, "w1"));
  FunctionScoreQuery csq = new FunctionScoreQuery(q, DoubleValuesSource.constant(5));
  BooleanQuery.Builder bqB = new BooleanQuery.Builder();
  bqB.add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
  bqB.add(csq, BooleanClause.Occur.MUST);
  BooleanQuery bq = bqB.build();
  qtest(new BoostQuery(bq, 6), new int[] { 0,1,2,3 });
}
 
Example 23
Source Project: lucene-solr   Source File: TestMoreLikeThis.java    License: Apache License 2.0 5 votes vote down vote up
public void testBoostFactor() throws Throwable {
  Map<String,Float> originalValues = getOriginalValues();
  mlt.setFieldNames(new String[] {"text"});
  mlt.setBoost(true);
  
  // this mean that every term boost factor will be multiplied by this
  // number
  float boostFactor = 5;
  mlt.setBoostFactor(boostFactor);
  
  BooleanQuery query = (BooleanQuery) mlt.like("text", new StringReader(
      "lucene release"));
  Collection<BooleanClause> clauses = query.clauses();
  
  assertEquals("Expected " + originalValues.size() + " clauses.",
      originalValues.size(), clauses.size());

  for (BooleanClause clause : clauses) {
    BoostQuery bq = (BoostQuery) clause.getQuery();
    TermQuery tq = (TermQuery) bq.getQuery();
    Float termBoost = originalValues.get(tq.getTerm().text());
    assertNotNull("Expected term " + tq.getTerm().text(), termBoost);

    float totalBoost = termBoost * boostFactor;
    assertEquals("Expected boost of " + totalBoost + " for term '"
        + tq.getTerm().text() + "' got " + bq.getBoost(), totalBoost, bq
        .getBoost(), 0.0001);
  }
}
 
Example 24
Source Project: lucene-solr   Source File: TestMoreLikeThis.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String,Float> getOriginalValues() throws IOException {
  Map<String,Float> originalValues = new HashMap<>();
  mlt.setFieldNames(new String[] {"text"});
  mlt.setBoost(true);
  BooleanQuery query = (BooleanQuery) mlt.like("text", new StringReader(
      "lucene release"));
  Collection<BooleanClause> clauses = query.clauses();

  for (BooleanClause clause : clauses) {
    BoostQuery bq = (BoostQuery) clause.getQuery();
    TermQuery tq = (TermQuery) bq.getQuery();
    originalValues.put(tq.getTerm().text(), bq.getBoost());
  }
  return originalValues;
}
 
Example 25
public void testSumScoreAggregator() 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 = atLeast(30); i > 0; --i) {
    Document doc = new Document();
    if (random().nextBoolean()) { // don't match all documents
      doc.add(new StringField("f", "v", Field.Store.NO));
    }
    doc.add(new FacetField("dim", "a"));
    iw.addDocument(config.build(taxoWriter, doc));
  }
  
  DirectoryReader r = DirectoryReader.open(iw);
  DirectoryTaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoWriter);
  
  FacetsCollector fc = new FacetsCollector(true);
  BoostQuery csq = new BoostQuery(new ConstantScoreQuery(new MatchAllDocsQuery()), 2f);
  
  TopDocs td = FacetsCollector.search(newSearcher(r), csq, 10, fc);

  Facets facets = new TaxonomyFacetSumValueSource(taxoReader, config, fc, DoubleValuesSource.SCORES);
  
  int expected = (int) (csq.getBoost() * td.totalHits.value);
  assertEquals(expected, facets.getSpecificValue("dim", "a").intValue());

  iw.close();
  IOUtils.close(taxoWriter, taxoReader, taxoDir, r, indexDir);
}
 
Example 26
Source Project: lucene-solr   Source File: QueryDecomposer.java    License: Apache License 2.0 5 votes vote down vote up
public Set<Query> decomposeBoostQuery(BoostQuery q) {
  if (q.getBoost() == 1.0)
    return decompose(q.getQuery());

  Set<Query> boostedDecomposedQueries = new HashSet<>();
  for (Query subq : decompose(q.getQuery())) {
    boostedDecomposedQueries.add(new BoostQuery(subq, q.getBoost()));
  }
  return boostedDecomposedQueries;
}
 
Example 27
Source Project: lucene-solr   Source File: TestExtractors.java    License: Apache License 2.0 5 votes vote down vote up
public void testBoostQueryExtractor() {

    BooleanQuery.Builder bq = new BooleanQuery.Builder();
    bq.add(new TermQuery(new Term("f", "q1")), BooleanClause.Occur.MUST);
    bq.add(new TermQuery(new Term("f", "q2")), BooleanClause.Occur.SHOULD);

    Query boostQuery = new BoostQuery(bq.build(), 0.5f);
    Set<Term> expected = Collections.singleton(new Term("f", "q1"));
    assertEquals(expected, collectTerms(boostQuery));
  }
 
Example 28
Source Project: lucene-solr   Source File: BoostQueryNodeBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Query build(QueryNode queryNode) throws QueryNodeException {
  BoostQueryNode boostNode = (BoostQueryNode) queryNode;
  QueryNode child = boostNode.getChild();

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

  Query query = (Query) child
      .getTag(QueryTreeBuilder.QUERY_TREE_BUILDER_TAGID);

  return new BoostQuery(query, boostNode.getValue());

}
 
Example 29
Source Project: lucene-solr   Source File: QueryBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Builds a new TermQuery instance.
 * <p>
 * This is intended for subclasses that wish to customize the generated queries.
 * @param term term
 * @return new TermQuery instance
 */
protected Query newTermQuery(Term term, float boost) {
  Query q = new TermQuery(term);
  if (boost == DEFAULT_BOOST) {
    return q;
  }
  return new BoostQuery(q, boost);
}
 
Example 30
Source Project: lucene-solr   Source File: FilterQuery.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
  // SolrRequestInfo reqInfo = SolrRequestInfo.getRequestInfo();

  if (!(searcher instanceof SolrIndexSearcher)) {
    // delete-by-query won't have SolrIndexSearcher
    return new BoostQuery(new ConstantScoreQuery(q), 0).createWeight(searcher, scoreMode, 1f);
  }

  SolrIndexSearcher solrSearcher = (SolrIndexSearcher)searcher;
  DocSet docs = solrSearcher.getDocSet(q);
  // reqInfo.addCloseHook(docs);  // needed for off-heap refcounting

  return new BoostQuery(new SolrConstantScoreQuery(docs.getTopFilter()), 0).createWeight(searcher, scoreMode, 1f);
}