通过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 ...
最新文章
- 干货!如何设计实现一个通用的分布式事务框架?
- R语言distVincentySphere函数计算大圆距离实战(Great Circle Distance)
- 微信小程序 遇到问题1
- Ubuntu首次开启root用户
- arduino代码_纯纯小白开发arduino--我的调试经验
- 了解Spring Web应用程序体系结构:经典方法
- 【小技巧】字符char与整型int的相互转换
- 小白视角来看传说中的卷积神经网络
- 第二阶段冲刺-个人总结04
- 交互式多模型_论文深度提升的万金油方法——多属性决策 Ⅱ
- 未来教育计算机三级课后题答案,全国计算机三级网络技术课后题答案(2016.3 未来教育).docx...
- 为什么交叉熵损失函数可以用作逻辑回归的损失函数?
- 储存管理系统c语言,《C语言,图书管理系统,未做文件储存系统.docx
- 计算机可以怎样做游戏,如何制做游戏 怎么制做游戏
- 使用hydra破解密码
- 制造业数字化转型的意义是什么?
- QGroundControl连接数传(3DR)失败
- source insight 设置窗口滑动条
- Mixly第26课~第28课,内容抢先看 | Mixly米思齐纯干货系列
- Three.js指定路径漫游(站走切换、路径动画、展示路线、开始、暂停、继续、退出、镜头跟随)
热门文章
- Sql(presto语法) 实现行转列和列转行
- 奇虎360软件阻止腾讯电脑管家启动,3Q大战将再度上演?
- waitpid最后以一个参数设为0_wait()和waitpid()解析
- 服务器显示ip访问权限,告诉你有限的访问权限如何解决
- 智源AI日报(2022-08-26):当下最强的 AI art 生成模型 Stable Diffusion 最全面介绍
- netlink实现与使用方法详解(用户态/内核态)
- 记录服务器被入侵病毒:ssh密码被更改登录失败、恶意程序跑满了cpu、jar包启动失败自动kill、一直弹出You have new mail in /var/spool/mail/root
- ftp服务器架设与维护,FTP服务器架设至安全维护大全.doc
- 未来十年,物联网最赚钱的是平台型企业?!!
- 《AI极简经济学》书中的精髓:人工智能的发展会给社会带来什么样的影响?人工智能会取代人们的工作吗?