org.apache.lucene.search.MultiTermQuery Java Examples

The following examples show how to use org.apache.lucene.search.MultiTermQuery. 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: SpanMultiTermQueryParser.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
    XContentParser parser = parseContext.parser();

    Token token = parser.nextToken();
    if (!MATCH_NAME.equals(parser.currentName()) || token != XContentParser.Token.FIELD_NAME) {
        throw new QueryParsingException(parseContext, "spanMultiTerm must have [" + MATCH_NAME + "] multi term query clause");
    }

    token = parser.nextToken();
    if (token != XContentParser.Token.START_OBJECT) {
        throw new QueryParsingException(parseContext, "spanMultiTerm must have [" + MATCH_NAME + "] multi term query clause");
    }

    Query subQuery = parseContext.parseInnerQuery();
    if (!(subQuery instanceof MultiTermQuery)) {
        throw new QueryParsingException(parseContext, "spanMultiTerm [" + MATCH_NAME + "] must be of type multi term query");
    }

    parser.nextToken();
    return new SpanMultiTermQueryWrapper<>((MultiTermQuery) subQuery);
}
 
Example #2
Source File: MultiTermRewriteMethodProcessor.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
protected QueryNode postProcessNode(QueryNode node) {

  // set setMultiTermRewriteMethod for WildcardQueryNode and
  // PrefixWildcardQueryNode
  if (node instanceof WildcardQueryNode
      || node instanceof AbstractRangeQueryNode || node instanceof RegexpQueryNode) {
    
    MultiTermQuery.RewriteMethod rewriteMethod = getQueryConfigHandler().get(ConfigurationKeys.MULTI_TERM_REWRITE_METHOD);

    if (rewriteMethod == null) {
      // This should not happen, this configuration is set in the
      // StandardQueryConfigHandler
      throw new IllegalArgumentException(
          "StandardQueryConfigHandler.ConfigurationKeys.MULTI_TERM_REWRITE_METHOD should be set on the QueryConfigHandler");
    }

    // use a TAG to take the value to the Builder
    node.setTag(MultiTermRewriteMethodProcessor.TAG_ID, rewriteMethod);

  }

  return node;
}
 
Example #3
Source File: HighlighterTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testGetBestFragmentsMultiTerm() throws Exception {
  TestHighlightRunner helper = new TestHighlightRunner() {

    @Override
    public void run() throws Exception {
      numHighlights = 0;
      BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder();
      booleanQuery.add(new TermQuery(new Term(FIELD_NAME, "john")), Occur.SHOULD);
      PrefixQuery prefixQuery = new PrefixQuery(new Term(FIELD_NAME, "kenn"));
      prefixQuery.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
      booleanQuery.add(prefixQuery, Occur.SHOULD);

      doSearching(booleanQuery.build());
      doStandardHighlights(analyzer, searcher, hits, query, HighlighterTest.this);
      assertTrue("Failed to find correct number of highlights " + numHighlights + " found",
          numHighlights == 5);
    }
  };

  helper.start();
}
 
Example #4
Source File: HighlighterTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testGetMidWildCardFragments() throws Exception {
  TestHighlightRunner helper = new TestHighlightRunner() {

    @Override
    public void run() throws Exception {
      numHighlights = 0;
      WildcardQuery wildcardQuery = new WildcardQuery(new Term(FIELD_NAME, "k*dy"));
      wildcardQuery.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
      doSearching(wildcardQuery);
      doStandardHighlights(analyzer, searcher, hits, query, HighlighterTest.this);
      assertTrue("Failed to find correct number of highlights " + numHighlights + " found",
          numHighlights == 5);
    }
  };

  helper.start();
}
 
Example #5
Source File: HighlighterTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testGetWildCardFragments() throws Exception {
  TestHighlightRunner helper = new TestHighlightRunner() {

    @Override
    public void run() throws Exception {
      numHighlights = 0;
      WildcardQuery wildcardQuery = new WildcardQuery(new Term(FIELD_NAME, "k?nnedy"));
      wildcardQuery.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
      doSearching(wildcardQuery);
      doStandardHighlights(analyzer, searcher, hits, query, HighlighterTest.this);
      assertTrue("Failed to find correct number of highlights " + numHighlights + " found",
          numHighlights == 4);
    }
  };

  helper.start();
}
 
