org.apache.lucene.search.MatchNoDocsQuery Java Examples

The following examples show how to use org.apache.lucene.search.MatchNoDocsQuery. 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: SimpleQueryParser.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/** Parses the query text and returns parsed query */
public Query parse(String queryText) {
  if ("*".equals(queryText.trim())) {
    return new MatchAllDocsQuery();
  }

  char data[] = queryText.toCharArray();
  char buffer[] = new char[data.length];

  State state = new State(data, buffer, 0, data.length);
  parseSubQuery(state);
  if (state.top == null) {
    return new MatchNoDocsQuery("empty string passed to query parser");
  } else {
    return state.top;
  }
}
 
Example #2
Source File: DatePointField.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Query getPointRangeQuery(QParser parser, SchemaField field, String min, String max, boolean minInclusive, boolean maxInclusive) {
  long actualMin, actualMax;
  if (min == null) {
    actualMin = Long.MIN_VALUE;
  } else {
    actualMin = DateMathParser.parseMath(null, min).getTime();
    if (!minInclusive) {
      if (actualMin == Long.MAX_VALUE) return new MatchNoDocsQuery();
      actualMin++;
    }
  }
  if (max == null) {
    actualMax = Long.MAX_VALUE;
  } else {
    actualMax = DateMathParser.parseMath(null, max).getTime();
    if (!maxInclusive) {
      if (actualMax == Long.MIN_VALUE) return new MatchNoDocsQuery();
      actualMax--;
    }
  }
  return LongPoint.newRangeQuery(field.getName(), actualMin, actualMax);
}
 
Example #3
Source File: FloatPointField.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Query getPointRangeQuery(QParser parser, SchemaField field, String min, String max, boolean minInclusive,
    boolean maxInclusive) {
  float actualMin, actualMax;
  if (min == null) {
    actualMin = Float.NEGATIVE_INFINITY;
  } else {
    actualMin = parseFloatFromUser(field.getName(), min);
    if (!minInclusive) {
      if (actualMin == Float.POSITIVE_INFINITY) return new MatchNoDocsQuery();
      actualMin = FloatPoint.nextUp(actualMin);
    }
  }
  if (max == null) {
    actualMax = Float.POSITIVE_INFINITY;
  } else {
    actualMax = parseFloatFromUser(field.getName(), max);
    if (!maxInclusive) {
      if (actualMax == Float.NEGATIVE_INFINITY) return new MatchNoDocsQuery();
      actualMax = FloatPoint.nextDown(actualMax);
    }
  }
  return FloatPoint.newRangeQuery(field.getName(), actualMin, actualMax);
}
 
Example #4
Source File: IntPointField.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Query getPointRangeQuery(QParser parser, SchemaField field, String min, String max, boolean minInclusive,
    boolean maxInclusive) {
  int actualMin, actualMax;
  if (min == null) {
    actualMin = Integer.MIN_VALUE;
  } else {
    actualMin = parseIntFromUser(field.getName(), min);
    if (!minInclusive) {
      if (actualMin == Integer.MAX_VALUE) return new MatchNoDocsQuery();
      actualMin++;
    }
  }
  if (max == null) {
    actualMax = Integer.MAX_VALUE;
  } else {
    actualMax = parseIntFromUser(field.getName(), max);
    if (!maxInclusive) {
      if (actualMax == Integer.MIN_VALUE) return new MatchNoDocsQuery();
      actualMax--;
    }
  }
  return IntPoint.newRangeQuery(field.getName(), actualMin, actualMax);
}
 
