1、什么是Spring Data

  Spring Data是一个用于简化数据库访问,并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快捷,并支持map-reduce框架和云计算数据服务。 Spring Data可以极大的简化JPA的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。除了CRUD外,还包括如分页、排序等一些常用的功能。

2、什么是Spring Data ElasticSearch

  Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API进行封装 。Spring Data为Elasticsearch项目提供集成搜索引擎。Spring Data Elasticsearch POJO的关键功能区域为中心的模型与Elastichsearch交互文档和轻松地编写一个存储库数据访问层。

3.Spring Data ElasticSearch环境  

     1.1 环境搭建
            步骤一:Spring-Data-ElasticSearch,Spring-test帮助你加载配置文件并且测试
                ESTemplate模板,模板当中包含了一系列的方法
               导入依赖:

 
          <dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>3.1.9.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport‐netty4‐client</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
<scope>test</scope>
</dependency>
 

步骤二:创建Spring的核心配置文

 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch.xsd">
<!--开启包扫描-->
<context:component-scan base-package="com.wdksoft"/>
<!--配置集群信息-->
<elasticsearch:transport-client id="esClient" cluster-name="my-elasticsearch" cluster-nodes="127.0.0.1:9300,127.0.0.1:9301,127.0.0.1:9302"/>
<!--注入ESTemplate模板-->
<bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="esClient"/>
</bean>
<!--扫描Mapper-->
<elasticsearch:repositories base-package="com.wdksoft.mapper"/>
</beans>

2.SpringDataES案例
        
        2.1 添加索引库

 
       @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpringDataESTest {
//植入模板对象
@Resource
private ElasticsearchTemplate elasticsearchTemplate; @Test
public void createIndex(){
//创建空的索引库
elasticsearchTemplate.createIndex(Hello.class); }
}

2.2 添加索引库并且指定Mapping信息
            利用POJO映射Mapping信

 
         @Document(indexName = "my-index",type = "hello")
public class Hello {
@Id
@Field(type = FieldType.Long,index = false,store = true)
private Long id;
@Field(type = FieldType.Text,index = true,store = true,analyzer = "ik_max_word")
private String title;
@Field(type = FieldType.Text,index = true,store = true,analyzer = "ik_max_word")
private String content;
}
 
          @Test
public void createIndex(){
//创建空的索引库
elasticsearchTemplate.+(Hello.class);
elasticsearchTemplate.putMapping(Hello.class); }

2.3 添加文档数据
            创建Mapper层接口:

 
                /**
* 数据访问层接口
*/
@Repository
public interface HelloMapper extends ElasticsearchRepository<Hello,Long> {
}

创建Service层接口

                public interface HelloService {
public void save(Hello hello);
}

创建Service层接口实现类

 
                @Service("helloService")
public class HelloServiceImpl implements HelloService {
//植入Mapper层对象
@Resource
private HelloMapper helloMapper; @Override
public void save(Hello hello) {
helloMapper.save(hello);
}
}

