一、Lucene存在的意义
我们通常的数据库搜索,比如说在content中搜索某个内容,我们需要使用like的方式,这种方式的效率的非常低下的。这便要说到Lucene了,Lucene搜索的时候,用到了索引,这个索引类似于我们查字典时候最前面的索引表,相比于拿一本字典去翻看,我们通过索引表来查询,效率一定会很高,这就是全文搜索存在的意义。首先Lucene会将整个结构创建一个索引,之后搜索的时候,根据索引来查找。还有一点就是,假如我们需要查询的内容在文件内部,而不是数据库表中,就比较难实现了,然而Lucene可以做到。
二、Lucene的下载
可以在Lucene下载地址下载对应版本的Lucene,这里使用的Lucene的3.5.0版本,有一点需要注意的:Lucene不是向下兼容的,各个版本之间的差距可能比较大。
三、Lucene项目的搭建
简单起见,我们创建一个Java项目,下载一个junit-4.7的jar包,将刚才下载的lucene-core-3.5.0.jar和junit-4.7.jar两个jar包放到项目下的lib中,并将它们add to build path。在Lucene工具中,大致可以分成三部分:索引部分、分词部分、搜索部分。
四、创建索引
创建索引之后,可以在E:\Lucene\IndexLibrary目录下,发现一些文件,这些文件就是所谓的索引了。之后,会使用Luke工具来查看这些索引的具体内容。
public void index() {
IndexWriter indexWriter = null;
try {
// 创建Directory,用于存放索引,可以放在内存,也可以放在硬盘
Directory directory = null;
// directory = new RAMDirectory();// 创建在内存中
directory = FSDirectory.open(new File("E:\\Lucene\\IndexLibrary"));// 创建在硬盘上
// 创建IndexWriter,用于写索引
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35));
indexWriter = new IndexWriter(directory, indexWriterConfig);
// 创建Document对象,也就是一个文档
Document document = null;
// 为Document添加Field,一个文档有很多属性,比如大小,路径,创建时间等,这些都叫Field
File[] files = new File("E:\\Lucene\\SearchSource").listFiles();
for (File file : files) {
document = new Document();
document.add(new Field("content", new FileReader(file)));
document.add(new Field("fileName", file.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED));
document.add(new Field("path", file.getAbsolutePath(), Field.Store.YES, Field.Index.NOT_ANALYZED));
// 通过IndexWriter添加文档到索引中
indexWriter.addDocument(document);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (indexWriter != null) {
try {
indexWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}