深入浅出spring-data-elasticsearch - 基本案例详解
创始人
2025-02-13 19:40:28
0次

本文提纲

[[194551]]

一、spring-data-elasticsearch-crud 的工程介绍

二、运行 spring-data-elasticsearch-crud 工程

三、spring-data-elasticsearch-crud 工程代码详解

一、spring-data-elasticsearch-crud 的工程介绍

spring-data-elasticsearch-crud 的工程,介绍 Spring Data Elasticsearch 简单的 ES 操作。Spring Data Elasticsearch 可以跟 JPA 进行类比。其使用方法也很简单。

二、运行 spring-data-elasticsearch-crud 工程

注意的是这里使用的是 ElasticSearch 2.3.2。是因为版本对应关系 https://github.com/spring-projects/spring-data-elasticsearch/wiki/Spring-Data-Elasticsearch---Spring-Boot---version-matrix;

  • Spring Boot Version (x) Spring Data Elasticsearch Version (y) Elasticsearch Version (z)
  • x <= 1.3.5 y <= 1.3.4 z <= 1.7.2*
  • x >= 1.4.x 2.0.0 <=y < 5.0.0** 2.0.0 <= z < 5.0.0**
  • * - 只需要你修改下对应的 pom 文件版本号
  • ** - 下一个 ES 的版本会有重大的更新

1. 后台起守护线程启动 Elasticsearch

  1. cd elasticsearch-2.3.2/  
  2. ./bin/elasticsearch -d 

git clone 下载工程 springboot-elasticsearch ,项目地址见 GitHub - https://github.com/JeffLi1993/ ... ample。

下面开始运行工程步骤(Quick Start):

2. 项目结构介绍

  1. org.spring.springboot.controller - Controller 层 
  2. org.spring.springboot.repository - ES 数据操作层 
  3. org.spring.springboot.domain - 实体类 
  4. org.spring.springboot.service - ES 业务逻辑层 
  5. Application - 应用启动类 
  6. application.properties - 应用配置文件,应用启动会自动读取配置 

本地启动的 ES ,就不需要改配置文件了。如果连测试 ES 服务地址,需要修改相应配置

3.编译工程

在项目根目录 spring-data-elasticsearch-crud,运行 maven 指令:

  1. mvn clean install 

4.运行工程

右键运行 Application 应用启动类(位置:/springboot-learning-example/springboot-elasticsearch/src/main/java/org/spring/springboot/Application.java)的 main 函数,这样就成功启动了 springboot-elasticsearch 案例。

用 Postman 工具新增两个城市

a. 新增城市信息

  1. POST http://127.0.0.1:8080/api/city 
  2.  
  3. {     
  4.     "id”:"1", 
  5.     "score":"5", 
  6.     "name":"上海", 
  7.     "description":"上海是个热城市" 
  8. } 
  1. POST http://127.0.0.1:8080/api/city 
  2.  
  3. {     
  4.     "id":"2",     
  5.     "score”:"4", 
  6.     "name”:”温岭", 
  7.     "description":”温岭是个沿海城市" 
  8.  
  9. } 

可以打开 ES 可视化工具 head 插件:http://localhost:9200/_plugin/head/:

