package demo1;
import java.io.File;
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.TermQuery;
public class TestBooleanQuery {
// 将索引创建的执行的盘符下
private final String PATH = "C://index";
public TestBooleanQuery() {
// TODO Auto-generated constructor stub
}
public void createIndex() {
try {
IndexWriter indexWriter = new IndexWriter(new File(PATH),
new StandardAnalyzer(), true);
// BooleanQuery bq = new BooleanQuery();
Field title1 = new Field("title", "我们生活在一个**", Field.Store.YES,
Field.Index.TOKENIZED);
Field title2 = new Field("title", "社会主义好就好,我们是一个大家庭", Field.Store.YES,
Field.Index.TOKENIZED);
Field title3 = new Field("title", "十大神兽中实在太可爱了", Field.Store.YES,
Field.Index.TOKENIZED);
Field title4 = new Field("title", "赤兔马", Field.Store.YES,
Field.Index.TOKENIZED);
Document doc1 = new Document();
Document doc2 = new Document();
Document doc3 = new Document();
Document doc4 = new Document();
doc1.add(title1);
doc2.add(title2);
doc3.add(title3);
doc4.add(title4);
indexWriter.addDocument(doc1);
indexWriter.addDocument(doc2);
indexWriter.addDocument(doc3);
indexWriter.addDocument(doc4);
indexWriter.optimize();
indexWriter.close();
System.out.println("创建索引成功!!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("创建索引失败!!");
}
}
/**
*
*/
public void searchIndex(){
try {
IndexSearcher search = new IndexSearcher(PATH);
BooleanQuery bq = new BooleanQuery();
Term t1 = new Term("title","社");
Term t2 = new Term("title","会");
Term t3 = new Term("title","马");
//表示检索的过程中包含 社 会 和马这三个关键字
bq.add(new TermQuery(t1), BooleanClause.Occur.SHOULD);
bq.add(new TermQuery(t2), BooleanClause.Occur.SHOULD);
bq.add(new TermQuery(t3), BooleanClause.Occur.SHOULD);
Hits hits = search.search(bq);
//System.out.println("--->>"+hits.length());
for(int i = 0;i<hits.length();i++){
Document doc = (Document)hits.doc(i);
System.out.println("---->>"+doc.get("title"));
}
//关闭检索的查询
search.close();
System.out.println("检索成功!!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("检索失败!!");
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestBooleanQuery test = new TestBooleanQuery();
test.createIndex();
test.searchIndex();
}
}