下面列出了怎么用org.apache.lucene.search.MatchNoDocsQuery的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
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);
}
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();
}
}
/** 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;
}
}
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());
}
@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 */
}
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);
}
/**
* 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);
}
@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);
}
@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);
}
@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);
}
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);
}
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);
}
@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);
}
@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);
}
@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);
}
@Test
public void testMatchNoDocsQuery() throws Exception {
// 全不匹配查询
Query query = new MatchNoDocsQuery();
TopDocs search = searcher.search(query, 1000);
Assert.assertEquals(0, search.totalHits.value);
}
@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);
}
@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);
}
private String getRewrittenQuery(IndexSearcher searcher, Query query) throws IOException {
Query queryRewrite = searcher.rewrite(query);
if (queryRewrite instanceof MatchNoDocsQuery) {
return query.toString();
} else {
return queryRewrite.toString();
}
}
public void testMatchNoDocsQuery() throws IOException {
highlighter = new UnifiedHighlighter(null, indexAnalyzer);
highlighter.setHighlightPhrasesStrictly(true);
String content = "whatever";
Object o = highlighter.highlightWithoutSearcher("body", new MatchNoDocsQuery(), content, 1);
assertEquals(content, o);
}
@Override
public Query rewrite(IndexReader reader) throws IOException {
if (this.terms.isEmpty()) {
return new MatchNoDocsQuery("CommonTermsQuery with no terms");
} else if (this.terms.size() == 1) {
return newTermQuery(this.terms.get(0), null);
}
final List<LeafReaderContext> leaves = reader.leaves();
final int maxDoc = reader.maxDoc();
final TermStates[] contextArray = new TermStates[terms.size()];
final Term[] queryTerms = this.terms.toArray(new Term[0]);
collectTermStates(reader, leaves, contextArray, queryTerms);
return buildQuery(maxDoc, contextArray, queryTerms);
}
public void testEquals() throws Exception {
Query q1, q2;
Rectangle rect = nextBox();
q1 = newRectQuery("field", rect.minLat, rect.maxLat, rect.minLon, rect.maxLon);
q2 = newRectQuery("field", rect.minLat, rect.maxLat, rect.minLon, rect.maxLon);
assertEquals(q1, q2);
// for "impossible" ranges LatLonPoint.newBoxQuery will return MatchNoDocsQuery
// changing the field is unrelated to that.
if (q1 instanceof MatchNoDocsQuery == false) {
assertFalse(q1.equals(newRectQuery("field2", rect.minLat, rect.maxLat, rect.minLon, rect.maxLon)));
}
double lat = nextLatitude();
double lon = nextLongitude();
q1 = newDistanceQuery("field", lat, lon, 10000.0);
q2 = newDistanceQuery("field", lat, lon, 10000.0);
assertEquals(q1, q2);
assertFalse(q1.equals(newDistanceQuery("field2", lat, lon, 10000.0)));
double[] lats = new double[5];
double[] lons = new double[5];
lats[0] = rect.minLat;
lons[0] = rect.minLon;
lats[1] = rect.maxLat;
lons[1] = rect.minLon;
lats[2] = rect.maxLat;
lons[2] = rect.maxLon;
lats[3] = rect.minLat;
lons[3] = rect.maxLon;
lats[4] = rect.minLat;
lons[4] = rect.minLon;
if (supportsPolygons()) {
q1 = newPolygonQuery("field", new Polygon(lats, lons));
q2 = newPolygonQuery("field", new Polygon(lats, lons));
assertEquals(q1, q2);
assertFalse(q1.equals(newPolygonQuery("field2", new Polygon(lats, lons))));
}
}
@Override
public MatchNoDocsQuery build(QueryNode queryNode) throws QueryNodeException {
// validates node
if (!(queryNode instanceof MatchNoDocsQueryNode)) {
throw new QueryNodeException(new MessageImpl(
QueryParserMessages.LUCENE_QUERY_CONVERSION_ERROR, queryNode
.toQueryString(new EscapeQuerySyntaxImpl()), queryNode.getClass()
.getName()));
}
return new MatchNoDocsQuery();
}
public void addSpanQuery(Query q) {
if (q.getClass() == MatchNoDocsQuery.class)
return;
if (! (q instanceof SpanQuery))
throw new AssertionError("Expected SpanQuery: " + q.toString(getFieldName()));
float boost = 1f;
if (q instanceof SpanBoostQuery) {
SpanBoostQuery bq = (SpanBoostQuery) q;
boost = bq.getBoost();
q = bq.getQuery();
}
addSpanQueryWeighted((SpanQuery)q, boost);
}
public void assertMatchNoDocsQuery(Query query) throws Exception {
if (query instanceof MatchNoDocsQuery) {
// good
} else if (query instanceof BooleanQuery && ((BooleanQuery) query).clauses().size() == 0) {
// good
} else {
fail("expected MatchNoDocsQuery or an empty BooleanQuery but got: " + query);
}
}
private void assertStopQueryIsMatchNoDocsQuery(String qtxt) throws Exception {
String[] fields = { "b", "t" };
Occur occur[] = { Occur.SHOULD, Occur.SHOULD };
TestQPHelper.QPTestAnalyzer a = new TestQPHelper.QPTestAnalyzer();
StandardQueryParser mfqp = new StandardQueryParser();
mfqp.setMultiFields(fields);
mfqp.setAnalyzer(a);
Query q = mfqp.parse(qtxt, null);
assertTrue(q instanceof MatchNoDocsQuery);
}
public void assertMatchNoDocsQuery(Query query) throws Exception {
if (query instanceof MatchNoDocsQuery) {
// good
} else if (query instanceof BooleanQuery && ((BooleanQuery) query).clauses().size() == 0) {
// good
} else {
fail("expected MatchNoDocsQuery or an empty BooleanQuery but got: " + query);
}
}
public void testGarbageEmpty() throws Exception {
MatchNoDocsQuery expected = new MatchNoDocsQuery();
assertEquals(expected, parse(""));
assertEquals(expected, parse(" "));
assertEquals(expected, parse(" "));
assertEquals(expected, parse("\\ "));
assertEquals(expected, parse("\\ \\ "));
assertEquals(expected, parse("\"\""));
assertEquals(expected, parse("\" \""));
assertEquals(expected, parse("\" \"|\" \""));
assertEquals(expected, parse("(\" \"|\" \")"));
assertEquals(expected, parse("\" \" \" \""));
assertEquals(expected, parse("(\" \" \" \")"));
}
public void assertMatchNoDocsQuery(Query query) throws Exception {
if (query instanceof MatchNoDocsQuery) {
// good
} else if (query instanceof BooleanQuery && ((BooleanQuery) query).clauses().size() == 0) {
// good
} else {
fail("expected MatchNoDocsQuery or an empty BooleanQuery but got: " + query);
}
}