Example #6
Source File: HighlighterTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testGetFuzzyFragments() throws Exception {
  TestHighlightRunner helper = new TestHighlightRunner() {

    @Override
    public void run() throws Exception {
      numHighlights = 0;
      FuzzyQuery fuzzyQuery = new FuzzyQuery(new Term(FIELD_NAME, "kinnedy"), 2);
      fuzzyQuery.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
      doSearching(fuzzyQuery);
      doStandardHighlights(analyzer, searcher, hits, query, HighlighterTest.this, true);
      assertTrue("Failed to find correct number of highlights " + numHighlights + " found",
          numHighlights == 4);
    }
  };

  helper.start();
}
 
Example #7
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 #8
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 #9
Source File: StandardQueryConfigHandler.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public StandardQueryConfigHandler() {
  // Add listener that will build the FieldConfig.
  addFieldConfigListener(new FieldBoostMapFCListener(this));
  addFieldConfigListener(new FieldDateResolutionFCListener(this));
  addFieldConfigListener(new PointsConfigListener(this));
  
  // Default Values
  set(ConfigurationKeys.ALLOW_LEADING_WILDCARD, false); // default in 2.9
  set(ConfigurationKeys.ANALYZER, null); //default value 2.4
  set(ConfigurationKeys.DEFAULT_OPERATOR, Operator.OR);
  set(ConfigurationKeys.PHRASE_SLOP, 0); //default value 2.4
  set(ConfigurationKeys.ENABLE_POSITION_INCREMENTS, false); //default value 2.4
  set(ConfigurationKeys.FIELD_BOOST_MAP, new LinkedHashMap<String, Float>());
  set(ConfigurationKeys.FUZZY_CONFIG, new FuzzyConfig());
  set(ConfigurationKeys.LOCALE, Locale.getDefault());
  set(ConfigurationKeys.MULTI_TERM_REWRITE_METHOD, MultiTermQuery.CONSTANT_SCORE_REWRITE);
  set(ConfigurationKeys.FIELD_DATE_RESOLUTION_MAP, new HashMap<CharSequence, DateTools.Resolution>());
  
}
 
Example #10
Source File: RegexpQueryNodeBuilder.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public RegexpQuery build(QueryNode queryNode) throws QueryNodeException {
  RegexpQueryNode regexpNode = (RegexpQueryNode) queryNode;

  // TODO: make the maxStates configurable w/ a reasonable default (QueryParserBase uses 10000)
  RegexpQuery q = new RegexpQuery(new Term(regexpNode.getFieldAsString(),
      regexpNode.textToBytesRef()));

  MultiTermQuery.RewriteMethod method = (MultiTermQuery.RewriteMethod) queryNode
      .getTag(MultiTermRewriteMethodProcessor.TAG_ID);
  if (method != null) {
    q.setRewriteMethod(method);
  }

  return q;
}
 
Example #11
Source File: TestQPHelper.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testRange() throws Exception {
  assertQueryEquals("[ a TO z]", null, "[a TO z]");
  assertEquals(MultiTermQuery.CONSTANT_SCORE_REWRITE, ((TermRangeQuery)getQuery("[ a TO z]", null)).getRewriteMethod());

  StandardQueryParser qp = new StandardQueryParser();
  
  qp.setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
  assertEquals(MultiTermQuery.SCORING_BOOLEAN_REWRITE,((TermRangeQuery)qp.parse("[ a TO z]", "field")).getRewriteMethod());

  // test open ranges
  assertQueryEquals("[ a TO * ]", null, "[a TO *]");
  assertQueryEquals("[ * TO z ]", null, "[* TO z]");
  assertQueryEquals("[ * TO * ]", null, "[* TO *]");
  
  assertQueryEquals("field>=a", null, "[a TO *]");
  assertQueryEquals("field>a", null, "{a TO *]");
  assertQueryEquals("field<=a", null, "[* TO a]");
  assertQueryEquals("field<a", null, "[* TO a}");
  
  // mixing exclude and include bounds
  assertQueryEquals("{ a TO z ]", null, "{a TO z]");
  assertQueryEquals("[ a TO z }", null, "[a TO z}");
  assertQueryEquals("{ a TO * ]", null, "{a TO *]");
  assertQueryEquals("[ * TO z }", null, "[* TO z}");
  
  assertQueryEquals("[ a TO z ]", null, "[a TO z]");
  assertQueryEquals("{ a TO z}", null, "{a TO z}");
  assertQueryEquals("{ a TO z }", null, "{a TO z}");
  assertQueryEquals("{ a TO z }^2.0", null, "({a TO z})^2.0");
  assertQueryEquals("[ a TO z] OR bar", null, "[a TO z] bar");
  assertQueryEquals("[ a TO z] AND bar", null, "+[a TO z] +bar");
  assertQueryEquals("( bar blar { a TO z}) ", null, "bar blar {a TO z}");
  assertQueryEquals("gack ( bar blar { a TO z}) ", null,
      "gack (bar blar {a TO z})");
}
 
