在写代码之前,首先要构建好开发的环境,添加项目所需要的jar包,lucene索引的创建和搜索需要的jar包主要如下:
lucene-core-4.3.0.jar
lucene-analyzers-common-4.3.0.jar
lucene-queryparser-4.3.0.jar
创建索引的主要代码如下:
/**
* 创建索引
* @Adder by arvin 2013-7-1 上午10:51:17
*/
public void index(){
IndexWriter indexWriter=null;
try {
//1.创建Directory由于存放索引
//Directory directory=new RAMDirectory();//索引存放在内容中
Directory directory=FSDirectory.open(new File("E:/luncene/index01"));
//2.创建IndexWriter用于写索引
IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_43,new StandardAnalyzer(Version.LUCENE_43));
indexWriter=new IndexWriter(directory,iwc);
//3.创建Document对象
Document document=null;
//4.为Document对象添加Field
File f=new File("E:/luncene/content");
for(File file : f.listFiles()){
document=new Document();
document.add(new TextField("contents", new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))));
document.add(new StringField("path", file.getPath(), Field.Store.YES));
document.add(new StringField("filename", file.getName(), Field.Store.YES));
indexWriter.addDocument(document);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(indexWriter!=null){
indexWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
创建搜索的代码主要如下:
/**
* 搜索索引
* @Adder by arvin 2013-7-1 下午2:27:41
*/
public void search(){
try {
//1.创建Directory
Directory directory=FSDirectory.open(new File("E:/luncene/index01"));
//2.创建IndexReader
IndexReader reader=DirectoryReader.open(directory);
//3.根据IndexReader创建IndexSearcher
IndexSearcher search=new IndexSearcher(reader);
//4.创建搜索的Query
//创建parser来确定搜索的内容,第二个参数表示搜索的域
QueryParser parser=new QueryParser(Version.LUCENE_43,"contents",new StandardAnalyzer(Version.LUCENE_43));
//创建query,表示搜索域中包含'java'的文档
Query query=parser.parse("java");
//5.根据search搜索返回TopDocs
TopDocs tds=search.search(query, 10);
//6.根据TopDocs获取Sco
ScoreDoc[] sd=tds.scoreDocs;
for(ScoreDoc s : sd){
//7.根据search和scoredoc获取具体的Document对象
Document doc=search.doc(s.doc);
//8.根据Document对象获取需要的内容
System.out.println(doc.get("filename")+"["+doc.get("path")+"]");
}
//9.关闭reader
reader.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
其中文件夹content存放的是要索引的文件,而index01是存放索引的文件