全文索引---Lucene

本文介绍全文检索的基本概念,区分结构化与非结构化数据,并深入探讨全文检索技术,特别是Lucene的实现方法。从创建索引到查询索引,详细解析了全文检索的工作流程。

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

1   全文检索

1.1   数据分类

我们生活中的数据总体分为两种:结构化数据和非结构化数据。

结构化数据:指具有固定格式或有限长度的数据,如数据库,元数据等。

非结构化数据:指不定长或无固定格式的数据,如邮件,word文档等磁盘上的文件。

有的地方还会提到第三种,半结构化数据,如XMLHTML等,当根据需要可按结构化数据来处理,也可抽取出纯文本按非结构化数据来处理。

1.2   结构化数据搜索

常见的结构化数据也就是数据库中的数据。在数据库中搜索很容易实现,通常都是使用sql语句进行查询,而且能很快的得到查询结果。

为什么数据库搜索很容易?

因为数据库中的数据存储是有规律的,有行有列而且数据格式、数据长度都是固定的。

1.3   非结构化数据的搜索

利用windows的搜索也可以搜索文件内容,Linux下的grep命令,再如用Google和百度可以搜索大量内容数据。主要有两种方法:

 

(1)顺序扫描法(Serial Scanning)

所谓顺序扫描,比如要找内容包含某一个字符串的文件,就是一个文档一个文档的看,对于每一个文档,从头看到尾,如果此文档包含此字符串,则此文档为我们要找的文件,接着看下一个文件,直到扫描完所有的文件。如利用windows的搜索也可以搜索文件内容,只是相当的慢。

(2)全文检索(Full-text Search)

将非结构化数据中的一部分信息提取出来,重新组织,使其变得有一定结构,然后对此有一定结构的数据进行搜索,从而达到搜索相对较快的目的。这部分从非结构化数据中提取出的然后重新组织的信息,我们称之索引

先建立索引,再对索引进行搜索的过程就叫全文检索(Full-text Search)

虽然创建索引的过程也是非常耗时的,但是索引一旦创建就可以多次使用,全文检索主要处理的是查询,所以耗时间创建索引是值得的。

1.4   如何实现全文检索

可以使用Lucene实现全文检索。Luceneapache下的一个开放源代码的全文检索引擎工具包。提供了完整的查询引擎和索引引擎,部分文本分析引擎。Lucene的目的是为软件开发人员提供一个简单易用的工具包,以方便的在目标系统中实现全文检索的功能。

 

1.5   全文检索的应用场景

对于数据量大、数据结构不固定的数据可采用全文检索方式搜索,比如百度、Google等搜索引擎、论坛站内搜索、电商网站站内搜索等。

 

2   Lucene实现全文检索的流程

2.1   索引和搜索流程图

 

2.2   创建索引

对文档索引的过程,将用户要搜索的文档内容进行索引,索引存储在索引库(index)中。

这里我们要搜索的文档是磁盘上的文本文件,根据案例描述:凡是文件名或文件内容包括关键字的文件都要找出来,这里要对文件名和文件内容创建索引。

 

2.2.1 获得原始文档

原始文档是指要索引和搜索的内容。原始内容包括互联网上的网页、数据库中的数据、磁盘上的文件等。

从互联网上、数据库、文件系统中等获取需要搜索的原始信息,这个过程就是信息采集,信息采集的目的是为了对原始内容进行索引。

Internet上采集信息的软件通常称为爬虫或蜘蛛,也称为网络机器人,爬虫访问互联网上的每一个网页,将获取到的网页内容存储起来。

      Lucene不提供信息采集的类库,需要自己编写一个爬虫程序实现信息采集,也可以通过一些开源软件实现信息采集。

2.2.2 创建文档对象

获取原始内容的目的是为了索引,在索引前需要将原始内容创建成文档(Document),文档中包括一个一个的域(Field),域中存储内容。

这里我们可以将磁盘上的一个文件当成一个documentDocument中包括一些Fieldfile_name文件名称、file_path文件路径、file_size文件大小、file_content文件内容)。

注意:每个Document可以有多个Field,不同的Document可以有不同的Field,同一个Document可以有相同的Field(域名和域值都相同)

每个文档都有一个唯一的编号,就是文档id

2.2.3 分析文档

将原始内容创建为包含域(Field)的文档(document),需要再对域中的内容进行分析,分析的过程是经过对原始文档提取单词、将字母转为小写、去除标点符号、去除停用词等过程生成最终的语汇单元,可以将语汇单元理解为一个一个的单词。

