百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

SpringBoot使用ElasticSearch做文档对象的持久化存储?

nanshan 2025-07-03 18:20 3 浏览 0 评论

ElasticSearch 是一个基于 Lucene 的开源搜索引擎,广泛应用于日志分析、全文搜索、复杂查询等领域,在有些场景中使用ElasticSearch进行文档对象的持久化存储是一个很不错的选择,特别是在一些需要全文检索,实时分析以及高性能查询的场景中表现非常的突出。下面我们就来通过一个简单的例子来演示如何使用Elasticsearch来进行存储和检索文档对象。

前提条件

要使用Elasticsearch的前提是确保已经安装好了ElasticSearch,并且ElasticSearch能够正常的运行。接下来就是在我们的SpringBoot项目中引入ElasticSearch依赖配置,如下所示。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

这里需要追SpringBoot的版本与ElasticSearch的版本对应,博主采用的是SpringBoot2.5.15,ElasticSearch版本是7.10.2,当然你也可以选择最新的版本做实验。但是生产环境建议使用稳定版本。

配置ElasticSearch的连接

在application.properties配置文件中添加ElasticSearch的连接信息。如下所示。

spring.elasticsearch.uris=http://localhost:9200
spring.elasticsearch.username=your_username
spring.elasticsearch.password=your_password

创建实体对象

创建实体类并且通过@Document注解来标注这个类,指定索引名称等属性,如下所示。

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "documents")
public class DocumentEntity {

    /**
     * 文档ID
     */
    @Id
    private String id;
    /**
     * 文档名
     */
    private String name;
    /**
     * 文档内容
     */
    private String content;
    /**
     * 所属部门
     */
    private Long deptId;
    /**
     * 所属部门ID
     */
    private String deptName;
    /**
     * 数据来源
     */
    private String dataResource;
    /**
     * 文件路径
     */
    private String filePath;
}

创建Repository接口

创建接口并继承ElasticsearchRepository。这样Spring Data Elasticsearch会自动为你生成基本的CRUD操作方法。

public interface DocumentRepository extends ElasticsearchRepository<DocumentEntity, String> {

    @Query("{\"match\": {\"content\": \"?0\"}}")
    List<DocumentEntity> findByContent(String content);

    @Query("{\"match\": {\"name\": \"?0\"}}")
    List<DocumentEntity> findByName(String name);
}

编写控制器

创建控制器类,提供API接口供前端或其他服务调用,如下所示。

@RestController
@RequestMapping("/api/documents")
public class DocumentController {

    @Autowired
    private DocumentRepository documentRepository;

    @Autowired
    private SnowflakeIdUtils snowflakeIdUtils;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;



    /**
     * 上传文档
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public AjaxResult uploadDocument(@RequestParam("file") MultipartFile file) throws IOException {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        String fileName = FileUploadUtils.upload(filePath, file);
        String newFilePath = fileName.replace("/profile/upload",filePath);
        String oldContent = ReadWordUtils.readDocumentNew(newFilePath);
        DocumentEntity document = new DocumentEntity();
        document.setId(snowflakeIdUtils.stringId());
        document.setName(file.getOriginalFilename());
        document.setContent(oldContent);
        document.setDeptId(SecurityUtils.getDeptId());
        document.setDeptName(SecurityUtils.getDeptName());
        document.setDataResource(SecurityUtils.getDeptName());
        document.setFilePath(fileName);
        documentRepository.save(document);
        return AjaxResult.success();
    }

    /**
     * 查询文档内容
     * @param query
     * @param field
     * @return
     */
    @GetMapping("/search")
    public AjaxResult searchDocuments(@RequestParam("q") String query, @RequestParam("field") String field) {
        if (field.equals("content")) {
            List<DocumentEntity> byContent = documentRepository.findByContent(query);
            return AjaxResult.success(byContent);
        } else if (field.equals("name")) {
            List<DocumentEntity> byName = documentRepository.findByName(query);
            return AjaxResult.success(byName);
        } else {
            throw new IllegalArgumentException("Invalid search field: " + field);
        }
    }


    @GetMapping("/searchR")
    public AjaxResult searchByRest(@RequestParam("q") String query, @RequestParam("field") String field) {
        String[] includedFields = {"id","name","deptId","deptName","dataResource","filePath"};
        Query searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery(field,query))
                .withSourceFilter(new FetchSourceFilter(includedFields,null))
                .build();
        List<DocumentEntity> collect = elasticsearchRestTemplate.search(searchQuery, DocumentEntity.class)
                .stream()
                .map(searchHit -> searchHit.getContent())
                .collect(Collectors.toList());
        return AjaxResult.success(collect);
    }


    /**
     * 根据ID删除文档
     * @param id
     * @return
     */
    @GetMapping("/delete")
    public AjaxResult deleteById(@RequestParam("id") String id){
        documentRepository.deleteById(id);
        return AjaxResult.success();
    }
}

