springboot集成Lucene的详细指南

2025-05-04 17:50

本文主要是介绍springboot集成Lucene的详细指南,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《springboot集成Lucene的详细指南》这篇文章主要为大家详细介绍了springboot集成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 = China编程new IndexWriter(directorypython, 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(DppdpICOqi"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.www.chinasem.cnput("content", highlightedText != null ? highlightedText : content);
            docs.add(docMap);
        }
        reader.close();
        return docs;
    }
}

创建控制器类

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

impoandroidrt 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内容请搜索编程China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!

这篇关于springboot集成Lucene的详细指南的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154481

相关文章

Spring @Scheduled注解及工作原理

《Spring@Scheduled注解及工作原理》Spring的@Scheduled注解用于标记定时任务,无需额外库,需配置@EnableScheduling,设置fixedRate、fixedDe... 目录1.@Scheduled注解定义2.配置 @Scheduled2.1 开启定时任务支持2.2 创建

SpringBoot中使用Flux实现流式返回的方法小结

《SpringBoot中使用Flux实现流式返回的方法小结》文章介绍流式返回(StreamingResponse)在SpringBoot中通过Flux实现,优势包括提升用户体验、降低内存消耗、支持长连... 目录背景流式返回的核心概念与优势1. 提升用户体验2. 降低内存消耗3. 支持长连接与实时通信在Sp

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Mac系统下卸载JAVA和JDK的步骤

《Mac系统下卸载JAVA和JDK的步骤》JDK是Java语言的软件开发工具包,它提供了开发和运行Java应用程序所需的工具、库和资源,:本文主要介绍Mac系统下卸载JAVA和JDK的相关资料,需... 目录1. 卸载系统自带的 Java 版本检查当前 Java 版本通过命令卸载系统 Java2. 卸载自定

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

Python中图片与PDF识别文本(OCR)的全面指南

《Python中图片与PDF识别文本(OCR)的全面指南》在数据爆炸时代,80%的企业数据以非结构化形式存在,其中PDF和图像是最主要的载体,本文将深入探索Python中OCR技术如何将这些数字纸张转... 目录一、OCR技术核心原理二、python图像识别四大工具库1. Pytesseract - 经典O

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比

《CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比》CSS中的position属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布... css 中的 position 属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布局和层叠关