当前位置: 代码网 > it编程>编程语言>Java > springboot集成Lucene的详细指南

springboot集成Lucene的详细指南

2025年05月04日 Java 我要评论
以下是 spring boot 集成 lucene 的详细步骤:添加依赖在 spring boot 项目的 pom.xml 文件中添加 lucene 的依赖,常用的核心依赖和中文分词器依赖如下:<

以下是 spring boot 集成 lucene 的详细步骤:

添加依赖

在 spring boot 项目的 pom.xml 文件中添加 lucene 的依赖,常用的核心依赖和中文分词器依赖如下:

<dependency>
    <groupid>org.apache.lucene</groupid>
    <artifactid>lucene-core</artifactid>
    <version>8.11.0</version>
</dependency>
<dependency>
    <groupid>org.apache.lucene</groupid>
    <artifactid>lucene-analyzers-common</artifactid>
    <version>8.11.0</version>
</dependency>
<dependency>
    <groupid>org.wltea</groupid>
    <artifactid>ik-analyzer</artifactid>
    <version>20200623</version>
</dependency>

创建配置类

创建一个配置类,对 lucene 的相关组件进行配置,如索引目录、分词器等:

import org.apache.lucene.analysis.analyzer;
import org.apache.lucene.analysis.standard.standardanalyzer;
import org.apache.lucene.store.directory;
import org.apache.lucene.store.fsdirectory;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import java.nio.file.paths;
 
@configuration
public class luceneconfig {
 
    private final string indexpath = "indexdir"; // 索引存储路径
 
    @bean
    public directory directory() throws exception {
        return fsdirectory.open(paths.get(indexpath));
    }
 
    @bean
    public analyzer analyzer() {
        return new standardanalyzer(); // 可替换为其他分词器,如 ikanalyzer
    }
}

创建实体类

根据实际需求创建一个实体类,用于表示要索引的文档对象,例如:

public class book {
    private string id;
    private string title;
    private string author;
    private string content;
    // 省略getter、setter等方法
}

创建索引服务类

创建一个服务类,用于处理索引相关的操作,如创建索引、添加文档、删除文档等:

import org.apache.lucene.document.document;
import org.apache.lucene.document.field;
import org.apache.lucene.document.textfield;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.apache.lucene.store.directory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
 
import java.io.ioexception;
import java.util.arraylist;
import java.util.list;
 
@service
public class luceneindexservice {
 
    @autowired
    private directory directory;
 
    @autowired
    private analyzer analyzer;
 
    // 创建索引
    public void createindex(list<book> booklist) throws ioexception {
        indexwriterconfig config = new indexwriterconfig(analyzer);
        indexwriter writer = new indexwriter(directory, config);
        for (book book : booklist) {
            document doc = new document();
            doc.add(new textfield("id", book.getid(), field.store.yes));
            doc.add(new textfield("title", book.gettitle(), field.store.yes));
            doc.add(new textfield("author", book.getauthor(), field.store.yes));
            doc.add(new textfield("content", book.getcontent(), field.store.yes));
            writer.adddocument(doc);
        }
        writer.close();
    }
 
    // 添加文档到索引
    public void adddocument(book book) throws ioexception {
        indexwriterconfig config = new indexwriterconfig(analyzer);
        indexwriter writer = new indexwriter(directory, config);
        document doc = new document();
        doc.add(new textfield("id", book.getid(), field.store.yes));
        doc.add(new textfield("title", book.gettitle(), field.store.yes));
        doc.add(new textfield("author", book.getauthor(), field.store.yes));
        doc.add(new textfield("content", book.getcontent(), field.store.yes));
        writer.adddocument(doc);
        writer.close();
    }
 
    // 删除文档
    public void deletedocument(string id) throws ioexception {
        indexwriterconfig config = new indexwriterconfig(analyzer);
        indexwriter writer = new indexwriter(directory, config);
        writer.deletedocuments(new term("id", id));
        writer.forcemergedeletes();
        writer.close();
    }
}

创建搜索服务类

创建一个服务类,用于处理搜索相关的操作,如简单搜索、高亮搜索等:

import org.apache.lucene.analysis.analyzer;
import org.apache.lucene.document.document;
import org.apache.lucene.index.directoryreader;
import org.apache.lucene.queryparser.classic.queryparser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.store.directory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
 