Example #5
Source File: LatLonDocValuesField.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Create a query for matching a bounding box using doc values.
 * This query is usually slow as it does not use an index structure and needs
 * to verify documents one-by-one in order to know whether they match. It is
 * best used wrapped in an {@link IndexOrDocValuesQuery} alongside a
 * {@link LatLonPoint#newBoxQuery}.
 */
public static Query newSlowBoxQuery(String field, double minLatitude, double maxLatitude, double minLongitude, double maxLongitude) {
  // exact double values of lat=90.0D and lon=180.0D must be treated special as they are not represented in the encoding
  // and should not drag in extra bogus junk! TODO: should encodeCeil just throw ArithmeticException to be less trappy here?
  if (minLatitude == 90.0) {
    // range cannot match as 90.0 can never exist
    return new MatchNoDocsQuery("LatLonDocValuesField.newBoxQuery with minLatitude=90.0");
  }
  if (minLongitude == 180.0) {
    if (maxLongitude == 180.0) {
      // range cannot match as 180.0 can never exist
      return new MatchNoDocsQuery("LatLonDocValuesField.newBoxQuery with minLongitude=maxLongitude=180.0");
    } else if (maxLongitude < minLongitude) {
      // encodeCeil() with dateline wrapping!
      minLongitude = -180.0;
    }
  }
  return new LatLonDocValuesBoxQuery(field, minLatitude, maxLatitude, minLongitude, maxLongitude);
}
 
Example #6
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 #7
Source File: NumericFieldType.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected Query getRangeQueryForMultiValuedDoubleDocValues(SchemaField sf, String min, String max, boolean minInclusive, boolean maxInclusive) {
  double minVal,maxVal;
  if (min == null) {
    minVal = Double.NEGATIVE_INFINITY;
  } else {
    minVal = parseDoubleFromUser(sf.getName(), min);
    if (!minInclusive) {
      if (minVal == Double.POSITIVE_INFINITY) return new MatchNoDocsQuery();
      minVal = DoublePoint.nextUp(minVal);
    }
  }
  if (max == null) {
    maxVal = Double.POSITIVE_INFINITY;
  } else {
    maxVal = parseDoubleFromUser(sf.getName(), max);
    if (!maxInclusive) {
      if (maxVal == Double.NEGATIVE_INFINITY) return new MatchNoDocsQuery();
      maxVal = DoublePoint.nextDown(maxVal);
    }
  }
  Long minBits = NumericUtils.doubleToSortableLong(minVal);
  Long maxBits = NumericUtils.doubleToSortableLong(maxVal);
  return numericDocValuesRangeQuery(sf.getName(), minBits, maxBits, true, true, true);
}
 
Example #8
Source File: NumericFieldType.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected Query getRangeQueryForMultiValuedFloatDocValues(SchemaField sf, String min, String max, boolean minInclusive, boolean maxInclusive) {
  float minVal,maxVal;
  if (min == null) {
    minVal = Float.NEGATIVE_INFINITY;
  } else {
    minVal = parseFloatFromUser(sf.getName(), min);
    if (!minInclusive) {
      if (minVal == Float.POSITIVE_INFINITY) return new MatchNoDocsQuery();
      minVal = FloatPoint.nextUp(minVal);
    }
  }
  if (max == null) {
    maxVal = Float.POSITIVE_INFINITY;
  } else {
    maxVal = parseFloatFromUser(sf.getName(), max);
    if (!maxInclusive) {
      if (maxVal == Float.NEGATIVE_INFINITY) return new MatchNoDocsQuery();
      maxVal = FloatPoint.nextDown(maxVal);
    }
  }
  Long minBits = (long)NumericUtils.floatToSortableInt(minVal);
  Long maxBits = (long)NumericUtils.floatToSortableInt(maxVal);
  return numericDocValuesRangeQuery(sf.getName(), minBits, maxBits, true, true, true);
}
 
Example #9
Source File: LongPointField.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Query getPointRangeQuery(QParser parser, SchemaField field, String min, String max, boolean minInclusive,
    boolean maxInclusive) {
  long actualMin, actualMax;
  if (min == null) {
    actualMin = Long.MIN_VALUE;
  } else {
    actualMin = parseLongFromUser(field.getName(), min);
    if (!minInclusive) {
      if (actualMin == Long.MAX_VALUE) return new MatchNoDocsQuery();
      actualMin++;
    }
  }
  if (max == null) {
    actualMax = Long.MAX_VALUE;
  } else {
    actualMax = parseLongFromUser(field.getName(), max);
    if (!maxInclusive) {
      if (actualMax == Long.MIN_VALUE) return new MatchNoDocsQuery();
      actualMax--;
    }
  }
  return LongPoint.newRangeQuery(field.getName(), actualMin, actualMax);
}
 
Example #10
Source File: DoublePointField.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Query getPointRangeQuery(QParser parser, SchemaField field, String min, String max, boolean minInclusive,
    boolean maxInclusive) {
  double actualMin, actualMax;
  if (min == null) {
    actualMin = Double.NEGATIVE_INFINITY;
  } else {
    actualMin = parseDoubleFromUser(field.getName(), min);
    if (!minInclusive) {
      if (actualMin == Double.POSITIVE_INFINITY) return new MatchNoDocsQuery();
      actualMin = DoublePoint.nextUp(actualMin);
    }
  }
  if (max == null) {
    actualMax = Double.POSITIVE_INFINITY;
  } else {
    actualMax = parseDoubleFromUser(field.getName(), max);
    if (!maxInclusive) {
      if (actualMax == Double.NEGATIVE_INFINITY) return new MatchNoDocsQuery();
      actualMax = DoublePoint.nextDown(actualMax);
    }
  }
  return DoublePoint.newRangeQuery(field.getName(), actualMin, actualMax);
}
 
Example #11
Source File: SimpleTermRewriteQuery.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Query rewrite(IndexReader reader) throws IOException {
  final List<Query> luceneSubQueries = new ArrayList<>();
  srndQuery.visitMatchingTerms(reader, fieldName,
  new SimpleTerm.MatchingTermVisitor() {
    @Override
    public void visitMatchingTerm(Term term) throws IOException {
      luceneSubQueries.add(qf.newTermQuery(term));
    }
  });
  return  (luceneSubQueries.size() == 0) ? new MatchNoDocsQuery()
  : (luceneSubQueries.size() == 1) ? luceneSubQueries.get(0)
  : SrndBooleanQuery.makeBooleanQuery(
    /* luceneSubQueries all have default weight */
    luceneSubQueries, BooleanClause.Occur.SHOULD); /* OR the subquery terms */
}
 
Example #12
Source File: DistanceQuery.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public Query getSpanNearQuery(
        IndexReader reader,
        String fieldName,
        BasicQueryFactory qf) throws IOException {
  SpanQuery[] spanClauses = new SpanQuery[getNrSubQueries()];
  Iterator<?> sqi = getSubQueriesIterator();
  int qi = 0;
  while (sqi.hasNext()) {
    SpanNearClauseFactory sncf = new SpanNearClauseFactory(reader, fieldName, qf);
    
    ((DistanceSubQuery)sqi.next()).addSpanQueries(sncf);
    if (sncf.size() == 0) { /* distance operator requires all sub queries */
      while (sqi.hasNext()) { /* produce evt. error messages but ignore results */
        ((DistanceSubQuery)sqi.next()).addSpanQueries(sncf);
        sncf.clear();
      }
      return new MatchNoDocsQuery();
    }
    
    spanClauses[qi] = sncf.makeSpanClause();
    qi++;
  }

  return new SpanNearQuery(spanClauses, getOpDistance() - 1, subQueriesOrdered());
}
 
Example #13
Source File: TestCheckJoinIndex.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testNoParent() throws IOException {
  final Directory dir = newDirectory();
  final RandomIndexWriter w = new RandomIndexWriter(random(), dir);
  final int numDocs = TestUtil.nextInt(random(), 1, 3);
  for (int i = 0; i < numDocs; ++i) {
    w.addDocument(new Document());
  }
  final IndexReader reader = w.getReader();
  w.close();
  BitSetProducer parentsFilter = new QueryBitSetProducer(new MatchNoDocsQuery());
  try {
    expectThrows(IllegalStateException.class, () -> CheckJoinIndex.check(reader, parentsFilter));
  } finally {
    reader.close();
    dir.close();
  }
}
 
Example #14
Source File: TestQueryBitSetProducer.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testReaderNotSuitedForCaching() throws IOException{
  Directory dir = newDirectory();
  IndexWriterConfig iwc = newIndexWriterConfig().setMergePolicy(NoMergePolicy.INSTANCE);
  RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
  w.addDocument(new Document());
  DirectoryReader reader = new DummyDirectoryReader(w.getReader());

  QueryBitSetProducer producer = new QueryBitSetProducer(new MatchNoDocsQuery());
  assertNull(producer.getBitSet(reader.leaves().get(0)));
  assertEquals(0, producer.cache.size());

  producer = new QueryBitSetProducer(new MatchAllDocsQuery());
  BitSet bitSet = producer.getBitSet(reader.leaves().get(0));
  assertEquals(1, bitSet.length());
  assertEquals(true, bitSet.get(0));
  assertEquals(0, producer.cache.size());

  IOUtils.close(reader, w, dir);
}
 
Example #15
Source File: TestQueryBitSetProducer.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testSimple() throws Exception {
  Directory dir = newDirectory();
  IndexWriterConfig iwc = newIndexWriterConfig().setMergePolicy(NoMergePolicy.INSTANCE);
  RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
  w.addDocument(new Document());
  DirectoryReader reader = w.getReader();

  QueryBitSetProducer producer = new QueryBitSetProducer(new MatchNoDocsQuery());
  assertNull(producer.getBitSet(reader.leaves().get(0)));
  assertEquals(1, producer.cache.size());

  producer = new QueryBitSetProducer(new MatchAllDocsQuery());
  BitSet bitSet = producer.getBitSet(reader.leaves().get(0));
  assertEquals(1, bitSet.length());
  assertEquals(true, bitSet.get(0));
  assertEquals(1, producer.cache.size());

  IOUtils.close(reader, w, dir);
}
 
Example #16
Source File: SeqNoFieldMapper.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower,
                        boolean includeUpper, QueryShardContext context) {
    long l = Long.MIN_VALUE;
    long u = Long.MAX_VALUE;
    if (lowerTerm != null) {
        l = parse(lowerTerm);
        if (includeLower == false) {
            if (l == Long.MAX_VALUE) {
                return new MatchNoDocsQuery();
            }
            ++l;
        }
    }
    if (upperTerm != null) {
        u = parse(upperTerm);
        if (includeUpper == false) {
            if (u == Long.MIN_VALUE) {
                return new MatchNoDocsQuery();
            }
            --u;
        }
    }
    return LongPoint.newRangeQuery(name(), l, u);
}
 