Example #12
Source File: HighlighterTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testGetRangeFragments() throws Exception {
  TestHighlightRunner helper = new TestHighlightRunner() {

    @Override
    public void run() throws Exception {
      numHighlights = 0;

      // Need to explicitly set the QueryParser property to use TermRangeQuery
      // rather
      // than RangeFilters

      TermRangeQuery rangeQuery = new TermRangeQuery(
          FIELD_NAME,
          new BytesRef("kannedy"),
          new BytesRef("kznnedy"),
          true, true);
      rangeQuery.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);

      query = rangeQuery;
      doSearching(query);

      doStandardHighlights(analyzer, searcher, hits, query, HighlighterTest.this);
      assertTrue("Failed to find correct number of highlights " + numHighlights + " found",
          numHighlights == 5);
    }
  };

  helper.start();
}
 
Example #13
Source File: TestQPHelper.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testConstantScoreAutoRewrite() throws Exception {
  StandardQueryParser qp = new StandardQueryParser(new MockAnalyzer(random(), MockTokenizer.WHITESPACE, false));
  Query q = qp.parse("foo*bar", "field");
  assertTrue(q instanceof WildcardQuery);
  assertEquals(MultiTermQuery.CONSTANT_SCORE_REWRITE, ((MultiTermQuery) q).getRewriteMethod());

  q = qp.parse("foo*", "field");
  assertTrue(q instanceof PrefixQuery);
  assertEquals(MultiTermQuery.CONSTANT_SCORE_REWRITE, ((MultiTermQuery) q).getRewriteMethod());

  q = qp.parse("[a TO z]", "field");
  assertTrue(q instanceof TermRangeQuery);
  assertEquals(MultiTermQuery.CONSTANT_SCORE_REWRITE, ((MultiTermQuery) q).getRewriteMethod());
}
 
Example #14
Source File: TermRangeQueryNodeBuilder.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public TermRangeQuery build(QueryNode queryNode) throws QueryNodeException {
  TermRangeQueryNode rangeNode = (TermRangeQueryNode) queryNode;
  FieldQueryNode upper = rangeNode.getUpperBound();
  FieldQueryNode lower = rangeNode.getLowerBound();
  
  String field = StringUtils.toString(rangeNode.getField());
  String lowerText = lower.getTextAsString();
  String upperText = upper.getTextAsString();
  
  if (lowerText.length() == 0) {
    lowerText = null;
  }
  
  if (upperText.length() == 0) {
    upperText = null;
  }
  
  TermRangeQuery rangeQuery = TermRangeQuery.newStringRange(field, lowerText, upperText, rangeNode
      .isLowerInclusive(), rangeNode.isUpperInclusive());
  
  MultiTermQuery.RewriteMethod method = (MultiTermQuery.RewriteMethod) queryNode
      .getTag(MultiTermRewriteMethodProcessor.TAG_ID);
  if (method != null) {
    rangeQuery.setRewriteMethod(method);
  }
  
  return rangeQuery;
  
}
 
Example #15
Source File: WildcardQueryNodeBuilder.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public WildcardQuery build(QueryNode queryNode) throws QueryNodeException {
  WildcardQueryNode wildcardNode = (WildcardQueryNode) queryNode;

  WildcardQuery q = new WildcardQuery(new Term(wildcardNode.getFieldAsString(),
                                               wildcardNode.getTextAsString()));
  
  MultiTermQuery.RewriteMethod method = (MultiTermQuery.RewriteMethod)queryNode.getTag(MultiTermRewriteMethodProcessor.TAG_ID);
  if (method != null) {
    q.setRewriteMethod(method);
  }
  
  return q;
}
 
