/*
* 该方法基于短语搜索
* 实现了多个短语进行搜素的功能
* */
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.MultiPhraseQuery;
import org.apache.lucene.search.PhraseQuery;
public class MultiPharse_Query {
public MultiPharse_Query(String INDEX_STORE_PATH){
try{
IndexWriter writer = new IndexWriter(INDEX_STORE_PATH, new StandardAnalyzer(), true);
writer.setUseCompoundFile(false);
//创建3个文档
Document doc1 = new Document();
Document doc2 = new Document();
Document doc3 = new Document();
Field f1 = new Field("bookname", "钢铁是怎样炼成的", Field.Store.YES, Field.Index.TOKENIZED);
Field f2 = new Field("bookname", "英雄儿女", Field.Store.YES, Field.Index.TOKENIZED);
Field f3 = new Field("bookname", "篱笆女人和狗", Field.Store.YES, Field.Index.TOKENIZED);
doc1.add(f1);
doc2.add(f2);
doc3.add(f3);
writer.addDocument(doc1);
writer.addDocument(doc2);
writer.addDocument(doc3);
writer.close();
IndexSearcher searcher = new IndexSearcher(INDEX_STORE_PATH);
//创建一个multiPharseQuery
MultiPhraseQuery query = new MultiPhraseQuery();
//首先向其中加入要查找的短语前缀
query.add(new Term("bookname", "钢"));
//构建三个Term, 作为短语的后缀
Term t1 = new Term("bookname", "铁");
Term t2 = new Term("bookname", "和");
Term t3 = new Term("bookname", "要");
//再向Query中国加入所有的后缀,与前缀一起,他们将组成3个短语
query.add(new Term[]{t1, t2, t3});
//打印查询结构
Hits hits = searcher.search(query);
for(int i = 0; i < hits.length(); i++){
System.out.println(hits.doc(i));
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("多个短语开始搜索------------>>>>>");
MultiPharse_Query mq = new MultiPharse_Query("E:\\lucene项目\\索引文件");
System.out.println("搜索完成------------------>>>>>");
System.out.println("停止搜索-----||||||||||||||||||||");
}
}