测试:

 
/**
* 添加文档数据
*/
@Test
public void createDocument(){
for(long i=1l;i<=10l;i++){
Hello hello=new Hello();
hello.setId(i);
hello.setTitle("新增的Title数据"+i);
hello.setContent("新增的Content数据"+i);
helloService.save(hello);
}

2.4 删除文档数据
                Service层接口

                    //根据文档ID删除
public void deleteById(long id);
//删除全部
public void deleteAll();

Service层接口实现类

 
                    @Override
public void deleteById(long id) {
helloMapper.deleteById(id);
} @Override
public void deleteAll() {
helloMapper.deleteAll();
}

测试:

 
            /**
* 删除文档数据
*/
@Test
public void deleteDocument(){
//根据文档ID删除
helloService.deleteById(1l);
//全部删除
helloService.deleteAll();
}

2.5 修改文档数据

  修改也是调用save方法,如果id不存在则添加,id存在则先删除再添加

 
            /**
* 修改文档数据:先删除再添加,调用的还是save方法
*/
@Test
public void updateDocument(){
Hello hello=new Hello();
hello.setId(1l);
hello.setTitle("[修改]新增的Title数据");
hello.setContent("[修改]新增的Content数据");
helloService.save(hello);
}

2.6 根据ID查询
            Service层接口

                    //根据文档ID查询数据
public Optional<Hello> findById(Long id);

Service层接口实现类

                    @Override
public Optional<Hello> findById(Long id) {
return helloMapper.findById(id);
}

测试:

 
                /**
* 根据文档ID查询
*/
@Test
public void getDocumentById(){
Optional<Hello> optional = helloService.findById(2l);
Hello hello = optional.get();
System.out.println(hello);

2.7 查询全部文档数据
            Service层接口

                //查询所有数据
public Iterable<Hello> findAll();
//查询所有数据包含分页
public Page<Hello> findAll(Pageable pageable);

Service层接口实现类

 
                @Override
public Iterable<Hello> findAll() {
return helloMapper.findAll();
} @Override
public Page<Hello> findAll(Pageable pageable) {
return helloMapper.findAll(pageable);
}

测试:

 
                /**
* 查询所有文档数据
*/
@Test
public void getAllDocument(){
Iterable<Hello> iterable = helloService.findAll();
iterable.forEach(item-> System.out.println(item));
}
/**
* 查询所有文档数据加分页
*/
@Test
public void getDocumentPage(){
//指定分页规则
Page<Hello> page = helloService.findAll(PageRequest.of(0, 5));
for (Hello hello:page.getContent()) {
System.out.println(hello);
}
}

2.8 根据查询方法的自定义规则进行数据查询
            根据Title域进行查询,并且加分页
                Mapper层接口:

 
                    /**
* 数据访问层接口
*/
@Repository
public interface HelloMapper extends ElasticsearchRepository<Hello,Long> {
//根据Title域中的关键词查找数据
public List<Hello> findByTitle(String str);
//根据Title域中的关键词查找数据
public List<Hello> findByTitle(String str, Pageable pageable);
}

Service层接口

                        //根据Title域中的关键词查找数据
public List<Hello> findByTitle(String str);
//根据Title域中的关键词查找数据
public List<Hello> findByTitle(String str, Pageable pageable);

Service层接口实现类

 
                    @Override
public List<Hello> findByTitle(String str) {
return helloMapper.findByTitle(str);
} @Override
public List<Hello> findByTitle(String str, Pageable pageable) {
return helloMapper.findByTitle(str,pageable);
}

测试:

 
                    /**
* 根据条件查询文档数据加分页
*/
@Test
public void getDocumentByTitle(){
/*List<Hello> helloLists = helloService.findByTitle("修改");
helloLists.stream().forEach(item-> System.out.println(item));*/ List<Hello> helloLists = helloService.findByTitle("新增", PageRequest.of(0, 5));
helloLists.stream().forEach(item-> System.out.println(item)); }

2.9 NativeSearchQuery

  将输入的查询条件先分词,再进行查询

 
            /**
* 根据一段内容查询数据:NativeSearchQuery
* 先分词再查询
*/
@Test
public void getDocumentQuery(){
//创建NativeSearchQueryBuilder对象
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
//指定查询规则
NativeSearchQuery build = nativeSearchQueryBuilder.withQuery(QueryBuilders.queryStringQuery("搜索新增").defaultField("title"))
.withPageable(PageRequest.of(0,5)).build();
//使用ESTemplates执行查询
List<Hello> hellos = elasticsearchTemplate.queryForList(build, Hello.class);
hellos.stream().forEach(item-> System.out.println(item));
}

Spring Data ElasticSearch的使用的更多相关文章

  1. elasticsearch系列七:ES Java客户端-Elasticsearch Java client(ES Client 简介、Java REST Client、Java Client、Spring Data Elasticsearch)

    一.ES Client 简介 1. ES是一个服务,采用C/S结构 2. 回顾 ES的架构 3. ES支持的客户端连接方式 3.1 REST API ,端口 9200 这种连接方式对应于架构图中的RE ...

  2. Elasticsearch基本用法(2)--Spring Data Elasticsearch

    Spring Data Elasticsearch是Spring Data项目下的一个子模块. 查看 Spring Data的官网:http://projects.spring.io/spring-d ...

  3. Elasticsearch Java client(ES Client 简介、Java REST Client、Java Client、Spring Data Elasticsearch)

    elasticsearch系列七:ES Java客户端-Elasticsearch Java client(ES Client 简介.Java REST Client.Java Client.Spri ...

  4. spring data elasticsearch 使用

    很久之前就安装了elasticsearch,一直没用java用过,最近看了一下spring data系列的elasticsearch,这里写一篇心得. 如果尚未安装elasticsearch,可以 参 ...

  5. Spring Boot + Spring Data + Elasticsearch实例

    Spring Boot + Spring Data + Elasticsearch实例 学习了:https://blog.csdn.net/huangshulang1234/article/detai ...

  6. elasticsearch 拼音+ik分词,spring data elasticsearch 拼音分词

    elasticsearch 自定义分词器 安装拼音分词器.ik分词器 拼音分词器: https://github.com/medcl/elasticsearch-analysis-pinyin/rel ...

  7. How to provide highlighting with Spring data elasticsearch

    How to provide highlighting with Spring data elasticsearch @Test public void shouldReturnHighlighted ...

  8. springboot集成spring data ElasticSearch

    ES支持SpringBoot使用类似于Spring Data Jpa的方式查询,使得查询更加方便. 1.依赖引入 compile “org.springframework.boot:spring-bo ...

  9. 031 Spring Data Elasticsearch学习笔记---重点掌握第5节高级查询和第6节聚合部分

    Elasticsearch提供的Java客户端有一些不太方便的地方: 很多地方需要拼接Json字符串,在java中拼接字符串有多恐怖你应该懂的 需要自己把对象序列化为json存储 查询到结果也需要自己 ...

  10. SpringBoot整合Spring Data Elasticsearch

    Spring Data Elasticsearch提供了ElasticsearchTemplate工具类,实现了POJO与elasticsearch文档之间的映射 elasticsearch本质也是存 ...

随机推荐

  1. pyrealsense2学习

    如何得到realsense设备信息 前提:将D455连接在电脑上,并且已经下载好 Realsense Viewer 打开Realsense Viewer--> Info, 便可得到相机的一些参数 ...

  2. Codeforces Round #756 (Div. 3)

    本场战绩:+451 题目如下: A. Make Even time limit per test 1 second memory limit per test 256 megabytes input ...

  3. HTML笔记整理--上节

    一.认识WEB 「网页」主要是由文字.图像和超链接等元素构成,当然除了这些元素,网页中还可以包括音频.视频以及Flash等. 「浏览器」是网页显示.运行的平台. 「浏览器内核」(排版引擎.解释引擎.渲 ...

  4. 从观察者设计模式的角度理解Zookeeper中的Watcher

    前面关于Zookeeper提供的API中,可以观察到大部分接口参数似乎都是用了Wathcerz这个接口.这个在观察者模式中略有涉及,本文重点分析从观察者模式的角度分析该接口. 首先上该接口的UML图: ...

  5. 本塔科技借力VR Engine,提供更优质的3D VR内容

    本文分享于华为开发者论坛<本塔科技借力HMS Core VR Engine,提供更优质的3D VR视频内容> 本塔科技致力于为影视行业提供优质的3D VR视频内容,追求稳定.观看感舒适.良 ...

  6. oracle-11G转10G

    先查询directory的地址 导出的文件必须放在此目录select * from dba_directories;找到directory_name的值 ,也可以新建一个create director ...

  7. 【转】int和Integer的区别

    int和Integer的区别: 1.Integer是int的包装类,int则是java的一种基本数据类型 2.Integer变量必须实例化后才能使用,而int变量不需要 3.Integer实际是对象的 ...

  8. Excel数据可视化图表设计需要注意的几个问题

    ​大数据发展迅速的时代,数据分析驱动商业决策.对于庞大.无序.复杂的数据要是没经过合适的处理,价值就无法体现. 可以想象一本没有图片的教科书.没有图表.图形或是带有箭头和标签的插图或流程图,那么这门学 ...

  9. 年底获奖人太多?奖状可以用Smartbi电子表格这么做!

    又到一年年终时,你的年终奖到手了吗?奖金没领到,发个奖状压压惊 今天给大家分享年终奖相关的年终奖状的批量套打功能,保证你的奖状及时到手! 示例说明 现有多个人员的奖励需要通知,需要生成可翻页的奖状.并 ...

  10. C#实现接口的两种方式:显示实现和隐式实现接口

    本示例声明一个接口IDimensions 和一个类 Box,显式实现了接口成员 GetLength 和 GetWidth. 通过接口实例 dimensions 访问这些成员. interface ID ...