2.2.4 创建索引

对所有文档分析得出的语汇单元进行索引,索引的目的是为了搜索,最终要实现只搜索被索引的语汇单元从而找到Document(文档)。

注意:创建索引是对语汇单元索引,通过词语找文档,这种索引的结构叫倒排索引结构

传统方法是根据文件找到该文件的内容,在文件内容中匹配搜索关键字,这种方法是顺序扫描方法,数据量大、搜索慢。

倒排索引结构也叫反向索引结构,包括索引和文档两部分,索引即词汇表,它的规模较小,而文档集合较大。


2.3   查询索引

查询索引也是搜索的过程。搜索就是用户输入关键字,从索引(index)中进行搜索的过程。根据关键字搜索索引,根据索引找到对应的文档,从而找到要搜索的内容(这里指磁盘上的文件)。

 

2.3.1 用户查询接口

全文检索系统提供用户搜索的界面供用户提交搜索的关键字,搜索完成展示搜索结果。

2.3.2 创建查询

用户输入查询关键字执行搜索之前需要先构建一个查询对象,查询对象中可以指定查询要搜索的Field文档域、查询关键字等,查询对象会生成具体的查询语法,

例如:

语法“fileName:lucene”表示要搜索Field域的内容为“lucene”的文档

2.3.3 执行查询

搜索索引过程:

根据查询语法在倒排索引词典表中分别找出对应搜索词的索引,从而找到索引所链接的文档链表。

比如搜索语法为“fileName:lucene”表示搜索出fileName域中包含Lucene的文档。

搜索过程就是在索引上查找域为fileName,并且关键字为Luceneterm,并根据term找到文档id列表。

2.3.4 渲染结果

以一个友好的界面将查询结果展示给用户,用户根据搜索结果找自己想要的信息,为了帮助用户很快找到自己的结果,提供了很多展示的效果,比如搜索结果中将关键字高亮显示,百度提供的快照等。

代码案例:

1.   索引库的添加&维护

package cn.itcast.createindex;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Before;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.util.Objects;

public class Test02 {

    private IndexWriter indexWriter;

    @Before
    public void init() throws Exception {
        // 1)创建Directory对象,索引库的位置
        Directory directory = FSDirectory.open(new File("E://lucene_index"));
        // 2)创建一个IndexWriter对象
        indexWriter = new IndexWriter(directory, new IndexWriterConfig(Version.LATEST, new IKAnalyzer()));

    }
    /**
     * 添加索引
     * @throws Exception
     */
    @Test
    public void addDocument() throws Exception {
        //原始文档的路径
        File files = new File("D://...");
        for(File file : Objects.requireNonNull(files.listFiles())) {
            //文件名
            String fileName = file.getName();
            //文件内容
            String fileContent = FileUtils.readFileToString(file);
            //文件路径
            String filePath = file.getPath();
            //文件大小
            long fileSize = FileUtils.sizeOf(file);
            //创建文件名域(域的名称,域的内容,是否存储)
            TextField fileNameField = new TextField("name", fileName, Field.Store.YES);
            //文件内容域
            Field fileContentField = new TextField("content", fileContent, Field.Store.YES);
            //文件路径域(不分析,不索引,只存储)
            Field filePathField = new TextField("path", filePath, Field.Store.YES);
            //文件大小域
            Field fileSizeField = new TextField("size", fileSize + "", Field.Store.YES);
            //创建Document对象
            Document document = new Document();
            document.add(fileNameField);
            document.add(fileContentField);
            document.add(filePathField);
            document.add(fileSizeField);
            //创建索引,并写入索引库
            indexWriter.addDocument(document);
        }
        // 6)提交、关闭索引库
        indexWriter.commit();
        indexWriter.close();

    }

    /**
     * 删除全部索引
     * @throws Exception
     */
    @Test
    public void deleteAllIndex() throws Exception {
        //删除全部索引
        indexWriter.deleteAll();
        //关闭indexwriter
        indexWriter.close();
    }

    /**
     * 根据查询条件删除索引
     * @throws Exception
     */
    @Test
    public void deleteIndexByQuery() throws Exception {
        //创建一个查询条件
        Query query = new TermQuery(new Term("name", "apache"));
        //根据查询条件删除
        indexWriter.deleteDocuments(query);
        //关闭indexwriter
        indexWriter.close();
    }