import java.io.ioexception;
import java.util.arraylist;
import java.util.list;
import java.util.map;
 
@service
public class lucenesearchservice {
 
    @autowired
    private directory directory;
 
    @autowired
    private analyzer analyzer;
 
    // 简单搜索
    public list<document> search(string querystr) throws exception {
        directoryreader reader = directoryreader.open(directory);
        indexsearcher searcher = new indexsearcher(reader);
        queryparser parser = new queryparser("content", analyzer);
        query query = parser.parse(querystr);
        topdocs results = searcher.search(query, 10);
        list<document> docs = new arraylist<>();
        for (scoredoc scoredoc : results.scoredocs) {
            docs.add(searcher.doc(scoredoc.doc));
        }
        reader.close();
        return docs;
    }
 
    // 高亮搜索
    public list<map<string, string>> searchwithhighlight(string querystr) throws exception {
        directoryreader reader = directoryreader.open(directory);
        indexsearcher searcher = new indexsearcher(reader);
        queryparser parser = new queryparser("content", analyzer);
        query query = parser.parse(querystr);
        topdocs results = searcher.search(query, 10);
        list<map<string, string>> docs = new arraylist<>();
 
        simplehtmlformatter htmlformatter = new simplehtmlformatter("<span style='color:red'>", "</span>");
        highlighter highlighter = new highlighter(htmlformatter, new queryscorer(query));
 
        for (scoredoc scoredoc : results.scoredocs) {
            document doc = searcher.doc(scoredoc.doc);
            string content = doc.get("content");
            tokenstream tokenstream = analyzer.tokenstream("content", new stringreader(content));
            string highlightedtext = highlighter.getbestfragment(tokenstream, content);
 
            map<string, string> docmap = new hashmap<>();
            docmap.put("id", doc.get("id"));
            docmap.put("title", doc.get("title"));
            docmap.put("author", doc.get("author"));
            docmap.put("content", highlightedtext != null ? highlightedtext : content);
            docs.add(docmap);
        }
        reader.close();
        return docs;
    }
}

创建控制器类

创建一个控制器类,用于处理 http 请求,并调用相应的服务类方法:

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.*;
 
import java.io.ioexception;
import java.util.list;
import java.util.map;
 
@restcontroller
@requestmapping("/search")
public class searchcontroller {
 
    @autowired
    private luceneindexservice luceneindexservice;
 
    @autowired
    private lucenesearchservice lucenesearchservice;
 
    // 创建索引
    @postmapping("/index")
    public string createindex(@requestbody list<book> booklist) {
        try {
            luceneindexservice.createindex(booklist);
            return "索引创建成功";
        } catch (ioexception e) {
            e.printstacktrace();
            return "索引创建失败";
        }
    }
 
    // 搜索结果
    @getmapping
    public list<document> search(@requestparam string query) {
        try {
            return lucenesearchservice.search(query);
        } catch (exception e) {
            e.printstacktrace();
            return new arraylist<>();
        }
    }
 
    // 高亮搜索
    @getmapping("/highlight")
    public list<map<string, string>> searchwithhighlight(@requestparam string query) {
        try {
            return lucenesearchservice.searchwithhighlight(query);
        } catch (exception e) {
            e.printstacktrace();
            return new arraylist<>();
        }
    }
}

使用示例

此外,还可以根据实际需求对上述代码进行扩展和优化,例如添加更复杂的查询条件、实现分页功能、优化索引的性能等。

创建索引 :启动 spring boot 应用后,发送一个 post 请求到http://localhost:8080/search/index,请求体中包含要索引的图书列表,如:

[
    {
        "id": "1",
        "title": " lucene in action ",
        "author": "robert muir",
        "content": "lucene is a search library from apache"
    },
    {
        "id": "2",
        "title": " java编程思想 ",
        "author": "bruce eckel",
        "content": "java is a programming language"
    }
]

简单搜索 :发送一个 get 请求到http://localhost:8080/search/?query=java,即可搜索出与“java”相关的文档。

高亮搜索 :发送一个 get 请求到http://localhost:8080/search/highlight/?query=java,即可搜索出与“java”相关的文档,并且搜索结果中的“java”会以高亮显示。

到此这篇关于springboot集成lucene的详细指南的文章就介绍到这了,更多相关springboot集成lucene内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com