Lucene使用主要有以下步骤
1建立索引
2搜索
3获得结果
附上简单的测试代码
package test;
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.Query;
import org.apache.lucene.search.TermQuery;
public class test{
private static String INDEX_STORE_PATH = "e:\\index";
public static void main(String args[]) throws IOException{
//建立索引
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();
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);
Term t1=new Term("bookname","女");
Query q1=new TermQuery(t1);
//BooleanQuery query=new BooleanQuery();
//query.add(q1,BooleanClause.Occur.MUST);
Hits hits =searcher.search(q1);
for(int i=0;i<hits.length();i++){
System.out.println(hits.doc(i));
System.out.println(hits.score(i));
}
}
}