Lucene笔记01-Lucene简介和创建索引初步

本文介绍了Lucene全文搜索引擎的意义及应用,详细讲解了Lucene的下载、项目搭建过程,包括索引的创建方法,以及如何使用Lucene进行高效搜索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、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();
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值