/*
* 通配符的概念已经被使用很久了,从最早的DOS时代一直到今天。
* 通常情况下,在通配符中使用"*"来表示0到多个字符,
* 而使用"?"来表示一个单一的字符。
* Lucene中提供了的通配符搜索工具WildcardQuery。
* 具体的使用非常简单,
* 就首先设定一个带通配符的字符串,
* 再包装成Term对象,然后将其作为wildCardQuery的构造函数的参数传入其中。
* */
package query;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.WildcardQuery;
public class WildCardQueryTest {
public WildCardQueryTest(String INDEX_STORE_PATH){
try{
IndexWriter writer = new IndexWriter(INDEX_STORE_PATH, new StandardAnalyzer(), true);
writer.setUseCompoundFile(false);
Document doc1 = new Document();
Document doc2 = new Document();
Document doc3 = new Document();
Document doc4 = new Document();
Document doc5 = new Document();
Document doc6 = new Document();
Field f1 = new Field("content", "word", Field.Store.YES, Field.Index.TOKENIZED);
Field f2 = new Field("content", "work", Field.Store.YES, Field.Index.TOKENIZED);
Field f3 = new Field("content", "world", Field.Store.YES, Field.Index.TOKENIZED);
Field f4 = new Field("content", "seed", Field.Store.YES, Field.Index.TOKENIZED);
Field f5 = new Field("content", "sword", Field.Store.YES, Field.Index.TOKENIZED);
Field f6 = new Field("content", "ford", Field.Store.YES, Field.Index.TOKENIZED);
doc1.add(f1);
doc2.add(f2);
doc3.add(f3);
doc4.add(f4);
doc5.add(f5);
doc6.add(f6);
writer.addDocument(doc1);
writer.addDocument(doc2);
writer.addDocument(doc3);
writer.addDocument(doc4);
writer.addDocument(doc5);
writer.addDocument(doc6);
writer.close();
IndexSearcher searcher = new IndexSearcher(INDEX_STORE_PATH);
//构建一个带有通配符的词条
Term t = new Term("content", "?o*");
WildcardQuery query = new WildcardQuery(t);
Hits hits = searcher.search(query);
for(int i = 0; i < hits.length(); i++){
System.out.println(hits.doc(i));
}
}catch(IOException e){
System.out.println("查找有误,请仔细检查");
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("开始执行通配符查找---------------------->>>");
System.out.println("查找中,请稍后---------------------->>");
WildCardQueryTest wt = new WildCardQueryTest("E:\\Lucene项目\\索引文件");
System.out.println("查找完毕");
}
}