public TestMultiPhraseQuery(String name) {
super(name);
}
public void testPhrasePrefix() throws IOException {
RAMDirectory indexStore = new RAMDirectory();
IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
add("blueberry pie", writer);
add("blueberry strudel", writer);
add("blueberry pizza", writer);
add("blueberry chewing gum", writer);
add("bluebird pizza", writer);
add("bluebird foobar pizza", writer);
add("piccadilly circus", writer);
writer.optimize();
writer.close();
IndexSearcher searcher = new IndexSearcher(indexStore, true);
// search for "blueberry pi*":
MultiPhraseQuery query1 = new MultiPhraseQuery();
// search for "strawberry pi*":
MultiPhraseQuery query2 = new MultiPhraseQuery();
query1.add(new Term("body", "blueberry"));
query2.add(new Term("body", "strawberry"));
LinkedList termsWithPrefix = new LinkedList();
IndexReader ir = IndexReader.open(indexStore, true);
// this TermEnum gives "piccadilly", "pie" and "pizza".
String prefix = "pi";
TermEnum te = ir.terms(new Term("body", prefix));
do {
if (te.term().text().startsWith(prefix))
{
termsWithPrefix.add(te.term());
}
} while (te.next());
query1.add((Term[])termsWithPrefix.toArray(new Term[0]));
assertEquals("body:\"blueberry (piccadilly pie pizza)\"", query1.toString());
query2.add((Term[])termsWithPrefix.toArray(new Term[0]));
assertEquals("body:\"strawberry (piccadilly pie pizza)\"", query2.toString());
ScoreDoc[] result;
result = searcher.search(query1, null, 1000).scoreDocs;
assertEquals(2, result.length);
result = searcher.search(query2, null, 1000).scoreDocs;
assertEquals(0, result.length);
// search for "blue* pizza":
MultiPhraseQuery query3 = new MultiPhraseQuery();
termsWithPrefix.clear();
prefix = "blue";
te = ir.terms(new Term("body", prefix));
do {
if (te.term().text().startsWith(prefix))
{
termsWithPrefix.add(te.term());
}
} while (te.next());
query3.add((Term[])termsWithPrefix.toArray(new Term[0]));
query3.add(new Term("body", "pizza"));
result = searcher.search(query3, null, 1000).scoreDocs;
assertEquals(2, result.length); // blueberry pizza, bluebird pizza
assertEquals("body:\"(blueberry bluebird) pizza\"", query3.toString());
// test slop:
query3.setSlop(1);
result = searcher.search(query3, null, 1000).scoreDocs;
assertEquals(3, result.length); // blueberry pizza, bluebird pizza, bluebird foobar pizza
MultiPhraseQuery query4 = new MultiPhraseQuery();
try {
query4.add(new Term("field1", "foo"));
query4.add(new Term("field2", "foobar"));
fail();
} catch(IllegalArgumentException e) {
// okay, all terms must belong to the same field
}
searcher.close();
indexStore.close();
}