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.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.TermQuery;
public class Phrase_Query {
public Phrase_Query(String INDEX_STORE){
try{
IndexWriter writer = new IndexWriter(INDEX_STORE, 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);
//创建一个PharseQuery,并搜索短语"钢铁"
PhraseQuery query = new PhraseQuery();
query.add(new Term("bookname","钢"));
query.add(new Term("bookname","铁"));
//打印查询结构
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("开始进行短语搜索----------->>");
Phrase_Query hq = new Phrase_Query("E:\\Lucene项目\\索引文件");
System.out.println("结束短语搜索----------->>");
}
}