    /**
     * 修改索引库
     * @throws Exception
     */
    @Test
    public void updateIndex() throws Exception {
        //创建一个Document对象
        Document document = new Document();
        //向document对象中添加域。
        //不同的document可以有不同的域,同一个document可以有相同的域。
        document.add(new TextField("name", "更新之后的文档", Field.Store.YES));
        document.add(new TextField("name2", "更新之后的文档2", Field.Store.YES));
        indexWriter.updateDocument(new Term("name", "spring"), document);
        //关闭indexWriter
        indexWriter.close();
    }

}


2.Lucene索引库查询

package cn.itcast.createindex;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Before;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;

public class Test000_SearchIndex {

    private IndexReader   indexReader;
    private IndexSearcher indexSearcher;

    @Before
    public void init() throws Exception {
        // 1、创建一个IndexReader对象
        Directory directory = FSDirectory.open(new File("E://lucene_index"));
        indexReader = DirectoryReader.open(directory);
        // 2、创建一个IndexSearcher对象
        indexSearcher = new IndexSearcher(indexReader);
    }

    private void execQuery(Query query) throws Exception {
        // 4、执行查询
        TopDocs topDocs = indexSearcher.search(query, 10);
        // 5、取查询结果的总记录数
        System.out.println("查询结果的总记录数:" + topDocs.totalHits);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        // 6、遍历查询结果
        for (ScoreDoc scoreDoc : scoreDocs) {
            //根据文档的id取文档对象
            Document document = indexSearcher.doc(scoreDoc.doc);
            System.out.println(document.get("name"));
            System.out.println(document.get("content"));
            System.out.println(document.get("path"));
            System.out.println(document.get("size"));
        }
        // 7、关闭IndexReader
        indexReader.close();
    }

    /**
     * 查询索引目录中的所有文档
     * @throws Exception
     */
    @Test
    public void testMatchAllDocsQuery() throws  Exception{
        //创建一个Query对象,使用MatchAllDocsQuery
        MatchAllDocsQuery query = new MatchAllDocsQuery();
        System.out.println(query);
        //执行查询
        execQuery(query);
    }

    /**
     * 根据数值范围查询
     * @throws Exception
     */
    @Test
    public void testNumericRangeQuery() throws Exception {
        //创建一个查询对象
        //参数1:要搜索的域
        //参数2:范围的最小值
        //参数3:范围的最大值
        //参数4:是否包含最小值
        //参数5:是否包含最大值
        Query query = NumericRangeQuery.newLongRange("size", 0L, 1024L, true, false);
        System.out.println(query);
        //执行查询
        execQuery(query);
    }

    /**
     * 组合条件查询
     * @throws Exception
     */
    @Test
    public void testBooleanQuery() throws Exception {
        //创建一个布尔查询对象
        BooleanQuery query = new BooleanQuery();
        // 2、创建查询条件1
        Query query1 = new TermQuery(new Term("name", "apache"));
        // 3、创建查询条件2 。。。。
        Query query2 = new TermQuery(new Term("content", "apache"));
        //组合查询条件
        query.add(query1, BooleanClause.Occur.MUST_NOT);
        query.add(query2, BooleanClause.Occur.SHOULD);
        System.out.println(query);
        //执行查询
        execQuery(query);
    }

    /**
     * 通过QueryParser也可以创建Query
     * @throws Exception
     */
    @Test
    public void testQueryParser() throws Exception {
        // 1)添加QueryParser的jar包到工程中。
        // 2)创建一QueryParser对象,需要指定两个参数1:默认搜索域 2:分析器对象
        QueryParser queryParser = new QueryParser("content", new IKAnalyzer());
        // 3)使用QueryParser的parse方法生成一个Query对象
        Query query = queryParser.parse("lucene是一个基于java开发的全文检索工具包");
        System.out.println(query);
        // 4)执行查询
        execQuery(query);
    }

    /**
     * MulitFieldQueryParser可以指定多个默认搜索域
     * @throws Exception
     */
    @Test
    public void testMultiFieldQueryParser() throws Exception {
        //创建一个MultiFieldQueryParser对象
        //参数1:默认搜索域,数组类型
        //参数2:分析器对象
        String[] fields = {"name","content"};
        MultiFieldQueryParser queryParser = new MultiFieldQueryParser(fields, new IKAnalyzer());
        //使用parser方法生成查询对象
        Query query = queryParser.parse("lucene是一个基于java开发的全文检索工具包");
        System.out.println(query);
        //执行查询
        execQuery(query);
    }
}
但在实际开发中一般用Solr



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiha_zhu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值