(如果不知道怎么安装,请查阅 《Elasticsearch 和插件 elasticsearch-head 安装详解》 http://www.bysocket.com/?p=1744 。)

在「数据浏览」tab,可以查阅到 ES 中数据是否被插入,插入后的数据格式如下:

  1. { 
  2. "_index": "cityindex", 
  3. "_type": "city", 
  4. "_id": "1", 
  5. "_version": 1, 
  6. "_score": 1, 
  7. "_source": {   
  8.     "id":"2",     
  9.     "score”:"4", 
  10.     "name”:”温岭", 
  11.     "description":”温岭是个沿海城市" 
  12. } 
  13. } 

下面是基本查询语句的接口:

a. 普通查询,查询城市描述

  1. GET http://localhost:8080/api/city ... on%3D温岭 

返回 JSON 如下:

  1. [ 
  2.     {         
  3.     "id": 2,         
  4.     "name": "温岭",         
  5.     "description": "温岭是个沿海城市",         
  6.     "score": 4 
  7.     } 
  8. ] 

b. AND 语句查询

  1. GET http://localhost:8080/api/city ... on%3D温岭&score=4 

返回 JSON 如下:

  1. [ 
  2.     {         
  3. "id": 2,         
  4. "name": "温岭",         
  5. "description": "温岭是个沿海城市",         
  6. "score": 4 
  7.     } 
  8. ] 

如果换成 score=5 ,就没有结果了。

c. OR 语句查询

  1. GET http://localhost:8080/api/city ... on%3D上海&score=4 

返回 JSON 如下:

  1. [ 
  2.     {         
  3. "id": 2,         
  4. "name": "温岭",         
  5. "description": "温岭是个沿海城市",         
  6. "score": 4 
  7.     }, 
  8.     {         
  9. "id": 1,         
  10. "name": "上海",         
  11. "description": "上海是个好城市",         
  12. "score": 3 
  13.     } 
  14. ] 

d. NOT 语句查询

  1. GET http://localhost:8080/api/city ... on%3D温州 

返回 JSON 如下:

  1. [ 
  2.     {         
  3. "id": 2,         
  4. "name": "温岭",         
  5. "description": "温岭是个沿海城市",         
  6. "score": 4 
  7.     }, 
  8.     {         
  9. "id": 1,         
  10. "name": "上海",         
  11. "description": "上海是个好城市",         
  12. "score": 3 
  13.     } 
  14. ] 

e. LIKE 语句查询

  1. GET http://localhost:8080/api/city ... on%3D城市 

返回 JSON 如下:

  1. [ 
  2.     {         
  3. "id": 2,         
  4. "name": "温岭",         
  5. "description": "温岭是个沿海城市",         
  6. "score": 4 
  7.     }, 
  8.     {         
  9. "id": 1,         
  10. "name": "上海",         
  11. "description": "上海是个好城市",         
  12. "score": 3 
  13.     } 
  14. ] 

三、spring-data-elasticsearch-crud 工程代码详解

具体代码见 GitHub - https://github.com/JeffLi1993/springboot-learning-example

1.pom.xml 依赖

  1.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/ma ... gt%3B 
  2.      
  3.  
  4.     4.0.0    springboot     
  5. spring-data-elasticsearch-crud     
  6. 0.0.1-SNAPSHOT     
  7. spring-data-elasticsearch-crud :: spring-data-elasticsearch - 基本案例      
  8.  
  9.  
  10.      
  11.         org.springframework.boot         
  12. spring-boot-starter-parent         
  13. 1.5.1.RELEASE     
  14.  
  15.  
  16.  
  17.      
  18.  
  19.  
  20.          
  21.          
  22.             org.springframework.boot            spring-boot-starter-data-elasticsearch         
  23.  
  24.  
  25.  
  26.          
  27.          
  28.             org.springframework.boot            spring-boot-starter-web         
  29.  
  30.  
  31.          
  32.          
  33.             junit            
  34.  junit            
  35.   4.12        
  36.     
  37.      
  38.  
  39.  

这里依赖的 spring-boot-starter-data-elasticsearch 版本是 1.5.1.RELEASE,对应的 spring-data-elasticsearch 版本是 2.1.0.RELEASE。对应官方文档:http://docs.spring.io/spring-d ... html/。后面数据操作层都是通过该 spring-data-elasticsearch 提供的接口实现。

2. application.properties 配置 ES 地址

  1. # ES 
  2. spring.data.elasticsearch.repositories.enabled = true 
  3. spring.data.elasticsearch.cluster-nodes = 127.0.0.1:9300 
  4.  
  5. 默认 9300 是 Java 客户端的端口。9200 是支持 Restful HTTP 的接口。 

更多配置:

  • spring.data.elasticsearch.cluster-name Elasticsearch 集群名。(默认值: elasticsearch)
  • spring.data.elasticsearch.cluster-nodes 集群节点地址列表,用逗号分隔。如果没有指定,就启动一个客户端节点。
  • spring.data.elasticsearch.propertie 用来配置客户端的额外属性。
  • spring.data.elasticsearch.repositories.enabled 开启 Elasticsearch 仓库。(默认值:true。)

3. ES 数据操作层

  1. /** 
  2.  * ES 操作类 
  3.  * 

     

  4.  * Created by bysocket on 17/05/2017. 
  5.  */public interface CityRepository extends ElasticsearchRepository {    /** 
  6.      * AND 语句查询 
  7.      * 
  8.      * @param description 
  9.      * @param score 
  10.      * @return 
  11.      */ 
  12.     List findByDescriptionAndScore(String description, Integer score);    /** 
  13.      * OR 语句查询 
  14.      * 
  15.      * @param description 
  16.      * @param score 
  17.      * @return 
  18.      */ 
  19.     List findByDescriptionOrScore(String description, Integer score);    /** 
  20.      * 查询城市描述 
  21.      * 
  22.      * 等同于下面代码 
  23.      * @Query("{\"bool\" : {\"must\" : {\"term\" : {\"description\" : \"?0\"}}}}") 
  24.      * Page findByDescription(String description, Pageable pageable); 
  25.      * 
  26.      * @param description 
  27.      * @param page 
  28.      * @return 
  29.      */ 
  30.     Page findByDescription(String description, Pageable page);    /** 
  31.      * NOT 语句查询 
  32.      * 
  33.      * @param description 
  34.      * @param page 
  35.      * @return 
  36.      */ 
  37.     Page findByDescriptionNot(String description, Pageable page);    /** 
  38.      * LIKE 语句查询 
  39.      * 
  40.      * @param description 
  41.      * @param page 
  42.      * @return 
  43.      */ 
  44.     Page findByDescriptionLike(String description, Pageable page); 
  45. } 

接口只要继承 ElasticsearchRepository 类即可。默认会提供很多实现,比如 CRUD 和搜索相关的实现。类似于 JPA 读取数据,是使用 CrudRepository 进行操作 ES 数据。支持的默认方法有: count(), findAll(), findOne(ID), delete(ID), deleteAll(), exists(ID), save(DomainObject), save(Iterable)。

另外可以看出,接口的命名是遵循规范的。常用命名规则如下:

关键字 方法命名

  • And findByNameAndPwd
  • Or findByNameOrSex
  • Is findById
  • Between findByIdBetween
  • Like findByNameLike
  • NotLike findByNameNotLike
  • OrderBy findByIdOrderByXDesc
  • Not findByNameNot

4. 实体类

  1. /** 
  2.  * 城市实体类 
  3.  * 

     

  4.  * Created by bysocket on 03/05/2017. 
  5.  */@Document(indexName = "province", type = "city")public class City implements Serializable { 
  6.     private static final long serialVersionUID = -1L;    /** 
  7.      * 城市编号 
  8.      */ 
  9.     private Long id;    /** 
  10.      * 城市名称 
  11.      */ 
  12.     private String name;    /** 
  13.      * 描述 
  14.      */ 
  15.     private String description;    /** 
  16.      * 城市评分 
  17.      */ 
  18.     private Integer score;    
  19. } 

注意

a. City 属性名不支持驼峰式。

b. indexName 配置必须是全部小写,不然会出异常。

org.elasticsearch.indices.InvalidIndexNameException: Invalid index name [provinceIndex], must be lowercase

【本文为51CTO专栏作者“李强强”的原创稿件,转载请通过51CTO联系作者获取授权】

戳这里,看该作者更多好文

相关内容

热门资讯

PHP新手之PHP入门 PHP是一种易于学习和使用的服务器端脚本语言。只需要很少的编程知识你就能使用PHP建立一个真正交互的...
网络中立的未来 网络中立性是什... 《牛津词典》中对“网络中立”的解释是“电信运营商应秉持的一种原则,即不考虑来源地提供所有内容和应用的...
各种千兆交换机的数据接口类型详... 千兆交换机有很多值得学习的地方,这里我们主要介绍各种千兆交换机的数据接口类型,作为局域网的主要连接设...
粉嫩如何诠释霸道 东芝M805... “霸道粉”是个什么玩意东芝M805拿过来的时候,笔者扑哧笑了,不是笑这款笔记本,而是笑这款产品的颜色...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
什么是大数据安全 什么是大数据... 在《为什么需要大数据安全分析》一文中,我们已经阐述了一个重要观点,即:安全要素信息呈现出大数据的特征...
只需三步,让你掌握阿尔法路由器... 请参照以下阿尔法路由器设置方法,通过浏览器进入及设置宽带路由器。经过这三个步骤的设置,基本上能够熟悉...
如何更省钱? 近期特价热门硒鼓... 如今激光打印设备已经成为商务或企业的绝对主力办公设备,但采购者往往忽视了激光打印设备所用的耗材,相对...
全面诠释网络负载均衡 负载均衡的出现大大缓解了服务器的压力,更是有效的利用了资源,提高了效率。那么我们现在来说一下网络负载...
如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...