赞
踩
原文网址:Spring Data Elasticsearch--ElasticsearchRestTemplate--使用/教程/实例_IT利刃出鞘的博客-CSDN博客
技术星球
欢迎来到IT技术星球,网站是:learn.skyofit.com(或者百度直接搜:自学精灵)。内容有:Java真实面试题、Java设计模式实战、Shiro项目实战、Idea和Navicat的“魔法”教程、SpringBoot进阶、架构与微服务设计、高并发实战、Java入门实战、网站防御技术、JavaWeb入门项目等。网站的定位:超高的质量、超高的真实性、超高的实用性。欢迎加入~
说明
本文用实例来介绍如何使用Spring Data Elasticsearch的ElasticsearchRestTemplate来操作ES。包括:索引的增删等、文档的增删改查、文档的动态查询(或者说:多条件查询、复杂查询)。
动态查询的含义:查询条件有多个时,某个查询条件可能有也可能没有,这时就需要手动判断,如果为空则不拼装搜索条件。
本文用博客的业务进行示例。索引名:blog,里边有标题、内容、作者、创建时间等。
官网
为什么用ElasticsearchRestTemplate
在Spring Data Elasticsearch4.0之后,ElasticsearchRepository里边大部分搜索方法都已经被标记为废弃,注释中让我们用两种方法来操作:
使用@Query自定义DSL不支持动态查询,其用法见:Spring Data Elasticsearch--使用/教程/实例_IT利刃出鞘的博客-CSDN博客
ElasticsearchOperations支持动态查询,ElasticsearchRestTemplate是ElasticsearchOperations的实现类。
依赖
主要是spring-boot-starter-data-elasticsearch这个依赖:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
- </dependency>
配置
- spring:
- elasticsearch:
- rest:
- # 如果是集群,用逗号隔开
- uris: http://127.0.0.1:9200
- # username: xxx
- # password: yyy
- # connection-timeout: 1
- # read-timeout: 30
-
- # 上边是客户端High Level REST Client的配置,推荐使用。
-
- # 下边是reactive客户端的配置,非官方,不推荐。
- # data:
- # elasticsearch:
- # client:
- # reactive:
- # endpoints: 127.0.0.1:9200
- # username: xxx
- # password: yyy
- # connection-timeout: 1
- # socket-timeout: 30
- # use-ssl: false
整个pom.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.3.12.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <groupId>com.example</groupId>
- <artifactId>demo_spring-data-elasticsearch</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <name>demo_spring-data-elasticsearch</name>
- <description>demo_spring-data-elasticsearch</description>
- <properties>
- <java.version>1.8</java.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <optional>true</optional>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>com.github.xiaoymin</groupId>
- <artifactId>knife4j-spring-boot-starter</artifactId>
- <version>3.0.3</version>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <configuration>
- <excludes>
- <exclude>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </exclude>
- </excludes>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- </project>
索引结构
http://localhost:9200/
PUT blog
- {
- "mappings": {
- "properties": {
- "id":{
- "type":"long"
- },
- "title": {
- "type": "text"
- },
- "content": {
- "type": "text"
- },
- "author":{
- "type": "text",
- "fields": {
- "keyword": {
- "type": "keyword"
- }
- }
- },
- "category":{
- "type": "keyword"
- },
- "createTime": {
- "type": "date",
- "format":"yyyy-MM-dd HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd HH:mm:ss||epoch_millis"
- },
- "updateTime": {
- "type": "date",
- "format":"yyyy-MM-dd HH:mm:ss.SSS||yyyy-MM-dd'T'HH:mm:ss.SSS||yyyy-MM-dd HH:mm:ss||epoch_millis"
- },
- "status":{
- "type":"integer"
- },
- "serialNum": {
- "type": "keyword"
- }
- }
- }
- }
数据
http://localhost:9200/
POST _bulk
- {"index":{"_index":"blog","_id":1}}
- {"blogId":1,"title":"Spring Data ElasticSearch学习教程1","content":"这是批量添加的文档1","author":"Iron Man","category":"ElasticSearch","status":1,"serialNum":"1","createTime":"2021-10-10 11:52:01.249","updateTime":null}
- {"index":{"_index":"blog","_id":2}}
- {"blogId":2,"title":"Spring Data ElasticSearch学习教程2","content":"这是批量添加的文档2","author":"Iron Man","category":"ElasticSearch","status":1,"serialNum":"2","createTime":"2021-10-10 11:52:02.249","updateTime":null}
- {"index":{"_index":"blog","_id":3}}
- {"blogId":3,"title":"Spring Data ElasticSearch学习教程3","content":"这是批量添加的文档3","author":"Captain America","category":"ElasticSearch","status":1,"serialNum":"3","createTime":"2021-10-10 11:52:03.249","updateTime":null}
- {"index":{"_index":"blog","_id":4}}
- {"blogId":4,"title":"Spring Data ElasticSearch学习教程4","content":"这是批量添加的文档4","author":"Captain America","category":"ElasticSearch","status":1,"serialNum":"4","createTime":"2021-10-10 11:52:04.249","updateTime":null}
- {"index":{"_index":"blog","_id":5}}
- {"blogId":5,"title":"Spring Data ElasticSearch学习教程5","content":"这是批量添加的文档5","author":"Spider Man","category":"ElasticSearch","status":1,"serialNum":"5","createTime":"2021-10-10 11:52:05.249","updateTime":null}
- {"index":{"_index":"blog","_id":6}}
- {"blogId":6,"title":"Java学习教程6","content":"这是批量添加的文档6","author":"Spider Man","category":"ElasticSearch","status":1,"serialNum":"6","createTime":"2021-10-10 11:52:06.249","updateTime":null}
- {"index":{"_index":"blog","_id":7}}
- {"blogId":7,"title":"Java学习教程7","content":"这是批量添加的文档7","author":"Iron Man","category":"ElasticSearch","status":1,"serialNum":"7","createTime":"2021-10-10 11:52:07.249","updateTime":null}
- {"index":{"_index":"blog","_id":8}}
- {"blogId":8,"title":"Java学习教程8","content":"这是批量添加的文档8","author":"Iron Man","category":"ElasticSearch","status":1,"serialNum":"8","createTime":"2021-10-10 11:52:08.249","updateTime":null}
- {"index":{"_index":"blog","_id":9}}
- {"blogId":9,"title":"Java学习教程9","content":"这是批量添加的文档9","author":"Captain America","category":"ElasticSearch","status":1,"serialNum":"9","createTime":"2021-10-10 11:52:09.249","updateTime":null}
- {"index":{"_index":"blog","_id":10}}
- {"blogId":10,"title":"Java学习教程10","content":"这是批量添加的文档10","author":"God Of Thunder","category":"ElasticSearch","status":1,"serialNum":"10","createTime":"2021-10-10 11:52:10.249","updateTime":null}
-
执行后的结果
- package com.example.demo.entity;
-
- import com.fasterxml.jackson.annotation.JsonFormat;
- import lombok.Data;
- import org.springframework.data.annotation.Id;
- import org.springframework.data.elasticsearch.annotations.DateFormat;
- import org.springframework.data.elasticsearch.annotations.Document;
- import org.springframework.data.elasticsearch.annotations.Field;
- import org.springframework.data.elasticsearch.annotations.FieldType;
-
- import java.util.Date;
-
- @Data
- @Document(indexName = "blog", shards = 1, replicas = 1)
- public class Blog {
- //此项作为id,不会写到_source里边。
- @Id
- private Long blogId;
-
- @Field(type = FieldType.Text)
- private String title;
-
- @Field(type = FieldType.Text)
- private String content;
-
- @Field(type = FieldType.Text)
- private String author;
-
- //博客所属分类。
- @Field(type = FieldType.Keyword)
- private String category;
-
- //0: 未发布(草稿) 1:已发布 2:已删除
- @Field(type = FieldType.Integer)
- private int status;
-
- //序列号,用于给外部展示的id
- @Field(type = FieldType.Keyword)
- private String serialNum;
-
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
- @Field(type= FieldType.Date, format= DateFormat.custom, pattern="yyyy-MM-dd HH:mm:ss.SSS")
- private Date createTime;
-
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
- @Field(type=FieldType.Date, format=DateFormat.custom, pattern="yyyy-MM-dd HH:mm:ss.SSS")
- private Date updateTime;
- }
本处只是展示索引的操作方法,项目中不会这样创建索引,而是手写DSL去创建。
- package com.example.demo.controller;
-
- import com.example.demo.entity.Blog;
- import io.swagger.annotations.Api;
- import io.swagger.annotations.ApiOperation;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- /**
- * 本处只是展示索引的操作方法,项目中不会这样创建索引,而是手写DSL去创建。
- */
- @Api(tags = "索引操作(用不到)")
- @RestController
- @RequestMapping("index")
- public class IndexController {
- @Autowired
- private ElasticsearchRestTemplate elasticsearchRestTemplate;
-
-
- @ApiOperation("创建索引")
- @PostMapping("createIndex")
- public String createIndex() {
- // 创建索引,会根据Blog类的@Document注解信息来创建
- elasticsearchRestTemplate.createIndex(Blog.class);
-
- // 配置映射,会根据Item类中的id、Field等字段来自动完成映射
- elasticsearchRestTemplate.putMapping(Blog.class);
- return "success";
- }
-
- @ApiOperation("创建索引")
- @PostMapping("deleteIndex")
- public String deleteIndex() {
- // 删除索引,会根据Blog类的@Document注解信息来删除
- elasticsearchRestTemplate.deleteIndex(Blog.class);
- return "success";
- }
- }
本处介绍常用的一些方法,这些方法能够满足开发中所有需求:
上边是文章的部分内容,为便于维护,全文已转移至此网址:Spring Data Elasticsearch-ElasticsearchRestTemplate-使用实例 - 自学精灵
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。