Example #16
Source File: PrefixWildcardQueryNodeBuilder.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public PrefixQuery build(QueryNode queryNode) throws QueryNodeException {    

  PrefixWildcardQueryNode wildcardNode = (PrefixWildcardQueryNode) queryNode;

  String text = wildcardNode.getText().subSequence(0, wildcardNode.getText().length() - 1).toString();
  PrefixQuery q = new PrefixQuery(new Term(wildcardNode.getFieldAsString(), text));
  
  MultiTermQuery.RewriteMethod method = (MultiTermQuery.RewriteMethod)queryNode.getTag(MultiTermRewriteMethodProcessor.TAG_ID);
  if (method != null) {
    q.setRewriteMethod(method);
  }
  
  return q;
}
 
Example #17
Source File: QueryParserTestBase.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testRange() throws Exception {
   assertQueryEquals("[ a TO z]", null, "[a TO z]");
   assertQueryEquals("[ a TO z}", null, "[a TO z}");
   assertQueryEquals("{ a TO z]", null, "{a TO z]"); 

    assertEquals(MultiTermQuery.CONSTANT_SCORE_REWRITE, ((TermRangeQuery)getQuery("[ a TO z]")).getRewriteMethod());

   CommonQueryParserConfiguration qp = getParserConfig( new MockAnalyzer(random(), MockTokenizer.SIMPLE, true));
   
   qp.setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
   assertEquals(MultiTermQuery.SCORING_BOOLEAN_REWRITE,((TermRangeQuery)getQuery("[ a TO z]", qp)).getRewriteMethod());
   
   // test open ranges
   assertQueryEquals("[ a TO * ]", null, "[a TO *]");
   assertQueryEquals("[ * TO z ]", null, "[* TO z]");
   assertQueryEquals("[ * TO * ]", null, "[* TO *]");
   
   // mixing exclude and include bounds
   assertQueryEquals("{ a TO z ]", null, "{a TO z]");
   assertQueryEquals("[ a TO z }", null, "[a TO z}");
   assertQueryEquals("{ a TO * ]", null, "{a TO *]");
   assertQueryEquals("[ * TO z }", null, "[* TO z}");
   
   assertQueryEquals("[ a TO z ]", null, "[a TO z]");
   assertQueryEquals("{ a TO z}", null, "{a TO z}");
   assertQueryEquals("{ a TO z }", null, "{a TO z}");
   assertQueryEquals("{ a TO z }^2.0", null, "({a TO z})^2.0");
   assertQueryEquals("[ a TO z] OR bar", null, "[a TO z] bar");
   assertQueryEquals("[ a TO z] AND bar", null, "+[a TO z] +bar");
   assertQueryEquals("( bar blar { a TO z}) ", null, "bar blar {a TO z}");
   assertQueryEquals("gack ( bar blar { a TO z}) ", null, "gack (bar blar {a TO z})");

   assertQueryEquals("[* TO Z]",null,"[* TO z]");
   assertQueryEquals("[A TO *]",null,"[a TO *]");
   assertQueryEquals("[* TO *]",null,"[* TO *]");
}
 
Example #18
Source File: SpanMultiTermQueryWrapper.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static SpanRewriteMethod selectRewriteMethod(MultiTermQuery query) {
  MultiTermQuery.RewriteMethod method = query.getRewriteMethod();
  if (method instanceof TopTermsRewrite) {
    final int pqsize = ((TopTermsRewrite) method).getSize();
    return new TopTermsSpanBooleanQueryRewrite(pqsize);
  } else {
    return SCORING_SPAN_QUERY_REWRITE;
  }
}
 
Example #19
Source File: ComplexPhraseQueryParser.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
protected Query newRangeQuery(String field, String part1, String part2,
    boolean startInclusive, boolean endInclusive) {
  RewriteMethod originalRewriteMethod = getMultiTermRewriteMethod();
  try {
    if (isPass2ResolvingPhrases) {
      setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_REWRITE);
    }
    return super.newRangeQuery(field, part1, part2, startInclusive, endInclusive);
  } finally {
    setMultiTermRewriteMethod(originalRewriteMethod);
  }
}
 
Example #20
Source File: EnwikiQueryMaker.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static Query[] getPrebuiltQueries(String field) {
  WildcardQuery wcq = new WildcardQuery(new Term(field, "fo*"));
  wcq .setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_REWRITE);
  // be wary of unanalyzed text
  return new Query[] {
      new SpanFirstQuery(new SpanTermQuery(new Term(field, "ford")), 5),
      new SpanNearQuery(new SpanQuery[] {
          new SpanTermQuery(new Term(field, "night")),
          new SpanTermQuery(new Term(field, "trading")) }, 4, false),
      new SpanNearQuery(new SpanQuery[] {
          new SpanFirstQuery(new SpanTermQuery(new Term(field, "ford")), 10),
          new SpanTermQuery(new Term(field, "credit")) }, 10, false), wcq, };
}
 