Example #17
Source File: StoredFeatureSet.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
@Override
public List<Query> toQueries(LtrQueryContext context, Map<String, Object> params) {
    List<Query> queries = new ArrayList<>(features.size());
    for (Feature feature : features) {
        if (context.isFeatureActive(feature.name())) {
            queries.add(feature.doToQuery(context, this, params));
        } else {
            queries.add(new MatchNoDocsQuery("Feature " + feature.name() + " deactivated"));
        }
    }
    return queries;
}
 
Example #18
Source File: CommonQueryBuilderTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testWhereRefEqNullWithDifferentTypes() throws Exception {
    for (DataType type : DataTypes.PRIMITIVE_TYPES) {
        if (DataTypes.STORAGE_UNSUPPORTED.contains(type)) {
            continue;
        }
        // ensure the test is operating on a fresh, empty cluster state (no existing tables)
        resetClusterService();

        DocTableInfo tableInfo = SQLExecutor.tableInfo(
            new RelationName(DocSchemaInfo.NAME, "test_primitive"),
            "create table doc.test_primitive (" +
            "  x " + type.getName() +
            ")",
            clusterService);

        TableRelation tableRelation = new TableRelation(tableInfo);
        Map<RelationName, AnalyzedRelation> tableSources = Map.of(tableInfo.ident(), tableRelation);
        SqlExpressions sqlExpressions = new SqlExpressions(tableSources, tableRelation, User.CRATE_USER);

        Query query = convert(sqlExpressions.normalize(sqlExpressions.asSymbol("x = null")));

        // must always become a MatchNoDocsQuery
        // string: term query with null would cause NPE
        // int/numeric: rangeQuery from null to null would match all
        // bool:  term would match false too because of the condition in the eq query builder
        assertThat(query, instanceOf(MatchNoDocsQuery.class));
    }
}
 
