ElasticSearch CRUD

1.springboot springData es

spring data

是spring对数据访问抽象.这些数据可以放入db,index,nosql等包含以下:

spring data jpa spring对关系型数据库访问支持

spring data ES  spring对es数据访问支持

spring data redis等 spring对redis数据访问支持

spring data .....

springboot springdata xxxx

spring data es

是spring对Es数据访问.和原来spring data jpa对db访问.

springboot spring data es

对 spring data es简化了配置.

2.入门

启动你的elasticsearch

2.1 依赖

注意:我这里使用了lombok

<!--springboot版本仲裁中心-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <!--springboot 对spring data es支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency> </dependencies>

1.1 配置application.yml

spring:
  data:
    elasticsearch:
      cluster-name: elasticsearch #指定elasticsearch集群名称
      cluster-nodes: localhost:9300 #9200是图形化界面端 9300是代码端

2.3 入口

@SpringBootApplication
public class EsApplication {
public static void main(String[] args) {
SpringApplication.run(EsApplication.class, args);
}
}

2.4 创建索引文件

注意:索引库名字只能全部是小写

package cn.dyier.doc;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
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; /**
* person索引库
* 现在ES Doc @Document(index,type) @Id @Feild 建立的是对象与文档直接映射
* 操作的时wwjEsTest索引库下的person文档
* @author Lenovo
*/
@Document(indexName = "wwjestest", type="person")
@NoArgsConstructor
@Getter
@Setter
@ToString(exclude = {"all"})
public class PersonDoc {
/**
* 文档的id就是对象的id
*/
@Id
private Long id; /**
* 没有特殊要求不用@Field
*/
private Integer age; /**
* keyword不分词
*/
@Field(type = FieldType.Keyword)
private String name; /**
* 指定分词类型,分词器,搜索器
*/
@Field(type = FieldType.Text,
analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
private String intro; /**
* 关键字搜索,指定作用于intro 和 name字段
* 虚拟字段all(所有需要做关键字搜索的值,中间通过空格分隔) zs +" "+ zs is .相当于一个字段代替了很多字段
*/
@Field(type = FieldType.Text,
analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
private String all; /**
* 进行拼接
* @return 返回拼接后的结果
*/
public String getAll() {
return this.name + " " + this.intro;
} public PersonDoc(Long id, Integer age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
}

PersonDoc

2.5 repository配置

public interface PersonDocRepository extends
ElasticsearchRepository<PersonDoc, Long> {
}

PersonDocRepository

2.6 创建索引库,添加类型映射,crud,高级查询,排序,分页

package cn.dyier;

import cn.dyier.doc.PersonDoc;
import cn.dyier.repository.PersonDocRepository;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
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.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; @RunWith(SpringRunner.class)
@SpringBootTest(classes = EsApplication.class)
public class EsTest {
//所有的操作都是通过ElasticsearchTemplate
@Autowired
private ElasticsearchTemplate elasticsearchTemplate; @Autowired
private PersonDocRepository personDocRepository; /**
* 创建索引库,类型映射 curd(Repository)
* @throws Exception
*/
@Test
public void init() throws Exception {
System.out.println(elasticsearchTemplate);
//创建索引库
elasticsearchTemplate.createIndex(PersonDoc.class);
//类型映射
elasticsearchTemplate.putMapping(PersonDoc.class);
} /**
* 添加或者修改 save
* id在索引库中存在就是修改
* @throws Exception
*/
@Test
public void testAddOrUpdate() throws Exception {
PersonDoc personDoc = new PersonDoc(1L, 17, "wwj_test01");
personDoc.setIntro("这是测试的第一个");
personDocRepository.save(personDoc);
} /**
* 批量添加 saveAll
* @throws Exception
*/
@Test
public void testAddAll() throws Exception {
ArrayList<PersonDoc> personDocs = new ArrayList<>();
for (int i = 0; i < 50; i++) {
PersonDoc personDoc = new PersonDoc(2L + i, 19 + i, "wwj_" + i);
personDoc.setIntro("wwj_intro_" + i);
personDocs.add(personDoc);
}
personDocRepository.saveAll(personDocs);
} /**
* 根据id删除一个 deleteById()
* @throws Exception
*/
@Test
public void testDeleteById() throws Exception {
personDocRepository.deleteById(14L);
} /**
* 根据id获取 一个
* @throws Exception
*/
@Test
public void testFindOne() throws Exception {
System.out.println(personDocRepository.findById(1L));
} /**
* 查询所有
* @throws Exception
*/
@Test
public void testFindAll() throws Exception {
personDocRepository.findAll().forEach(System.out::println);
} /**
* dsl分页+高级查询+排序
* @throws Exception
*/
@Test
public void testDsl() throws Exception {
//1.创建一个构造器 NativeSearchQueryBuilder
NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
//2.设置条件 QueryBuilders.boolQuery()
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//2.1 must 必须 all字段包含wwj
boolQueryBuilder.must(QueryBuilders.matchQuery("all", "wwj"));
//2.2 filter 过滤 gte大于等于 lte小于等于
boolQueryBuilder.filter(QueryBuilders.rangeQuery("age").gte(20).lte(50));
builder.withQuery(boolQueryBuilder);
//3.排序 根据id排序
builder.withSort(SortBuilders.fieldSort("id"));
//4.分页 页数从0开始
builder.withPageable(PageRequest.of(0, 10));
//5.截取字段
builder.withSourceFilter(new FetchSourceFilter(
new String[]{"id", "name", "age"}, null));
//6.查询并封装结果
NativeSearchQuery build = builder.build();
//当前页数据
Page<PersonDoc> page = personDocRepository.search(build);
//总数
System.out.println(page.getTotalElements());
//当前页数据
System.out.println(page.getContent());
}
}

精髓..

SpringBoot支持SpringData es的更多相关文章

  1. SpringData ES中一些底层原理的分析

    之前写过一篇SpringData ES 关于字段名和索引中的列名字不一致导致的查询问题,顺便深入学习下Spring Data Elasticsearch. Spring Data Elasticsea ...

  2. docker+es+kibana和springboot中使用es

    本次和大家分享的主要是docker搭建es和springboot操作es的内容,也便于工作中或将来使用方便,因此从搭建es环境开始到代码插入信息到es中:主要节点如下: elasticsearch启动 ...

  3. 「Elasticsearch」SpringBoot快速集成ES

    Elastic Search 的底层是开源库 Lucene.但是Lucene的使用门槛比较高,必须自己写代码去调用它的接口.而Elastic Search的出现正是为了解决了这个问题,它是 Lucen ...

  4. SpringBoot整合SpringData JPA入门到入坟

    首先创建一个SpringBoot项目,目录结构如下: 在pom.xml中添加jpa依赖,其它所需依赖自行添加 <dependency> <groupId>org.springf ...

  5. spring-boot支持websocket

    spring-boot本身对websocket提供了很好的支持,可以直接原生支持sockjs和stomp协议.百度搜了一些中文文档,虽然也能实现websocket,但是并没有直接使用spring-bo ...

  6. SpringBoot整合SpringData和Mysql数据库

    1.新建maven项目(具体的新建过程就不细说了) 2.添加maven依赖,也就是在pom.xml文件添加项目的依赖jar包: <project xmlns="http://maven ...

  7. 天啦!竟然从来没有人讲过 SpringBoot 支持配置如此平滑的迁移

    SpringBoot 是原生支持配置迁移的,但是官方文档没有看到这方面描述,在源码中才看到此模块,spring-boot-properties-migrator,幸亏我没有跳过.看到这篇文章的各位,可 ...

  8. SpringBoot+Security+MyBatis+ES+MQ+Redis+Docker+Vue的电商系统

    今天鹏哥给大家推荐的项目是一套电商系统,包括前台商城系统及后台管理系统,基于SpringBoot+MyBatis实现. 前台商城系统包含首页门户.商品推荐.商品搜索.商品展示.购物车.订单流程.会员中 ...

  9. springboot(二)配置SpringBoot支持自动装载Servlet

    Servlet详解:https://blog.csdn.net/yanmiao0715/article/details/79949911 Web 技术成为当今主流的互联网 Web 应用技术之一,而 S ...

随机推荐

  1. Docker在树莓派的安装与使用(Ubuntu Arm Server v19.10)

    最近由于冠状病毒疫情的原因,只能够和小朋友家里蹲.这几天把尘封已久的那个树莓派拿出来继续捣鼓.希望能够做一个异构的分布式系统框架,于是想把Docker也安装到树莓派上,以便后期做进一步的开发和实验. ...

  2. itext5和itext7操作pdf平铺和图层叠加(tiling, and N-upping)

    区别 itext5 生成pdf版本:1.4(Acrobat5.x) itext7 生成pdf版本:1.7(Acrobat8.x) iText7生成的pdf文件大, itext7 Java库更加系统和完 ...

  3. laravel 队列服务使用总结

    laravel 队列服务使用总结 使用步骤 配置队列驱动 //env文件,有的版本是QUEUE_DRIVER QUEUE_CONNECTION=database 迁移队列需要的数据表,在数据库中生成j ...

  4. artTemplate--使用artTemplate时,由于json对象属性有数字命名格式 导致调用报错 syntax error

    案例 今天在使用artTemplate做开发时,遇到一个比较奇葩的问题,就是使用json对象去获取值得时候,报如下错误: Template Error <temp> function an ...

  5. 娱乐往事,年初捡到1G PAR,平淡的日子泛起波澜

    常听说这样的故事 垃圾佬捡到蓝牙键盘,于是配了一台上万的电脑 垃圾佬捡到机箱,于是配了一台带遥控的HTPC 垃圾佬捡到假NAS,于是组了20+T的RAID 而我,不是垃圾佬,更没有捡到过U盘,对突如其 ...

  6. 看完这篇文章,再次遇到Jedis「Redis客户端」异常相信你不再怕了!

    本文导读: [1] 疫情当前 [2] 应用异常监控 [3] Redis客户端异常分析 [4] Redis客户端问题引导分析 [5] 站在Redis客户端视角分析 [6] 站在Redis服务端视角分析 ...

  7. 初识Redis,看这一篇就够了

    环境的搭建和安装网上有很多教程,在这里就不再重复了. 1. Redis是什么? Redis(全称:Remote Dictionary Server 远程字典服务)是一个开源的使用ANSI C语言编写. ...

  8. 《考研机试》(一)C/C++基础

    1.setfill/setw使用 2.定义结构体 3.关于字符串读取 4.排序问题:复试不要求一般用:冒泡排序 5.数字和字符之间转换 6.进制转化:10进制转8进制 7.质数判断 8.字符串拷贝函数 ...

  9. LUA学习笔记(第5-6章)

    x = a or b 如果a为真则x = a 如果a为假则x = b print(a .. b) 任何非nil类型都会被连接为字符串,输出 多重返回值 local s,e = string.find( ...

  10. CERC2017 H Hidden Hierarchy(树+模拟)

    题意: 在一些给定的目录里按要求展开到制定大小并按字典序输出 思路: 因为有目录这个东西,所以想到模拟一个类似字典树的东西,不过这里每个儿子可能有n个节点,而且不能O(1)查询了 代码超长.. #in ...