-
SpringBoot使用ElasticSearch做文档对象的持久化存储?
- 网站名称:SpringBoot使用ElasticSearch做文档对象的持久化存储?
- 网站分类:技术文章
- 收录时间:2025-07-16 15:40
- 网站地址:
“SpringBoot使用ElasticSearch做文档对象的持久化存储?” 网站介绍
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提供的强大的全文搜索和查询能力,我们可以处理大量的文档对象存储。我们也可以根据实际需求来添加更多的映射配置、分片存储、副本存储等高级配置内容。
更多相关网站
- Pug 3.0.0正式发布,不再支持 Node.js 6/8
- topjui(easyui) filebox多图上传(easyui 文件上传)
- 文件上传,排版是伤(文档上传是什么意思)
- 国外免费公共云存储产品有哪些(上)?
- php手把手教你做网站(三十)上传图片生成缩略图
- Nodejs文件上传、监听上传进度(node实现文件上传)
- SPRINGBOOT 实现大文件上传下载、分片、断点续传教程
- 从致远OA-ajax.do任意文件上传漏洞复现到EXP编写
- Axure高保真教程:上传本地图片(axure如何发布)
- 图片上传并回显Ajax异步篇(ajax发送图片)
- 网页中实现文件上传下载的三种解决方案(推荐)
- 使用jQuery ajaxFileUpload+servlet实现文件上传
- 最近发表
- 标签列表
-
- mydisktest_v298 (35)
- sql 日期比较 (33)
- document.appendchild (35)
- 头像打包下载 (35)
- 二调符号库 (23)
- acmecadconverter_8.52绿色版 (25)
- 梦幻诛仙表情包 (36)
- 魔兽模型 (23)
- java面试宝典2019pdf (26)
- disk++ (30)
- vncviewer破解版 (20)
- pk10牛牛 (20)
- 加密与解密第四版pdf (29)
- iteye (26)
- parsevideo (22)
- ckeditor4中文文档 (20)
- centos7.4下载 (32)
- cuda10.1下载 (22)
- intouch2014r2sp1永久授权 (33)
- usb2.0-serial驱动下载 (24)
- 魔兽争霸全图 (21)
- jdk1.8.0_191下载 (27)
- axure9注册码 (30)
- gitlab日志 (20)
- spire.pdf 破解版 (21)