网站首页 > 开源技术 正文
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提供的强大的全文搜索和查询能力,我们可以处理大量的文档对象存储。我们也可以根据实际需求来添加更多的映射配置、分片存储、副本存储等高级配置内容。
猜你喜欢
- 2024-10-20 项目实训及课程设计指导——Web表示层典型功能实现的应用实例
 - 2024-10-20 前端开发中常用的JS插件大集合(前端插件是什么意思)
 - 2024-10-20 JavaScript—异步提交表单的6种方式
 - 2024-10-20 公司员工工作日志办公系统+vue(员工工作日志模板)
 - 2024-10-20 springboot:实现文件上传下载实时进度条功能【附带源码】
 - 2024-10-20 Web开发者必备,有点酷的文件上传库!——Bootstrap-Fileinput
 - 2024-10-20 图片MD5秒传、分片上传和断点续传
 - 2024-10-20 一文看懂Ajax,学习前端开发的同学不可错过
 - 2024-10-20 Spring Boot实现大文件的分片上传功能?
 - 2024-10-20 Solarwinds Serv-U中的XSS漏洞(CVE-2021-32604)
 
欢迎 你 发表评论:
- 1590℃北京那些看上去很牛的车牌们!(北京厉害车牌)
 - 1107℃2025年度视频去水印软件TOP5对比:哪款最值得用
 - 684℃《我的世界》不同版本的差异 ——新手向
 - 595℃新疆话里的“虫子”
 - 516℃中兴光猫 Telnet下设置大全(中兴光猫命令大全)
 - 514℃蓝牙设备配对失败的系统性解决方案与技术解析
 - 510℃未备份电脑文件数据恢复的七种方法
 - 488℃工艺管道常用英文缩写 英汉对照
 
- 最近发表
 
- 标签列表
 - 
- jdk (81)
 - putty (66)
 - rufus (78)
 - 内网穿透 (89)
 - okhttp (70)
 - powertoys (74)
 - windowsterminal (81)
 - netcat (65)
 - ghostscript (65)
 - veracrypt (65)
 - asp.netcore (70)
 - wrk (67)
 - aspose.words (80)
 - itk (80)
 - ajaxfileupload.js (66)
 - sqlhelper (67)
 - express.js (67)
 - phpmailer (67)
 - xjar (70)
 - redisclient (78)
 - wakeonlan (66)
 - tinygo (85)
 - startbbs (72)
 - webftp (82)
 - vsvim (79)
 
 

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