日期:2014-05-20 浏览次数:20799 次
public class MyPhraseQuery
{
public void setUp() throws Exception
{
dir=new RAMDirectory();
IndexWriter writer=getWriter();
Document doc=new Document();
doc.add(new StringField("field","the quick brown fox jumped over the lazy dog",Store.YES));
writer.addDocument(doc);
writer.close();
reader=DirectoryReader.open(dir);
searcher=new IndexSearcher(reader);
}
public void tearDown() throws IOException
{
reader.close();
dir.close();
}
public boolean matched(String [] phrase,int slop) throws IOException
{
PhraseQuery query=new PhraseQuery();
query.setSlop(slop);
for(String word:phrase)
{
query.add(new Term("field",word));
}
TopDocs matches=searcher.search(query, 10);
return matches.totalHits>0;
}
private IndexWriter getWriter() throws Exception {
Analyzer analyzer=new WhitespaceAnalyzer(Version.LUCENE_47);
IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_47, analyzer);
return new IndexWriter(dir, iwc);
}
private Directory dir;
private IndexReader reader;
private IndexSearcher searcher;
}
public class MyPhraseQueryTest
{
@Test
public void PhraseQueryTest() throws Exception
{
MyPhraseQuery q=new MyPhraseQuery();
q.setUp();
String[] phrase=new String[]{"quick","fox"};
System.out.println(q.matched(phrase,0)+" "+q.matched(phrase,1));
assertFalse("exact phrase not fount",q.matched(phrase,0));
assertTrue("close enough",q.matched(phrase,1));
q.tearDown();
}
}