Example #21
Source File: HighlighterTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testNotRewriteMultiTermQuery() throws IOException {
  // field "bar": (not the field we ultimately want to extract)
  MultiTermQuery mtq = new TermRangeQuery("bar", new BytesRef("aa"), new BytesRef("zz"), true, true) ;
  WeightedSpanTermExtractor extractor = new WeightedSpanTermExtractor() {
    @Override
    protected void extract(Query query, float boost, Map<String, WeightedSpanTerm> terms) throws IOException {
      assertEquals(mtq, query);
      super.extract(query, boost, terms);
    }
  };
  extractor.setExpandMultiTermQuery(true);
  extractor.setMaxDocCharsToAnalyze(51200);
  extractor.getWeightedSpanTerms(
      mtq, 3, new CannedTokenStream(new Token("aa",0,2), new Token("bb", 2,4)), "foo"); // field "foo"
}
 
Example #22
Source File: QueryParsers.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public static MultiTermQuery.RewriteMethod parseRewriteMethod(ParseFieldMatcher matcher, @Nullable String rewriteMethod, @Nullable MultiTermQuery.RewriteMethod defaultRewriteMethod) {
    if (rewriteMethod == null) {
        return defaultRewriteMethod;
    }
    if (matcher.match(rewriteMethod, CONSTANT_SCORE)) {
        return MultiTermQuery.CONSTANT_SCORE_REWRITE;
    }
    if (matcher.match(rewriteMethod, SCORING_BOOLEAN)) {
        return MultiTermQuery.SCORING_BOOLEAN_REWRITE;
    }
    if (matcher.match(rewriteMethod, CONSTANT_SCORE_BOOLEAN)) {
        return MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE;
    }

    int firstDigit = -1;
    for (int i = 0; i < rewriteMethod.length(); ++i) {
        if (Character.isDigit(rewriteMethod.charAt(i))) {
            firstDigit = i;
            break;
        }
    }

    if (firstDigit >= 0) {
        final int size = Integer.parseInt(rewriteMethod.substring(firstDigit));
        String rewriteMethodName = rewriteMethod.substring(0, firstDigit);

        if (matcher.match(rewriteMethodName, TOP_TERMS)) {
            return new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(size);
        }
        if (matcher.match(rewriteMethodName, TOP_TERMS_BOOST)) {
            return new MultiTermQuery.TopTermsBoostOnlyBooleanQueryRewrite(size);
        }
        if (matcher.match(rewriteMethodName, TOP_TERMS_BLENDED_FREQS)) {
            return new MultiTermQuery.TopTermsBlendedFreqScoringRewrite(size);
        }
    }

    throw new IllegalArgumentException("Failed to parse rewrite_method [" + rewriteMethod + "]");
}
 
Example #23
Source File: TestNumericRangeQuery64.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/** test for constant score + boolean query + filter, the other tests only use the constant score mode */
private void testRange(int precisionStep) throws Exception {
  String field="field"+precisionStep;
  int count=3000;
  long lower=(distance*3/2)+startOffset, upper=lower + count*distance + (distance/3);
  LegacyNumericRangeQuery<Long> q = LegacyNumericRangeQuery.newLongRange(field, precisionStep, lower, upper, true, true);
  for (byte i=0; i<2; i++) {
    TopFieldCollector collector = TopFieldCollector.create(Sort.INDEXORDER, noDocs, Integer.MAX_VALUE);
    String type;
    switch (i) {
      case 0:
        type = " (constant score filter rewrite)";
        q.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_REWRITE);
        break;
      case 1:
        type = " (constant score boolean rewrite)";
        q.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE);
        break;
      default:
        return;
    }
    searcher.search(q, collector);
    TopDocs topDocs = collector.topDocs();
    ScoreDoc[] sd = topDocs.scoreDocs;
    assertNotNull(sd);
    assertEquals("Score doc count"+type, count, sd.length );
    Document doc=searcher.doc(sd[0].doc);
    assertEquals("First doc"+type, 2*distance+startOffset, doc.getField(field).numericValue().longValue() );
    doc=searcher.doc(sd[sd.length-1].doc);
    assertEquals("Last doc"+type, (1+count)*distance+startOffset, doc.getField(field).numericValue().longValue() );
  }
}
 
