编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

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

wxchong 2024-10-20 15:16:40 开源技术 196 ℃ 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提供的强大的全文搜索和查询能力,我们可以处理大量的文档对象存储。我们也可以根据实际需求来添加更多的映射配置、分片存储、副本存储等高级配置内容。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表