Example #19
Source File: TestSolrCoreParser.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testHandyQuery() throws IOException, ParserException {
  final String lhsXml = "<HelloQuery/>";
  final String rhsXml = "<GoodbyeQuery/>";
  final Query query = parseHandyQuery(lhsXml, rhsXml);
  assertTrue(query instanceof BooleanQuery);
  final BooleanQuery bq = (BooleanQuery)query;
  assertEquals(2, bq.clauses().size());
  assertTrue(bq.clauses().get(0).getQuery() instanceof MatchAllDocsQuery);
  assertTrue(bq.clauses().get(1).getQuery() instanceof MatchNoDocsQuery);
}
 
Example #20
Source File: OptimizedFeatureSet.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
@Override
public List<Query> toQueries(LtrQueryContext context, Map<String, Object> params) {
    List<Query> queries = new ArrayList<>(features.size());
    for(Feature feature : features) {
        if(context.isFeatureActive(feature.name())) {
            queries.add(feature.doToQuery(context, this, params));
        } else {
            queries.add(new MatchNoDocsQuery("Feature " + feature.name() + " deactivated"));
        }
    }
    return queries;
}
 
Example #21
Source File: NumericFieldType.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static Query numericDocValuesRangeQuery(
    String field,
    Number lowerValue, Number upperValue,
    boolean lowerInclusive, boolean upperInclusive,
    boolean multiValued) {

  long actualLowerValue = Long.MIN_VALUE;
  if (lowerValue != null) {
    actualLowerValue = lowerValue.longValue();
    if (lowerInclusive == false) {
      if (actualLowerValue == Long.MAX_VALUE) {
        return new MatchNoDocsQuery();
      }
      ++actualLowerValue;
    }
  }

  long actualUpperValue = Long.MAX_VALUE;
  if (upperValue != null) {
    actualUpperValue = upperValue.longValue();
    if (upperInclusive == false) {
      if (actualUpperValue == Long.MIN_VALUE) {
        return new MatchNoDocsQuery();
      }
      --actualUpperValue;
    }
  }
  if (multiValued) {
    // In multiValued case use SortedNumericDocValuesField, this won't work for Trie*Fields wince they use BinaryDV in the multiValue case
    return SortedNumericDocValuesField.newSlowRangeQuery(field, actualLowerValue, actualUpperValue);
  } else {
    return NumericDocValuesField.newSlowRangeQuery(field, actualLowerValue, actualUpperValue);
  }
}
 
