org.apache.lucene.search.BoostQuery Java Examples

The following examples show how to use org.apache.lucene.search.BoostQuery. 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: TestQPHelper.java    From lucene-solr with Apache License 2.0 7 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 #2
Source File: TestPrecedenceQueryParser.java    From lucene-solr with 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 #3
Source File: ToMatchQuery.java    From crate with 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 #4
Source File: SolrPluginUtils.java    From lucene-solr with 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 #5
Source File: QueryElevationComponent.java    From lucene-solr with 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 #6
Source File: MoreLikeThisHandler.java    From lucene-solr with 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 #7
Source File: MoreLikeThisHandler.java    From lucene-solr with 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 #8
Source File: TestBooleanSimilarity.java    From lucene-solr with 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 #9
Source File: QueryBuilder.java    From lucene-solr with 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 #10
Source File: QueryParserTestBase.java    From lucene-solr with 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 #11
Source File: QueryParserTestBase.java    From lucene-solr with 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 #12
Source File: UserInputQueryBuilder.java    From lucene-solr with 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 #13
Source File: QueryDecomposer.java    From lucene-solr with 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 #14
Source File: TestFunctionScoreQuery.java    From lucene-solr with 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 #15
Source File: FieldQuery.java    From lucene-solr with 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 #16
Source File: FieldQuery.java    From lucene-solr with 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 #17
Source File: FieldQuery.java    From lucene-solr with 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 #18
Source File: FieldQuery.java    From lucene-solr with 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 #19
Source File: HighlightCustomQueryTest.java    From lucene-solr with 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 #20
Source File: LoggingFetchSubPhase.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
private Tuple<RankerQuery, HitLogConsumer> extractQuery(LoggingSearchExtBuilder.LogSpec logSpec, Map<String, Query> namedQueries) {
    Query q = namedQueries.get(logSpec.getNamedQuery());
    if (q == null) {
        throw new IllegalArgumentException("No query named [" + logSpec.getNamedQuery() + "] found");
    }
    return toLogger(logSpec, inspectQuery(q)
            .orElseThrow(() -> new IllegalArgumentException("Query named [" + logSpec.getNamedQuery() +
                    "] must be a [sltr] query [" +
                    ((q instanceof BoostQuery) ? ((BoostQuery) q).getQuery().getClass().getSimpleName(

                    ) : q.getClass().getSimpleName()) +
                    "] found")));
}
 
Example #21
Source File: TestScoreJoinQPScore.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Ignore("SOLR-7814, also don't forget cover boost at testCacheHit()")
public void testBoost() throws Exception {
  indexDataForScorring();
  ScoreMode score = ScoreMode.values()[random().nextInt(ScoreMode.values().length)];

  final SolrQueryRequest req = req("q", "{!join from=movieId_s to=id score=" + score + " b=200}title:movie", "fl", "id,score", "omitHeader", "true");
  SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, new SolrQueryResponse()));
  final Query luceneQ = QParser.getParser(req.getParams().get("q"), req).getQuery().rewrite(req.getSearcher().getSlowAtomicReader());
  assertTrue(luceneQ instanceof BoostQuery);
  float boost = ((BoostQuery) luceneQ).getBoost();
  assertEquals("" + luceneQ, Float.floatToIntBits(200), Float.floatToIntBits(boost));
  SolrRequestInfo.clearRequestInfo();
  req.close();
}
 
Example #22
Source File: TestSolrQueryParser.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testCSQ() throws Exception {
  SolrQueryRequest req = req();

  QParser qParser = QParser.getParser("text:x^=3", req);
  Query q = qParser.getQuery();
  assertTrue(q instanceof BoostQuery);
  assertTrue(((BoostQuery) q).getQuery() instanceof ConstantScoreQuery);
  assertEquals(3.0, ((BoostQuery) q).getBoost(), 0.0f);

  req.close();
}
 
Example #23
Source File: TestExtendedDismaxParser.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private boolean containsClause(Query query, String field, String value,
                               int boost, boolean fuzzy) {

  float queryBoost = 1f;
  if (query instanceof BoostQuery) {
    BoostQuery bq = (BoostQuery) query;
    query = bq.getQuery();
    queryBoost = bq.getBoost();
  }

  if(query instanceof BooleanQuery) {
    return containsClause((BooleanQuery)query, field, value, boost, fuzzy);
  }
  if(query instanceof DisjunctionMaxQuery) {
    return containsClause((DisjunctionMaxQuery)query, field, value, boost, fuzzy);
  }
  if (boost != queryBoost) {
    return false;
  }
  if(query instanceof TermQuery && !fuzzy) {
    return containsClause((TermQuery)query, field, value);
  }
  if(query instanceof FuzzyQuery && fuzzy) {
    return containsClause((FuzzyQuery)query, field, value);
  }
  return false;
}
 
Example #24
Source File: LoggingFetchSubPhase.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
private Optional<RankerQuery> inspectQuery(Query q) {
    if (q instanceof RankerQuery) {
        return Optional.of((RankerQuery) q);
    } else if (q instanceof BoostQuery && ((BoostQuery) q).getQuery() instanceof RankerQuery) {
        return Optional.of((RankerQuery) ((BoostQuery) q).getQuery());
    }
    return Optional.empty();
}
 
Example #25
Source File: ExtendedDismaxQParser.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Recursively examines the given query list for identical structure in all queries.
 * Boosts on BoostQuery-s are ignored, and the contained queries are instead used as the basis for comparison.
 **/
private boolean allSameQueryStructure(List<Query> lst) {
  boolean allSame = true;
  Query firstQuery = lst.get(0);
  if (firstQuery instanceof BoostQuery) {
    firstQuery = ((BoostQuery)firstQuery).getQuery(); // ignore boost; compare contained query
  }
  for (int n = 1 ; n < lst.size(); ++n) {
    Query nthQuery = lst.get(n);
    if (nthQuery instanceof BoostQuery) {
      nthQuery = ((BoostQuery)nthQuery).getQuery();
    }
    if (nthQuery.getClass() != firstQuery.getClass()) {
      allSame = false;
      break;
    }
    if (firstQuery instanceof BooleanQuery) {
      List<BooleanClause> firstBooleanClauses = ((BooleanQuery)firstQuery).clauses();
      List<BooleanClause> nthBooleanClauses = ((BooleanQuery)nthQuery).clauses();
      if (firstBooleanClauses.size() != nthBooleanClauses.size()) {
        allSame = false;
        break;
      }
      for (int c = 0 ; c < firstBooleanClauses.size() ; ++c) {
        if (nthBooleanClauses.get(c).getQuery().getClass() != firstBooleanClauses.get(c).getQuery().getClass()
            || nthBooleanClauses.get(c).getOccur() != firstBooleanClauses.get(c).getOccur()) {
          allSame = false;
          break;
        }
        if (firstBooleanClauses.get(c).getQuery() instanceof BooleanQuery && ! allSameQueryStructure
            (Arrays.asList(firstBooleanClauses.get(c).getQuery(), nthBooleanClauses.get(c).getQuery()))) {
          allSame = false;
          break;
        }
      }
    }
  }
  return allSame;
}
 
Example #26
Source File: FilterQuery.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 {
  // 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);
}
 
Example #27
Source File: QueryBuilder.java    From lucene-solr with 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 #28
Source File: QueryTermExtractor.java    From lucene-solr with 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 #29
Source File: TestUnifiedHighlighterStrictPhrases.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
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 #30
Source File: BoostQueryNodeBuilder.java    From lucene-solr with 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());

}