总结

通过上述步骤,你可以通过ElasticSearch来实现文档对象的持久化存储和检索。通过ElasticSearch提供的强大的全文搜索和查询能力,我们可以处理大量的文档对象存储。我们也可以根据实际需求来添加更多的映射配置、分片存储、副本存储等高级配置内容。

相关推荐

在 Ubuntu 上安装 Zabbix(以 Zabbix 6.4 LTS 版本为例)

Zabbix是一个流行的开源监控解决方案,能够监控各种网络参数和服务器健康状态。一、环境准备系统要求Ubuntu20.04/22.04LTS至少2GBRAM(生产环境建议4GB+)至少1...

如何在 Ubuntu 24.04 服务器上安装 Apache Solr

ApacheSolr是一个免费、开源的搜索平台,广泛应用于实时索引。其强大的可扩展性和容错能力使其在高流量互联网场景下表现优异。Solr基于Java开发,提供了分布式索引、复制、负载均衡及自...

如何在 Ubuntu 24.04 LTS 或 22.04/20.04 上安装 Apache Maven

Maven是由Apache托管的开源工具,用于管理Java项目。它包含一个项目对象模型(POM):一个配置文件(XML),其中包含项目的基本信息,包括配置、项目依赖项等。Maven可以处理...

Cursor的终极对手——Trae Pro最新系统提示词

前段时间,字节的AI编程神器Trae国际版,终于甩出了Pro订阅计划!很多对它又爱又恨的小伙伴,直呼:终于等到你。爱它,是因为Trae长期免费+体验真香;恨它?还不是那该死的排队等待,...

AI系统提示词:V0(ai代码提示)

以下是对V0系统提示词(SystemPrompt)的分部分讲解与解读,帮助你理解其核心内容和设计意图。V0系统提示词##CoreIdentity-Youarev0,Vercel&...

8岁男童失踪第13天,搜救人员发现可疑水库,更恶心的事情发生了

Lookingatyourrequest,Ineedtorewritethearticleaboutthe8-year-oldmissingboywhilemaking...

docker常用指令及安装rabbitMQ(docker安装zabbix)

一、docker常用指令启动docker:systemctlstartdocker停止docker:systemctlstopdocker重启docker:systemctlrestart...

三步教你用Elasticsearch+PyMuPDF实现PDF大文件秒搜!

面对100页以上的大型PDF文件时,阅读和搜索往往效率低下。传统关系型数据库在处理此类数据时容易遇到性能瓶颈,而Elasticsearch凭借其强大的全文检索和分布式架构,成为理想解决方案。通过...

ElasticSearch中文分词插件(IK)安装

坚持原创,共同进步!请关注我,后续分享更精彩!!!前言ElasticSearch默认的分词插件对中文支持很不友好。一段话按规则会以每个中文字符来拆解,再分别建立倒排索引。如"中华人民共和国国歌...

SpringBoot使用ElasticSearch做文档对象的持久化存储?

ElasticSearch是一个基于Lucene的开源搜索引擎,广泛应用于日志分析、全文搜索、复杂查询等领域,在有些场景中使用ElasticSearch进行文档对象的持久化存储是一个很不错的选择...

Elasticsearch数据迁移方案(elasticsearch copyto)

前言最近小编要去给客户部署一套系统涉及到了Mysql和ES数据的迁移,下面就给大家分享一下ES数据迁移的几套方案,根据具体的使用场景来选择不同的迁移方案能使你事倍功半,话多说下面就一一介绍。Elast...

Rancher部署单体ElasticSearch(rancher2.5部署)

Rancher是k8s图形管理界面,之前曾有写文章介绍如何安装。ElasticSearch是热门搜索引擎,很多地方都有用到,常规安装部署略显繁琐,本文介绍在k8s下用rancher简易部署ES。1.在...

Elasticsearch在Java项目的搜索实践:从零开始构建高效搜索系统

Elasticsearch在Java项目中的搜索实践:从零开始构建高效搜索系统在现代的Java项目中,数据量激增,传统的数据库查询方式已经无法满足快速检索的需求。这时,Elasticsearch(E...

小白入门-Kibana安装(kibana安装配置)

一Kibana基础1.1介绍Kibana是一款免费且开放的前端应用程序,其基础是ElasticStack,可以为Elasticsearch中索引的数据提供搜索和数据可视化功能。Kiban...

Docker上使用Elasticsearch,Logstash,Kibana

在对一个项目做性能测试时我需要处理我们web服务器的访问日志来分析当前用户的访问情况。因此,我想这是试用ELK的一个好机会。ELK栈首先要注意的是使用它是非常简单的。从决定使用ELK到在本机上搭一个...

取消回复欢迎 发表评论: