学习内容:

  1. 掌握配置文件的编写
  2. 熟练掌握使用es的高级客户端对索引和文档的操作
  3. 使用ElasticsearchRepository对数据库进行交互
  4. 使用接口或者高级客户端完成对数据的精确查询和高亮查询

你要知道:

提示:本人使用的spring boot版本为2.5.3,底层所依赖的es版本为7.12.1


导入依赖

<dependencies><!--web场景启动器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--MySQL驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.16</version></dependency><!--整合mybatis--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.0</version></dependency><!--弹性搜索--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><!--json相关--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version></dependency>
</dependencies>

编写配置文件

public class EsCoonfig{@Beanpublic RestHighLevelClient restHighLevelClient(){RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.31.79", 9200, "http")));return client;}
}

高级客户端对索引以及文档的操作

@Autowired
private RestHighLevelClient client;

创建索引

//创建索引
@Test
public void testCreateIndex(){//创建索引请求CreateIndexRequest request=new CreateIndexRequest("moyi");//客户端执行请求,请求后获得响应CreateIndexResponse response=client.indeices().create(request,RequestOptions.DEFAULT);
}

判断索引是否存在

//获取索引,判断索引是否存在
@Test
public void testGetIndex() throws IOException {//创建获取索引的请求GetIndexRequest request = new GetIndexRequest();request.indices("moyi");boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);System.out.println(exists);
}

删除索引

//删除索引
@Test
public void testDeleteIndex() throws IOException {DeleteIndexRequest request = new DeleteIndexRequest("moyi");AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);System.out.println(response.isAcknowledged());
}

创建文档

public class User{private String name;private int age;
}
@Test
public void testAddDocument() thrwos IOException{//创建对象User user=new User("moyi",20)//创建请求IndexRequest request=new IndexRequest();//添加规则,将user对象添加到moyi索引下,id设置为1,如果不设置id则随机生成uuidrequest.index("moyi").id("1");//将数据放入请求中,使用fastjson将user对象转换为json字符串request.source(JSON.toJSONString(user),XContentType.JSON);//客户端发送请求,获取响应的结果IndexResponse response = client.index(request, RequestOptions.DEFAULT);//获取响应的结果System.out.println(response.getResult());//获取响应的状态System.out.println(response.status());
}

判断文档是否存在

//判断文档是否存在
@Test
public void testIsExists() throws IOException {GetRequest request = new GetRequest("moyi", "1");//不获取返回的_source的上下文request.fetchSourceContext(new FetchSourceContext(false));request.storedFields("_none_");boolean exists = client.exists(request, RequestOptions.DEFAULT);System.out.println(exists);
}

获取文档的信息

//获取文档信息
@Test
public void testGetDocument() throws IOException {GetRequest request = new GetRequest("moyi", "1");GetResponse response = client.get(request, RequestOptions.DEFAULT);System.out.println(response.getSourceAsString());//打印文档内容System.out.println(response);
}

更新文档记录

@Test
public void testUpdateDocument() throws IOException {UpdateRequest request = new UpdateRequest("moyi", "1");//设置超时时间request.timeout(TimeValue.timeValueSeconds(1));User user = new User("时光之境", 24);request.doc(JSON.toJSONString(user), XContentType.JSON);UpdateResponse response = client.update(request, RequestOptions.DEFAULT);System.out.println(response.status());System.out.println(response.getResult());
}

删除文档记录

//删除文档记录
@Test
public void testDeleteDocument() throws IOException {DeleteRequest request = new DeleteRequest("moyi", "1");//设置超时时间request.timeout(TimeValue.timeValueSeconds(1));DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);System.out.println(response.status());
}

批量插入数据

@Test
public void testBulkRequest() throws IOException {BulkRequest request = new BulkRequest();request.timeout(TimeValue.timeValueSeconds(10));List<User> users = new ArrayList<>();users.add(new User("zhangsan", 10));users.add(new User("lisi", 11));users.add(new User("wangwu", 12));users.add(new User("zhaoliu", 13));for (int i = 0; i < users.size(); i++) {request.add(new IndexRequest("moyi").id("" + (i + 1)).source(JSON.toJSONString(users.get(i)), XContentType.JSON));}BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);//判断是否执行失败,false表示成功插入System.out.println(response.hasFailures());
}

查询文档

/*** 查询文档* SearchRequest搜索请求* SearchSourceBuilder条件构造* HighlightBuilder构建高亮* TermQueryBuilder精确查询* matchAllQueryBuilder匹配所有* xxxQueryBuilder* @throws IOException*/
@Test
public void testSearch() throws IOException {SearchRequest searchRequest = new SearchRequest("moyi");//构建搜索条件SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//构建查询条件,通过QueryBuilders工具实现TermQueryBuilder termQuery = QueryBuilders.termQuery("name", "zhangsan");sourceBuilder.query(termQuery);//设置超时时间sourceBuilder.timeout(TimeValue.timeValueSeconds(60));searchRequest.source(sourceBuilder);SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);System.out.println(response.getHits().toString());System.out.println("======================================================");SearchHit[] hits = response.getHits().getHits();for (SearchHit hit : hits) {System.out.println(hit.getSourceAsMap());}
}

使用ElasticsearchRepository将数据库的数据存入到es中

创建一个entity类

package com.moyi.nowcoder.entity;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;
import org.springframework.data.elasticsearch.annotations.Setting;import java.util.Date;
@Document(indexName = "discusspost")//设置索引名称
@Setting(shards = 6, //设置分片replicas = 3 //设置副本
)
public class DiscussPost {@Idprivate Integer id;@Field(type = FieldType.Integer)private Integer userid;@Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_smart_word")private String title;@Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_smart_word")private String content;@Field(type = FieldType.Integer)private Integer type=0;@Field(type = FieldType.Integer)private Integer status=0;@Field(type = FieldType.Date)private Date createTime;@Field(type = FieldType.Integer)private Integer commentCount=0;@Field(type = FieldType.Double)private double score;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public Integer getUserid() {return userid;}public void setUserid(Integer userid) {this.userid = userid;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public Integer getType() {return type;}public void setType(Integer type) {this.type = type;}public Integer getStatus() {return status;}public void setStatus(Integer status) {this.status = status;}public Date getCreateTime() {return createTime;}public void setCreateTime(Date createTime) {this.createTime = createTime;}public Integer getCommentCount() {return commentCount;}public void setCommentCount(Integer commentCount) {this.commentCount = commentCount;}public double getScore() {return score;}public void setScore(Double score) {this.score = score;}public DiscussPost(int id, int userid, String title, String content, int type, int status, Date createTime, int commentCount, double score) {this.id = id;this.userid = userid;this.title = title;this.content = content;this.type = type;this.status = status;this.createTime = createTime;this.commentCount = commentCount;this.score = score;}public DiscussPost() {}@Overridepublic String toString() {return "DiscussPost{" +"id=" + id +", userid=" + userid +", title='" + title + '\'' +", content='" + content + '\'' +", type=" + type +", status=" + status +", createTime=" + createTime +", commentCount=" + commentCount +", score=" + score +'}';}
}

定义DiscussPostRepository接口

package com.moyi.nowcoder.dao.elasticsearch;import com.moyi.nowcoder.entity.DiscussPost;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;@Repository
public interface DiscussPostRepository extends ElasticsearchRepository<DiscussPost,Integer> {}

保存或修改数据

@Autowired
private DiscussPostRepository postRepository;@Autowired
private RestHighLevelClient restHighLevelClient;/*** 保存或修改数据* @param discussPost*/
public void save(DiscussPost discussPost){postRepository.save(discussPost);
}

根据id删除数据

    /*** 根据id删除数据* @param id*/public void delete(Integer id){postRepository.deleteById(id);}

高亮查询

/*** 高亮查询* @param keyword* @param start* @param limit* @return*/
public List<DiscussPost> search(String keyword,int start,int limit) throws IOException {//构建查询SearchRequest request = new SearchRequest("discusspost");//构建查询条件SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(QueryBuilders.multiMatchQuery(keyword,"title","content"))//多字段匹配.sort(SortBuilders.fieldSort("type").order(SortOrder.DESC))//根据类型排序.sort(SortBuilders.fieldSort("score").order(SortOrder.DESC))//根据得分排序.sort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))//根据时间排序.from(start).size(limit).highlighter(new HighlightBuilder().field("title").preTags("<em style='color:red'>").postTags("</em>").requireFieldMatch(false))//高亮字段用em标签包裹,且关闭多个高亮.highlighter(new HighlightBuilder().field("content").preTags("<em style='color:red'>").postTags("</em>").requireFieldMatch(false));request.source(sourceBuilder);SearchResponse searchResponse = restHighLevelClient.search(request, RequestOptions.DEFAULT);SearchHit[] hits = searchResponse.getHits().getHits();List<DiscussPost> list=new ArrayList<>();for (SearchHit hit : hits) {//获取高亮字段Map<String, HighlightField> highlightFields = hit.getHighlightFields();//解析高亮字段Map<String, Object> sourceAsMap = hit.getSourceAsMap();HighlightField title = highlightFields.get("title");if (title != null) {Text[] fragments = title.getFragments();String newTitle="";newTitle+=title;sourceAsMap.put("title",newTitle);}HighlightField content = highlightFields.get("content");if (content != null) {Text[] fragments = content.getFragments();String newContent="";newContent+=content;sourceAsMap.put("content",newContent);}list.add(JSONObject.parseObject(hit.getSourceAsString(),DiscussPost.class));}return list;
}

elasticSearch(二)springboot与es的整合相关推荐

  1. ElasticSearch系列 - SpringBoot整合ES:分析器

    文章目录 01. ElasticSearch 分析器 1. ElasticSearch match 文本搜索的过程? 2. ElasticSearch 分析器是什么? 3. ElasticSearch ...

  2. SpringBoot与ElasticSearch、ActiveMQ、RocketMQ的整合及多环境配置、响应式框架WebFlux、服务器端主动推送SSE技术、生产环境部署、Actuator监控平台

    1.SpringBoot 与 ElasticSearch 框架的整合 (1)主要的搜索框架:MySQL.Solr.ElasticSearch MySQL:使用 like 进行模糊查询,存在性能问题 S ...

  3. 优化大数据量查询方案——SpringBoot(Cloud)整合ES

    一.Elasticsearch简介 实际业务场景中,多端的查询功能都有很大的优化空间.常见的处理方式有:建索引.建物化视图简化查询逻辑.DB层之上建立缓存.分页-然而随着业务数据量的不断增多,总有那么 ...

  4. 从ElasticSearch 认识到实战(SpringBoot集成ES)

    ElasticSearch 认识到实战 目录 搜索引擎介绍 ElasticSearch知识 安装 使用restful风格查询ES SpringBoot配置ES SpringBoot集成使用 一.搜索引 ...

  5. spring-boot 2.3.x 整合elasticsearch

    spring-boot 2.3.x 整合elasticsearch 文章目录 spring-boot 2.3.x 整合elasticsearch 1.elasticsearch的安装(docker形式 ...

  6. 《SpringBoot框架开发技术整合》笔记(二)

    文章目录 前言 第五章 SpringBoot配置全局的异常捕获 一. 页面跳转形式 二. ajax形式 三. 统一返回异常的形式 参考 前言     笔者近期在慕课网上学习了<Springboo ...

  7. ElasticSearch(二):ES集群安装

    安装Elasticsearch 创建普通用户 ES不能使用root用户来启动,必须使用普通用户来安装启动.这里我们创建一个普通用户以及定义一些常规目录用于存放我们的数据文件以及安装包等. 创建一个es ...

  8. ElasticSearch - SpringBoot集成ES

    文章目录 ElasticSearch - SpringBoot集成ES 1.整体设计思路(仿NBA中国官网) 2.项目搭建 3.ES API的基本使用 3.1 新增球员信息 3.2 查看球员信息 3. ...

  9. SpringBoot操作ES进行各种高级查询(值得收藏)

    来源:cnblogs.com/keatsCoder/p/11341835.html SpringBoot整合ES 创建SpringBoot项目,导入 ES 6.2.1 的 RestClient 依赖和 ...

最新文章

  1. vs2010 SQL Server Compact 3.5出错
  2. JS对象和JSON字符串相互转化总结
  3. 云服务器有什么好 能让云大佬们竞争如此激烈
  4. Linux 下 Shell 命令的分类及用法
  5. Linux之ssh无密码登录
  6. Idea 工具在java文件中怎么避免 import .*包
  7. 41个机器学习面试题
  8. option设置selected
  9. 电影记忆之20(恐怖游轮)
  10. BigDecimal的ROUND_DOWN()中的坑
  11. day05【JQuery框架】HTML引入Jquery、jQuery与JS区别、基本选择器、层级关系选择器、属性选择器、过滤选择器、 对象遍历、Jquery的DOM操作【重点】、Jquery事件绑定
  12. 浅谈API开发安全之sign有效时间(三)
  13. Vue自定义组件之时间跨度选择器
  14. Android APP memory用量如何回收
  15. python语言表白超炫图形_经验分享 篇二:三分钟教你用Excel制作各种尺寸、底色的证件照...
  16. 问卷调查有哪些作用?
  17. python 桑基图 地理坐标_利用Python+Excel制作桑基(Sankey)图
  18. Codeforces Round #127 (Div. 1) B. Guess That Car! 扫描线
  19. 电动车充电软件测试,电动车充电用哪个app好?6款充电app评测
  20. 通过PS把荒野草地变成大雪纷飞的雪景

热门文章

  1. SpringBoot的幕后推手是谁?
  2. java使用poi读写word中的图片(二)
  3. 嵌入式开发为啥不适合macOS系统?
  4. python+selenium实战搭建PO模型
  5. 平分肥宅快乐水(C++)
  6. 曾经作为程序员的你为什么不当程序员了?现在在做什么?
  7. 带你认识 M1、UID、CUID、FUID、UFUID
  8. splits——安卓gradle
  9. OPENGL OSG setNearFarRatio可以动态调节远近剪裁面
  10. python多久可以完全学会_python好学吗自学要学多久