通过Spring Data Elasticsearch操作ES
Elasticsearch
Elasticsearch (ES)是一个基于Lucene构建的开源、分布式、RESTful 接口全文搜索引擎。Elasticsearch 还是一个分布式文档数据库,其中每个字段均是被索引的数据且可被搜索,它能够扩展至数以百计的服务器存储以及处理PB级的数据。它可以在很短的时间内在存储、搜索和分析大量的数据。它通常作为具有复杂搜索场景情况下的核心发动机。es是由java语言编写的。
Elasticsearch就是为高可用和可扩展而生的。可以通过购置性能更强的服务器来完成。
官网
Elasticsearch:官方分布式搜索和分析引擎 | Elastichttps://www.elastic.co/cn/elasticsearch/
Spring Data
Spring Data是Spring 的一个子项目。用于简化数据库访问,支持NoSQL和关系数据库存储。其主要目标是使数据库的访问变得方便快捷。
官网
Spring DataLevel up your Java code and explore what Spring can do for you.https://spring.io/projects/spring-data
Spring Data ElasticSearch
Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API进行封装。Spring Data为Elasticsearch项目提供集成搜索引擎。Spring Data Elasticsearch POJO的关键功能区域为中心的模型与Elastichsearch交互文档和轻松地编写一个存储库数据访问层。
官网
Spring Data Elasticsearchhttps://spring.io/projects/spring-data-elasticsearch
代码
创建maven项目,并引入依赖
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.6.RELEASE</version><relativePath/></parent><dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-test</artifactId></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId></dependency></dependencies>
在resources文件夹下创建application.properties文件
application.properties内容如下
# es 服务地址
elasticsearch.host=部署es服务器的ip
# es 服务端口
elasticsearch.port=9200
# 配置日志级别,开启 debug 日志
logging.level.com.es=debug
创建MainApplication
package com.es;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class MainApplication {public static void main(String[] args) {SpringApplication.run(MainApplication.class, args);}
}
创建ElasticSearch配置文件ElasticsearchConfig
package com.es.config;import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;@ConfigurationProperties(prefix = "elasticsearch")
@Configuration
@Data
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {private String host ;private Integer port ;@Overridepublic RestHighLevelClient elasticsearchClient() {RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));RestHighLevelClient restHighLevelClient = newRestHighLevelClient(builder);return restHighLevelClient;}
}
创建实体类Person
package com.es.DO;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;@Data
@Document(indexName = "contact", shards = 3, replicas = 1)
public class Person {/*** 主键 id*/@Idpublic Long id;/*** 姓名 name*/@Field(type = FieldType.Text, analyzer = "ik_max_word")public String name;/*** 年龄 age*/@Field(type = FieldType.Integer)public int age;/*** 地址 address*/@Field(type = FieldType.Keyword, index = false)public String address;
}
配置Person的Dao类,PersonDao
package com.es.dao;import com.es.DO.Person;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;@Repository
public interface PersonDao extends ElasticsearchRepository<Person, Long>{}
创建测试类SpringDataESIndexTest,测试类跟启动类在同一个包下,不然启动会报错。
package com.es.test;import com.es.DO.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataESIndexTest {//注入 ElasticsearchRestTemplate@Autowiredprivate ElasticsearchRestTemplate elasticsearchRestTemplate;//创建索引并增加映射配置@Testpublic void createIndex(){//创建索引,系统初始化会自动创建索引System.out.println("创建索引");}@Testpublic void deleteIndex(){//创建索引,系统初始化会自动创建索引boolean flg = elasticsearchRestTemplate.deleteIndex(Person.class);System.out.println("删除索引 = " + flg);}
}
测试
对索引创建及删除进行测试
http://IP地址:9200/_cat/indices?v,用浏览器或Postman等工具访问该地址来看结果
运行createIndex测试方法
运行deleteIndex测试方法
文档操作
新加SpringDataESPersonDaoTest测试类
新增
@Autowiredprivate PersonDao personDao;/*** 新增*/@Testpublic void save(){Person person = new Person();person.setId(1L);person.setName("张三");person.setAge(21);person.setAddress("北京市海淀区");personDao.save(person);}
测试地址:http://IP地址:9200/contact/_doc/1
修改
@Autowiredprivate PersonDao personDao;//修改@Testpublic void update(){Person person = new Person();person.setId(1L);person.setName("张三");person.setAge(21);person.setAddress("北京市朝阳区");personDao.save(person);}
测试地址:http://IP地址:9200/contact/_doc/1
根据 id 查询
@Autowiredprivate PersonDao personDao; //根据 id 查询@Testpublic void findById(){Person person = personDao.findById(1L).get();System.out.println(person);}
打印成功
打印所有
@Autowiredprivate PersonDao personDao;@Testpublic void findAll(){Iterable<Person> persons = personDao.findAll();for (Person person : persons) {System.out.println(person);}}
删除
@Autowiredprivate PersonDao personDao;@Testpublic void delete(){Person person = new Person();person.setId(1L);personDao.delete(person);}
测试地址:http://IP地址:9200/contact/_doc/1
已删除
批量新增
@Autowiredprivate PersonDao personDao;//批量新增@Testpublic void saveAll(){List<Person> personList = new ArrayList<>();for (int i = 0; i < 10; i++) {Person person = new Person();person.setId(Long.valueOf(i));person.setName("["+i+"]张三");person.setAge(21+i);person.setAddress("北京市海淀区");personList.add(person);}personDao.saveAll(personList);}
测试地址:http://ip地址:9200/contact/_search
分页查询
@Autowiredprivate PersonDao personDao;@Testpublic void findByPageable(){//设置排序(排序方式,正序还是倒序,排序的 id)Sort sort = Sort.by(Sort.Direction.DESC,"id");int currentPage=0;//当前页,第一页从 0 开始, 1 表示第二页int pageSize = 5;//每页显示多少条//设置查询分页PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);//分页查询Page<Person> personPage = personDao.findAll(pageRequest);for (Person person : personPage.getContent()) {System.out.println(person);}}
查询成功,查出第一页
完整代码如下
package com.es.test;import com.es.DO.Person;
import com.es.dao.PersonDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataESPersonDaoTest {@Autowiredprivate PersonDao personDao;/*** 新增*/@Testpublic void save(){Person person = new Person();person.setId(1L);person.setName("张三");person.setAge(21);person.setAddress("北京市海淀区");personDao.save(person);}//POSTMAN, GET http://IP地址:9200/contact/_doc/1//修改@Testpublic void update(){Person person = new Person();person.setId(1L);person.setName("张三");person.setAge(21);person.setAddress("北京市朝阳区");personDao.save(person);}//POSTMAN, GET http://IP地址:9200/contact/_doc/1//根据 id 查询@Testpublic void findById(){Person person = personDao.findById(1L).get();System.out.println(person);}@Testpublic void findAll(){Iterable<Person> persons = personDao.findAll();for (Person person : persons) {System.out.println(person);}}//删除@Testpublic void delete(){Person person = new Person();person.setId(1L);personDao.delete(person);}//POSTMAN, GET http://IP地址:9200/contact/_doc/1//批量新增@Testpublic void saveAll(){List<Person> personList = new ArrayList<>();for (int i = 0; i < 10; i++) {Person person = new Person();person.setId(Long.valueOf(i));person.setName("["+i+"]张三");person.setAge(21+i);person.setAddress("北京市海淀区");personList.add(person);}personDao.saveAll(personList);}//分页查询@Testpublic void findByPageable(){//设置排序(排序方式,正序还是倒序,排序的 id)Sort sort = Sort.by(Sort.Direction.DESC,"id");int currentPage=0;//当前页,第一页从 0 开始, 1 表示第二页int pageSize = 5;//每页显示多少条//设置查询分页PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);//分页查询Page<Person> personPage = personDao.findAll(pageRequest);for (Person person : personPage.getContent()) {System.out.println(person);}}
}
文档搜索
新建测试类SpringDataESSearchTest
termQuery
@Autowiredprivate PersonDao personDao;/*** term 查询* search(termQueryBuilder) 调用搜索方法,参数查询构建器对象*/@Testpublic void termQuery(){TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]张三");Iterable<Person> persons = personDao.search(termQueryBuilder);for (Person person : persons) {System.out.println(person);}}
termQuery加分页
@Autowiredprivate PersonDao personDao; /*** term 查询加分页*/@Testpublic void termQueryByPage(){int currentPage= 0 ;int pageSize = 5;//设置查询分页PageRequest pageRequest = PageRequest.of(currentPage, pageSize);TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]张三");Iterable<Person> persons =personDao.search(termQueryBuilder,pageRequest);for (Person person : persons) {System.out.println(person);}}
只有一条name为[8]张三的记录
完整代码如下
package com.es.test;import com.es.DO.Person;
import com.es.dao.PersonDao;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataESSearchTest {@Autowiredprivate PersonDao personDao;/*** term 查询* search(termQueryBuilder) 调用搜索方法,参数查询构建器对象*/@Testpublic void termQuery(){TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]张三");Iterable<Person> persons = personDao.search(termQueryBuilder);for (Person person : persons) {System.out.println(person);}}/*** term 查询加分页*/@Testpublic void termQueryByPage(){int currentPage= 0 ;int pageSize = 5;//设置查询分页PageRequest pageRequest = PageRequest.of(currentPage, pageSize);TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]张三");Iterable<Person> persons =personDao.search(termQueryBuilder,pageRequest);for (Person person : persons) {System.out.println(person);}}}
通过Spring Data Elasticsearch操作ES相关推荐
- Spring Boot + Spring Data + Elasticsearch实例
在本文中,我们将讨论"如何创建Spring Boot + Spring Data + Elasticsearch范例". 本文中使用的工具: Spring Boot 1.5.1.R ...
- SpringBoot207 - 集成 spring data elasticsearch
扯淡: Spring Data Elasticsearch 是spring data对elasticsearch进行的封装.所以在springboot项目中使用es非常方便,直接在 dao 接口继承 ...
- Elasticsearch 实战1:ES 项目实战(一)Java 集成 Spring Data Elasticsearch(一):简介及环境搭建
一:前语 1.项目文档 CSDN 专栏:<Elasticsearch 入门和项目实战> 博客路径: https://blog.csdn.net/a767815662/category_91 ...
- es拼音分词 大帅哥_elasticsearch 拼音+ik分词,spring data elasticsearch 拼音分词
elasticsearch 自定义分词器 安装拼音分词器.ik分词器 下载源码需要使用maven打包 下载构建好的压缩包解压后放直接在elasticsearch安装目录下 plugins文件夹下,可以 ...
- Spring Data Elasticsearch案例详解
一.Elasticsearch 工作原理 1.1 文档存储的路由 当索引到一个文档(如:报价系统),具体的文档数据(如:报价数据)会存储到一个分片.具体文档数据会被切分,并分别存储在分片 1 或者 分 ...
- Spring系列学习之Spring Data Elasticsearch数据访问
英文原文:https://spring.io/projects/spring-data-elasticsearch 目录 概述 特性 快速开始 学习 文档 概述 Elasticsearch的Sprin ...
- Lucene 和 Kibana、ElasticSeach、Spring Data ElasticSearch
什么是全文检索 数据分类 生活中的数据总体分为两种:结构化数据和非结构化数据. 结构化数据 - 行数据,可以用二维表结构来逻辑表达实现的数据:指具有固定格式或有限长度的数据,如数据库,元数据等. 非结 ...
- Spring Data ElasticSearch 3.2版本发布,相关新特性说明
由于ElasticSearch更新的速度非常的快,那么就造成了一些常见的Java交互API更新速度无法匹配最新的版本等情况,比如Spring Data ElasticSearch.对于习惯了使用其他类 ...
- Spring Data ElasticSearch增删改查
Spring Data ElasticSearch 一.介绍 ElasticSearch 学习路线图 1.学习ElasticSearch安装及其API操作 2. 学习原生ElastricSearch ...
最新文章
- 张量功率谱CAMB参数调试
- jeecms v9 vue环境搭建
- o.s.b.d.LoggingFailureAnalysisReporter
- centos6.5 bash基础命令2
- jquery 停止事件冒泡方法
- HEVC---xCompressCU()函数作用及位置
- Chrome 45 减少了内存占用
- 快捷键调出计算机桌面小工具,win7桌面怎么快速创建便签小工具
- excel查标准正态分布_Excel有关正态分布函数NORMSDIST做正态分布图
- android点赞功能源码,Android实现朋友圈点赞列表
- voipdiscount免费拨打全球电话(无需手机注册)
- PCB多种特殊走线画法与技巧
- 西邮校园网路由器教程
- Linux系统时区时间修改
- 〖产品思维训练白宝书 - 核心竞争力篇①〗- 产品经理 的核心竞争力解读
- python 遗传算法 排课_遗传算法实现自动排课
- 香蕉好处多 但吃香蕉要注意这些禁忌!
- 在AHK窗体上使用 Windows Aero 效果
- 使用风格迁移模仿创作艺术风格图画
- ZYNQ 裸机和petalinux扩展CAN接口
热门文章
- [华为动态路由-RIP协议] RIP协议的介绍和配置
- html用表格做个人主页页面,利用HTML的表格进行页面布局
- IDEA classpath jar包不存在 问题求助
- 2011 DB2著作---舞动DB2系列之设计优化篇隆重问世!
- java.net.NoRouteToHostException: No route to host(Host unreachable)
- mysql的TIMESTAMPDIFF的简单使用
- Newbee商城项目-阿里云部署
- 笔记本安装固态硬盘及系统迁移
- 【Py】下划线命名与驼峰命名转换方式汇总
- 赛码网——约德尔测试