深入浅出spring-data-elasticsearch - 基本案例详解

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

本文提纲

[[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":"上海是个热城市" 
  1. POST http://127.0.0.1:8080/api/city 
  2.  
  3. {     
  4.     "id":"2",     
  5.     "score”:"4", 
  6.     "name”:”温岭"
  7.     "description":”温岭是个沿海城市" 
  8.  

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

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

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

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

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

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

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

返回 JSON 如下:

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

b. AND 语句查询

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

返回 JSON 如下:

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

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

c. OR 语句查询

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

返回 JSON 如下:

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

d. NOT 语句查询

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

返回 JSON 如下:

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

e. LIKE 语句查询

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

返回 JSON 如下:

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

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

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

1.pom.xml 依赖

  1. <?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" 
  2.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/ma ... gt%3B 
  3.      
  4.  
  5.     <modelVersion>4.0.0</modelVersion>    <groupId>springboot</groupId>     
  6. <artifactId>spring-data-elasticsearch-crud</artifactId>     
  7. <version>0.0.1-SNAPSHOT</version>     
  8. <name>spring-data-elasticsearch-crud :: spring-data-elasticsearch - 基本案例 </name>     
  9.  
  10. <!-- Spring Boot 启动父依赖 --> 
  11.     <parent> 
  12.         <groupId>org.springframework.boot</groupId>         
  13. <artifactId>spring-boot-starter-parent</artifactId>         
  14. <version>1.5.1.RELEASE</version>     
  15. </parent> 
  16.  
  17.  
  18.     <dependencies> 
  19.  
  20.  
  21.         <!-- Spring Boot Elasticsearch 依赖 --> 
  22.         <dependency> 
  23.             <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>         
  24. </dependency> 
  25.  
  26.  
  27.         <!-- Spring Boot Web 依赖 --> 
  28.         <dependency> 
  29.             <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency> 
  30.  
  31.  
  32.         <!-- Junit --> 
  33.         <dependency> 
  34.             <groupId>junit</groupId>            
  35.  <artifactId>junit</artifactId>            
  36.   <version>4.12</version>        
  37.    </dependency> 
  38.     </dependencies> 
  39.  
  40. </project> 

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

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

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

关键字 方法命名

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

4. 实体类

  1. /** 
  2.  * 城市实体类 
  3.  * <p> 
  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;    

注意

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

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

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

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

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

责任编辑:武晓燕 来源: 51CTO专栏
相关推荐

2017-06-06 15:24:13

springElasticSear架构

2017-06-14 10:53:58

spring-data快速入门

2022-01-12 08:54:52

Spring编程架构设计

2011-05-05 14:44:43

SurfaceFlinSurfaceActivity

2021-03-16 08:54:35

AQSAbstractQueJava

2011-07-04 10:39:57

Web

2009-06-22 15:34:00

Javascript

2009-06-18 10:23:03

Javascript 基本框架

2020-05-27 20:25:47

SpringSpringBoot数据

2019-01-07 15:29:07

HadoopYarn架构调度器

2017-07-02 18:04:53

块加密算法AES算法

2012-05-21 10:06:26

FrameworkCocoa

2021-07-20 15:20:02

FlatBuffers阿里云Java

2022-09-26 09:01:15

语言数据JavaScript

2022-09-29 09:19:04

线程池并发线程

2011-01-27 10:11:46

J2EEjavaspring

2012-02-21 13:55:45

JavaScript

2019-11-11 14:51:19

Java数据结构Properties

2009-11-30 16:46:29

学习Linux

2009-11-18 13:30:37

Oracle Sequ
点赞
收藏

51CTO技术栈公众号