Example #24
Source File: TestNumericRangeQuery32.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/** test for both constant score and boolean query, the other tests only use the constant score mode */
private void testRange(int precisionStep) throws Exception {
  String field="field"+precisionStep;
  int count=3000;
  int lower=(distance*3/2)+startOffset, upper=lower + count*distance + (distance/3);
  LegacyNumericRangeQuery<Integer> q = LegacyNumericRangeQuery.newIntRange(field, precisionStep, lower, upper, true, true);
  for (byte i=0; i<2; i++) {
    TopFieldCollector collector = TopFieldCollector.create(Sort.INDEXORDER, noDocs, Integer.MAX_VALUE);
    String type;
    switch (i) {
      case 0:
        type = " (constant score filter rewrite)";
        q.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_REWRITE);
        break;
      case 1:
        type = " (constant score boolean rewrite)";
        q.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE);
        break;
      default:
        return;
    }
    searcher.search(q, collector);
    TopDocs topDocs = collector.topDocs();
    ScoreDoc[] sd = topDocs.scoreDocs;
    assertNotNull(sd);
    assertEquals("Score doc count"+type, count, sd.length );
    Document doc=searcher.doc(sd[0].doc);
    assertEquals("First doc"+type, 2*distance+startOffset, doc.getField(field).numericValue().intValue());
    doc=searcher.doc(sd[sd.length-1].doc);
    assertEquals("Last doc"+type, (1+count)*distance+startOffset, doc.getField(field).numericValue().intValue());
  }
}
 
Example #25
Source File: FieldType.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Expert: Returns the rewrite method for multiterm queries such as wildcards.
 * @param parser The {@link org.apache.solr.search.QParser} calling the method
 * @param field The {@link org.apache.solr.schema.SchemaField} of the field to search
 * @return A suitable rewrite method for rewriting multi-term queries to primitive queries.
 */
public MultiTermQuery.RewriteMethod getRewriteMethod(QParser parser, SchemaField field) {
  if (!field.indexed() && field.hasDocValues()) {
    return new DocValuesRewriteMethod();
  } else {
    return MultiTermQuery.CONSTANT_SCORE_REWRITE;
  }
}
 
Example #26
Source File: StringFieldType.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public Query prefixQuery(String value, MultiTermQuery.RewriteMethod method, QueryShardContext context) {
    failIfNotIndexed();
    PrefixQuery query = new PrefixQuery(new Term(name(), indexedValueForSearch(value)));
    if (method != null) {
        query.setRewriteMethod(method);
    }
    return query;
}
 
Example #27
Source File: TextFieldMapper.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public Query prefixQuery(String value, MultiTermQuery.RewriteMethod method, QueryShardContext context) {
    if (prefixFieldType == null || prefixFieldType.accept(value.length()) == false) {
        return super.prefixQuery(value, method, context);
    }
    Query tq = prefixFieldType.termQuery(value, context);
    if (method == null || method == MultiTermQuery.CONSTANT_SCORE_REWRITE
        || method == MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE) {
        return new ConstantScoreQuery(tq);
    }
    return tq;
}
 
Example #28
Source File: TestSpanMultiTermQueryWrapper.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrappedQueryIsNotModified() {
  final PrefixQuery pq = new PrefixQuery(new Term("field", "test"));
  int pqHash = pq.hashCode();
  SpanMultiTermQueryWrapper<PrefixQuery> wrapper = new SpanMultiTermQueryWrapper<>(pq);
  assertEquals(pqHash, pq.hashCode());
  wrapper.setRewriteMethod(new SpanMultiTermQueryWrapper.SpanRewriteMethod() {
    @Override
    public SpanQuery rewrite(IndexReader reader, MultiTermQuery query) throws IOException {
      return null;
    }
  });
  assertEquals(pqHash, pq.hashCode());
}
 
Example #29
Source File: QueryParsers.java    From crate with Apache License 2.0 4 votes vote down vote up
public static void setRewriteMethod(MultiTermQuery query, @Nullable MultiTermQuery.RewriteMethod rewriteMethod) {
    if (rewriteMethod == null) {
        return;
    }
    query.setRewriteMethod(rewriteMethod);
}
 
Example #30
Source File: SolrQueryParserBase.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/**
 * @see #setMultiTermRewriteMethod
 */
public MultiTermQuery.RewriteMethod getMultiTermRewriteMethod() {
  return multiTermRewriteMethod;
}