分类:
2008-09-12 13:07:35
网上流行的lucene使用方法大部分是lucene1.4左右,而现在的lucene已经到了2.x,以下是lucene2.2.0的事例
1.像往常的框架一样,自然需要将其所需的jar包导入
导入lucene-core-2.2.0.jar(最新的jar)
//---------------------------------------------------------
2.创建索引(Index)
public void createIndex(){
File indexDir=new File("f:/lucene/"); //将索引写入到"f:/lucene/"下;
long start=new Date().getTime();
StandardAnalyzer sa=new StandardAnalyzer(); //创建标准分析器
try {
IndexWriter indexWriter=new IndexWriter(indexDir,sa,true); //需要Index写入器,(创建)
indexWriter.setMergeFactor(100);
indexWriter.setMaxMergeDocs(100);
indexWriter.setMaxFieldLength(5000);
while(rs.next()){
Document doc=new Document(); //创建文档(document)对象,rs是recordset对象,事先已经从数据库取出!
doc.add(new Field("productName",rs.getString("productName"),Field.Store.YES,Field.Index.TOKENIZED)); //为document添加好field
doc.add(new Field("unitprice",rs.getString("unitprice"),Field.Store.YES,Field.Index.TOKENIZED));
indexWriter.addDocument(doc); //别忘记,将document加到写入器indexWriter
}
indexWriter.optimize(); //进行优化
indexWriter.close();//关闭
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LockObtainFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long end=new Date().getTime();
System.out.println("索引创建完毕,用时:"+(end-start)+"毫秒");
}
//---------------------------------------------------------------
3.创建检索方法(searcher)
public Hits searcher(String queryString){
Hits hits=null;
try {
IndexSearcher indexSearcher=new IndexSearcher("f:/lucene/"); //创建从"f:/lucene"检索数据的检索器
String[] fields={"productName","unitprice"};
QueryParser queryParser=new MultiFieldQueryParser(fields,new StandardAnalyzer()); //创建查询分析器
Query query= queryParser.parse(queryString); //查询分析器解析 查询条件
hits=indexSearcher.search(query);//检索器检索出所有符合条件的数据,封成hits返回.
return hits;
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
[1]