Skip to content

Apache Lucene open-source search software

LUCENE-543: WildcardQuery without wildcarded term rewrites to a TermQuery

Erik Hatcherc44be0c446fe
diff --git a/CHANGES.txt b/CHANGES.txt
index c15440ef897..f3253af2669 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -30,6 +30,11 @@ Changes in runtime behavior
for range queries. Added useOldRangeQuery property to QueryParser to allow
selection of old RangeQuery class if required.
+ 6. LUCENE-543: WildcardQuery now performs a TermQuery if the provided term
+ does not contain a wildcard character (? or *), when previously a
+ StringIndexOutOfBoundsException was thrown.
+ (Michael Busch via Erik Hatcher)
+
New features
1. LUCENE-503: New ThaiAnalyzer and ThaiWordFilter in contrib/analyzers
@@ -58,7 +63,7 @@ New features
7. LUCENE-573: QueryParser now allows backslash escaping in
quoted terms and phrases. (Michael Busch via Yonik Seeley)
- 7. LUCENE-716: QueryParser now allows specification of unicode
+ 8. LUCENE-716: QueryParser now allows specification of unicode
characters in terms via a unicode escape of the form \uXXXX
(Michael Busch via Yonik Seeley)
diff --git a/src/java/org/apache/lucene/search/WildcardQuery.java b/src/java/org/apache/lucene/search/WildcardQuery.java
index 19a283ae398..47f2e8efa59 100644
--- a/src/java/org/apache/lucene/search/WildcardQuery.java
+++ b/src/java/org/apache/lucene/search/WildcardQuery.java
@@ -31,8 +31,11 @@ import java.io.IOException;
* @see WildcardTermEnum
*/
public class WildcardQuery extends MultiTermQuery {
+ private boolean termContainsWildcard;
+
public WildcardQuery(Term term) {
super(term);
+ this.termContainsWildcard = (term.text().indexOf('*') != -1) || (term.text().indexOf('?') != -1);
}
protected FilteredTermEnum getEnum(IndexReader reader) throws IOException {
@@ -45,4 +48,12 @@ public class WildcardQuery extends MultiTermQuery {
return false;
}
+
+ public Query rewrite(IndexReader reader) throws IOException {
+ if (this.termContainsWildcard) {
+ return super.rewrite(reader);
+ }
+
+ return new TermQuery(getTerm());
+ }
}
diff --git a/src/test/org/apache/lucene/search/TestWildcard.java b/src/test/org/apache/lucene/search/TestWildcard.java
index 1beaf2a8156..0f7b49a2274 100644
--- a/src/test/org/apache/lucene/search/TestWildcard.java
+++ b/src/test/org/apache/lucene/search/TestWildcard.java
@@ -54,6 +54,21 @@ public class TestWildcard
assertFalse(wq1.equals(fq));
assertFalse(fq.equals(wq1));
}
+
+ /**
+ * Tests if a WildcardQuery that has no wildcard in the term is rewritten to a single
+ * TermQuery.
+ */
+ public void testTermWithoutWildcard() throws IOException {
+ RAMDirectory indexStore = getIndexStore("field", new String[]{"nowildcard", "nowildcardx"});
+ IndexSearcher searcher = new IndexSearcher(indexStore);
+
+ Query wq = new WildcardQuery(new Term("field", "nowildcard"));
+ assertMatches(searcher, wq, 1);
+
+ wq = searcher.rewrite(wq);
+ assertTrue(wq instanceof TermQuery);
+ }
/**
* Tests Wildcard queries with an asterisk.