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

『  风云说:能分享自己职位的知识的领导是个好领导。 』

运行环境:JDK 7 或 8,Maven 3.0+

技术栈:SpringBoot 1.5+, Spring Data Elasticsearch 1.5+ ,ElasticSearch 2.3.2

本文提纲

一、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

cdelasticsearch-2.3.2/./bin/elasticsearch -d

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

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

2. 项目结构介绍

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

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

3.编译工程

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

mvnclean install

4.运行工程

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

用 Postman 工具新增两个城市

a. 新增城市信息

POSThttp://127.0.0.1:8080/api/city{"id”:"1","score":"5","name":"上海","description":"上海是个热城市"}

POSThttp://127.0.0.1:8080/api/city{"id":"2","score”:"4","name”:”温岭","description":”温岭是个沿海城市"}

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

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

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

{"_index":"cityindex","_type":"city","_id":"1","_version":1,"_score":1,"_source": {"id":"2","score”:"4","name”:”温岭","description":”温岭是个沿海城市"}}

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

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

GEThttp://localhost:8080/api/city ...on%3D温岭

返回 JSON 如下:

[{"id":2,"name":"温岭","description":"温岭是个沿海城市","score":4}]

b. AND 语句查询

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

返回 JSON 如下:

[{"id":2,"name":"温岭","description":"温岭是个沿海城市","score":4}]

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

c. OR 语句查询

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

返回 JSON 如下:

[{"id":2,"name":"温岭","description":"温岭是个沿海城市","score":4},    {"id":1,"name":"上海","description":"上海是个好城市","score":3}]

d. NOT 语句查询

GEThttp://localhost:8080/api/city ...on%3D温州

返回 JSON 如下:

[{"id":2,"name":"温岭","description":"温岭是个沿海城市","score":4},    {"id":1,"name":"上海","description":"上海是个好城市","score":3}]

e. LIKE 语句查询

GEThttp://localhost:8080/api/city ...on%3D城市

返回 JSON 如下:

[{"id":2,"name":"温岭","description":"温岭是个沿海城市","score":4},    {"id":1,"name":"上海","description":"上海是个好城市","score":3}]

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

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

1.pom.xml 依赖

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.0http://maven.apache.org/xsd/ma ... gt%3B4.0.0springbootspring-data-elasticsearch-crud0.0.1-SNAPSHOTspring-data-elasticsearch-crud :: spring-data-elasticsearch - 基本案例 org.springframework.bootspring-boot-starter-parent1.5.1.RELEASEorg.springframework.bootspring-boot-starter-data-elasticsearchorg.springframework.bootspring-boot-starter-webjunitjunit4.12

这里依赖的 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 地址

# ESspring.data.elasticsearch.repositories.enabled =truespring.data.elasticsearch.cluster-nodes =127.0.0.1:9300默认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 数据操作层

/*** ES 操作类*

* Created by bysocket on 17/05/2017.*/publicinterfaceCityRepositoryextendsElasticsearchRepository{/*** AND 语句查询**@paramdescription*@paramscore*@return*/List findByDescriptionAndScore(String description, Integer score);/*** OR 语句查询**@paramdescription*@paramscore*@return*/List findByDescriptionOrScore(String description, Integer score);/*** 查询城市描述** 等同于下面代码*@Query("{\"bool\" : {\"must\" : {\"term\" : {\"description\" : \"?0\"}}}}")* Page findByDescription(String description, Pageable pageable);**@paramdescription*@parampage*@return*/Page findByDescription(String description, Pageable page);/*** NOT 语句查询**@paramdescription*@parampage*@return*/Page findByDescriptionNot(String description, Pageable page);/*** LIKE 语句查询**@paramdescription*@parampage*@return*/Page findByDescriptionLike(String description, Pageable page);}

接口只要继承 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. 实体类

/*** 城市实体类*

* Created by bysocket on 03/05/2017.*/@Document(indexName ="province", type ="city")publicclassCityimplementsSerializable{privatestaticfinallongserialVersionUID =-1L;/*** 城市编号*/privateLong id;/*** 城市名称*/privateString name;/*** 描述*/privateString description;/*** 城市评分*/privateInteger score;publicLonggetId(){returnid;    }publicvoidsetId(Long id){this.id = id;    }publicStringgetName(){returnname;    }publicvoidsetName(String name){this.name = name;    }publicStringgetDescription(){returndescription;    }publicvoidsetDescription(String description){this.description = description;    }publicIntegergetScore(){returnscore;    }publicvoidsetScore(Integer score){this.score = score;    }}

注意

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

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

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

四、小结

预告下

下一篇《深入浅出 spring-data-elasticsearch - 实战案例详解》,会带来实战项目中涉及到的权重分 & 短语精准匹配的讲解。

摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 161,513评论 4 369
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,312评论 1 305
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,124评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,529评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,937评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,913评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,084评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,816评论 0 205
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,593评论 1 249
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,788评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,267评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,601评论 3 261
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,265评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,158评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,953评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,066评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,852评论 2 277

推荐阅读更多精彩内容