Example #22
Source File: LumongoQueryParser.java    From lumongo with Apache License 2.0 5 votes vote down vote up
@Override
protected Query newTermQuery(org.apache.lucene.index.Term term) {
	String field = term.field();
	String text = term.text();

	FieldConfig.FieldType fieldType = indexConfig.getFieldTypeForIndexField(field);
	if (IndexConfigUtil.isNumericOrDateFieldType(fieldType)) {
		if (IndexConfigUtil.isDateFieldType(fieldType)) {
			return getNumericOrDateRange(field, text, text, true, true);
		}
		else {
			if (IndexConfigUtil.isNumericIntFieldType(fieldType) && Ints.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
			else if (IndexConfigUtil.isNumericLongFieldType(fieldType) && Longs.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
			else if (IndexConfigUtil.isNumericFloatFieldType(fieldType) && Floats.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
			else if (IndexConfigUtil.isNumericDoubleFieldType(fieldType) && Doubles.tryParse(text) != null) {
				return getNumericOrDateRange(field, text, text, true, true);
			}
		}
		return new MatchNoDocsQuery(field + " expects numeric");
	}

	return super.newTermQuery(term);
}
 
Example #23
Source File: NumberFieldMapper.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public Query rangeQuery(String field, Object lowerTerm, Object upperTerm,
                 boolean includeLower, boolean includeUpper,
                 boolean hasDocValues) {
    int l = Integer.MIN_VALUE;
    int u = Integer.MAX_VALUE;
    if (lowerTerm != null) {
        l = parse(lowerTerm, true);
        // if the lower bound is decimal:
        // - if the bound is positive then we increment it:
        //      if lowerTerm=1.5 then the (inclusive) bound becomes 2
        // - if the bound is negative then we leave it as is:
        //      if lowerTerm=-1.5 then the (inclusive) bound becomes -1 due to the call to longValue
        boolean lowerTermHasDecimalPart = hasDecimalPart(lowerTerm);
        if ((lowerTermHasDecimalPart == false && includeLower == false) ||
                (lowerTermHasDecimalPart && signum(lowerTerm) > 0)) {
            if (l == Integer.MAX_VALUE) {
                return new MatchNoDocsQuery();
            }
            ++l;
        }
    }
    if (upperTerm != null) {
        u = parse(upperTerm, true);
        boolean upperTermHasDecimalPart = hasDecimalPart(upperTerm);
        if ((upperTermHasDecimalPart == false && includeUpper == false) ||
                (upperTermHasDecimalPart && signum(upperTerm) < 0)) {
            if (u == Integer.MIN_VALUE) {
                return new MatchNoDocsQuery();
            }
            --u;
        }
    }
    Query query = IntPoint.newRangeQuery(field, l, u);
    if (hasDocValues) {
        Query dvQuery = SortedNumericDocValuesField.newSlowRangeQuery(field, l, u);
        query = new IndexOrDocValuesQuery(query, dvQuery);
    }
    return query;
}
 
Example #24
Source File: NumberFieldMapper.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public Query rangeQuery(String field, Object lowerTerm, Object upperTerm,
                 boolean includeLower, boolean includeUpper,
                 boolean hasDocValues) {
    long l = Long.MIN_VALUE;
    long u = Long.MAX_VALUE;
    if (lowerTerm != null) {
        l = parse(lowerTerm, true);
        // if the lower bound is decimal:
        // - if the bound is positive then we increment it:
        //      if lowerTerm=1.5 then the (inclusive) bound becomes 2
        // - if the bound is negative then we leave it as is:
        //      if lowerTerm=-1.5 then the (inclusive) bound becomes -1 due to the call to longValue
        boolean lowerTermHasDecimalPart = hasDecimalPart(lowerTerm);
        if ((lowerTermHasDecimalPart == false && includeLower == false) ||
                (lowerTermHasDecimalPart && signum(lowerTerm) > 0)) {
            if (l == Long.MAX_VALUE) {
                return new MatchNoDocsQuery();
            }
            ++l;
        }
    }
    if (upperTerm != null) {
        u = parse(upperTerm, true);
        boolean upperTermHasDecimalPart = hasDecimalPart(upperTerm);
        if ((upperTermHasDecimalPart == false && includeUpper == false) ||
                (upperTermHasDecimalPart && signum(upperTerm) < 0)) {
            if (u == Long.MIN_VALUE) {
                return new MatchNoDocsQuery();
            }
            --u;
        }
    }
    Query query = LongPoint.newRangeQuery(field, l, u);
    if (hasDocValues) {
        Query dvQuery = SortedNumericDocValuesField.newSlowRangeQuery(field, l, u);
        query = new IndexOrDocValuesQuery(query, dvQuery);
    }
    return query;
}
 
Example #25
Source File: IpFieldMapper.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, QueryShardContext context) {
    failIfNotIndexed();
    InetAddress lower;
    if (lowerTerm == null) {
        lower = InetAddressPoint.MIN_VALUE;
    } else {
        lower = parse(lowerTerm);
        if (includeLower == false) {
            if (lower.equals(InetAddressPoint.MAX_VALUE)) {
                return new MatchNoDocsQuery();
            }
            lower = InetAddressPoint.nextUp(lower);
        }
    }

    InetAddress upper;
    if (upperTerm == null) {
        upper = InetAddressPoint.MAX_VALUE;
    } else {
        upper = parse(upperTerm);
        if (includeUpper == false) {
            if (upper.equals(InetAddressPoint.MIN_VALUE)) {
                return new MatchNoDocsQuery();
            }
            upper = InetAddressPoint.nextDown(upper);
        }
    }

    return InetAddressPoint.newRangeQuery(name(), lower, upper);
}
 
Example #26
Source File: MultiPhrasePrefixQuery.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public Query rewrite(IndexReader reader) throws IOException {
    Query rewritten = super.rewrite(reader);
    if (rewritten != this) {
        return rewritten;
    }
    if (termArrays.isEmpty()) {
        return new MatchNoDocsQuery();
    }
    MultiPhraseQuery.Builder query = new MultiPhraseQuery.Builder();
    query.setSlop(slop);
    int sizeMinus1 = termArrays.size() - 1;
    for (int i = 0; i < sizeMinus1; i++) {
        query.add(termArrays.get(i), positions.get(i));
    }
    Term[] suffixTerms = termArrays.get(sizeMinus1);
    int position = positions.get(sizeMinus1);
    ObjectHashSet<Term> terms = new ObjectHashSet<>();
    for (Term term : suffixTerms) {
        getPrefixTerms(terms, term, reader);
        if (terms.size() > maxExpansions) {
            break;
        }
    }
    if (terms.isEmpty()) {
        if (sizeMinus1 == 0) {
            // no prefix and the phrase query is empty
            return Queries.newMatchNoDocsQuery("No terms supplied for " + MultiPhrasePrefixQuery.class.getName());
        }

        // if the terms does not exist we could return a MatchNoDocsQuery but this would break the unified highlighter
        // which rewrites query with an empty reader.
        return new BooleanQuery.Builder()
            .add(query.build(), BooleanClause.Occur.MUST)
            .add(Queries.newMatchNoDocsQuery("No terms supplied for " + MultiPhrasePrefixQuery.class.getName()),
                BooleanClause.Occur.MUST).build();
    }
    query.add(terms.toArray(Term.class), position);
    return query.build();
}
 
Example #27
Source File: LuceneQueryTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testMatchNoDocsQuery() throws Exception {
    // 全不匹配查询
    Query query = new MatchNoDocsQuery();
    TopDocs search = searcher.search(query, 1000);
    Assert.assertEquals(0, search.totalHits.value);
}
 
Example #28
Source File: TestSoftDeletesRetentionMergePolicy.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testForceMergeDeletes() throws Exception {
  Directory dir = newDirectory();
  IndexWriterConfig config = newIndexWriterConfig().setSoftDeletesField("soft_delete");
  config.setMergePolicy(newMergePolicy(random(), false)); // no mock MP it might not select segments for force merge
  if (random().nextBoolean()) {
    config.setMergePolicy(new SoftDeletesRetentionMergePolicy("soft_delete",
        () -> new MatchNoDocsQuery(), config.getMergePolicy()));
  }
  IndexWriter writer = new IndexWriter(dir, config);
  // The first segment includes d1 and d2
  for (int i = 0; i < 2; i++) {
    Document d = new Document();
    d.add(new StringField("id", Integer.toString(i), Field.Store.YES));
    writer.addDocument(d);
  }
  writer.flush();
  // The second segment includes only the tombstone
  Document tombstone = new Document();
  tombstone.add(new NumericDocValuesField("soft_delete", 1));
  writer.softUpdateDocument(new Term("id", "1"), tombstone, new NumericDocValuesField("soft_delete", 1));
  writer.flush(false, true); // flush pending updates but don't trigger a merge, we run forceMergeDeletes below
  // Now we have have two segments - both having soft-deleted documents.
  // We expect any MP to merge these segments into one segment
  // when calling forceMergeDeletes.
  writer.forceMergeDeletes(true);
  assertEquals(1, writer.cloneSegmentInfos().size());
  assertEquals(1, writer.getDocStats().numDocs);
  assertEquals(1, writer.getDocStats().maxDoc);
  writer.close();
  dir.close();
}
 
Example #29
Source File: MapperQueryParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Query parse(String query) throws ParseException {
    if (query.trim().isEmpty()) {
        // if the query string is empty we return no docs / empty result
        // the behavior is simple to change in the client if all docs is required
        // or a default query
        return new MatchNoDocsQuery();
    }
    return super.parse(query);
}
 
Example #30
Source File: MultiPhrasePrefixQuery.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Query rewrite(IndexReader reader) throws IOException {
    if (getBoost() != 1.0F) {
        return super.rewrite(reader);
    }
    if (termArrays.isEmpty()) {
        return new MatchNoDocsQuery();
    }
    MultiPhraseQuery query = new MultiPhraseQuery();
    query.setSlop(slop);
    int sizeMinus1 = termArrays.size() - 1;
    for (int i = 0; i < sizeMinus1; i++) {
        query.add(termArrays.get(i), positions.get(i));
    }
    Term[] suffixTerms = termArrays.get(sizeMinus1);
    int position = positions.get(sizeMinus1);
    ObjectHashSet<Term> terms = new ObjectHashSet<>();
    for (Term term : suffixTerms) {
        getPrefixTerms(terms, term, reader);
        if (terms.size() > maxExpansions) {
            break;
        }
    }
    if (terms.isEmpty()) {
        return Queries.newMatchNoDocsQuery();
    }
    query.add(terms.toArray(Term.class), position);
    query.setBoost(getBoost());
    return query.rewrite(reader);
}