Springboot整合Elasticsearch(High-level-Client)
前言
通过学习Elasticsearch一小段时间来稍微认识了一点ES的体系架构。发现ES最大的坑就是版本兼容性问题了—在整合Springboot也不例外,但是,有一种方式能较好的解决—通过restclient
。
项目github地址springboot_elasticsearch求star
内容
当前springboot整合ElasticSearch的方法主体分为2大种——restclient
和transportclient
。其中transportclient将逐渐被遗弃
。而restclient会变得更加流行。
其中
transportclient:
通过监听9300端口tcp链接进行数据传输,他可以触摸到es的API和结构。在Springboot集成ES的两种方式种,一般有spring-boot-starter-data-elasticsearch和Spring-data-elasticsearch。其中spring-boot-starter-data-elasticsearch。第一个是Springboot官方的整合包,使用更方便。但是更新缓慢,支持版本较低。而ES版本更新较快。版本不一致直接整合不上。而Spring-data-elasticsearch对版本支持稍微好一点。版本对应关系。你会发现对新版本支持还是比较差的。restclient:
rest,不难想到http,restclient就是采用http进行交互。restclient相比transport最大的好处就是—对于版本兼容性较好。然而,restclient也分为两种——high—level和low—level两种,两者原理基本一致,区别最大的就是封装性。low—level各种操作都要你自己封装,并且java本身不支持json还需要引用第三方包。而high—level是针对elasticsearch的api进行高级封装,和elasticsearch的版本关联大一些。因为以前学过爬虫,所以对这方面的理解还好一点,两个可以这么类比一下:low—level就行原生爬虫,啥东西都要你自己写,而high—level就像是框架一般,各种方法帮你稍微封装好。使用起来较为方便。用哪一个?
官方明确说明transportclient在elasticsearch高版本会直接遗弃。只支持restclient。为了顺应ES的潮流,还是要用restclient。并且transportclient在高并发会有性能问题。
Springboot简单整合elasticsearch-rest-high-level-client
- maven依赖
org.elasticsearch</groupId>elasticsearch</artifactId></dependency>org.elasticsearch.client</groupId>elasticsearch-rest-high-level-client</artifactId>6.6.1</version></dependency>
- esConfig.java文件
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestClientBuilder.HttpClientConfigCallback;
import org.elasticsearch.client.RestClientBuilder.RequestConfigCallback;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.ArrayList;@Configuration
public class esConfig {private static String hosts = "127.0.0.1"; // 集群地址,多个用,隔开private static int port = 9200; // 使用的端口号private static String schema = "http"; // 使用的协议private static ArrayList hostList = null;private static int connectTimeOut = 1000; // 连接超时时间private static int socketTimeOut = 30000; // 连接超时时间private static int connectionRequestTimeOut = 500; // 获取连接的超时时间private static int maxConnectNum = 100; // 最大连接数private static int maxConnectPerRoute = 100; // 最大路由连接数static {hostList = new ArrayList<>();String[] hostStrs = hosts.split(",");for (String host : hostStrs) {hostList.add(new HttpHost(host, port, schema));}}@Beanpublic RestHighLevelClient client() {RestClientBuilder builder = RestClient.builder(hostList.toArray(new HttpHost[0]));// 异步httpclient连接延时配置builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {@Overridepublic Builder customizeRequestConfig(Builder requestConfigBuilder) {requestConfigBuilder.setConnectTimeout(connectTimeOut);requestConfigBuilder.setSocketTimeout(socketTimeOut);requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);return requestConfigBuilder;}});// 异步httpclient连接数配置builder.setHttpClientConfigCallback(new HttpClientConfigCallback() {@Overridepublic HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {httpClientBuilder.setMaxConnTotal(maxConnectNum);httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);return httpClientBuilder;}});RestHighLevelClient client = new RestHighLevelClient(builder);return client;}}
- pojo类
package com.elasticsearch.pojo;public class dog {private String name;private String type;private int age;private String details;//介绍public dog(String name, String type, int age,String details) {this.name = name;this.type = type;this.age = age;this.details=details;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getType() {return type;}public void setType(String type) {this.type = type;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getDetails() {return details;}public void setDetails(String details) {this.details = details;}
}
- Esteamplate封装你想要的操作,比如你想创建索引,删除索引,查找,插入等等操作,你可以将方法封装起来供使用。我将Esteamplate封装成一个bean对象用于注入。这里我用了一个自增id作为每个插入的索引id(可配合redis),实际可以根据场景进行自由封装,对于
ES
的更新操作
。你只需要将根据index,type和id等信息进行插入就会覆盖。
package com.elasticsearch.service;import com.elasticsearch.pojo.dog;import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;import java.io.IOException;
@Component
public class Esteamplate {@Autowiredprivate RestHighLevelClient client;private int indexid=0;private static final Logger log= LoggerFactory.getLogger(Esteamplate.class);private boolean addindex(String index) throws IOException {//CreateIndexRequest request = new CreateIndexRequest(index);CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);JSONObject jsonObject=new JSONObject(createIndexResponse);log.info("createIndex: " jsonObject.toString());return true;}public boolean deleteIndex(String indexName) {DeleteIndexRequest index = new DeleteIndexRequest(indexName);try {client.indices().delete(index);return true;} catch (IOException e) {e.printStackTrace();return false;}}public JSONObject addDogs(String index, String type, dog dog) throws IOException {GetIndexRequest request = new GetIndexRequest();request.indices(index);if(!client.indices().exists(request,RequestOptions.DEFAULT))//添加之前判断是否存在index{addindex(index);}IndexRequest indexRequest=new IndexRequest(index,type,String.valueOf(indexid ));//用自增id作为唯一indexindexRequest.source((new JSONObject(dog)).toString(), XContentType.JSON);IndexResponse indexResponse=client.index(indexRequest,RequestOptions.DEFAULT);JSONObject jsonObject=new JSONObject(indexResponse);log.info("addDog: " jsonObject.toString());return jsonObject;}public JSONObject searchdog(String index, String type, String detail) throws IOException {BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();boolBuilder.must(QueryBuilders.matchQuery("detail", detail)); // 这里可以根据字段进行搜索,must表示符合条件的,相反的mustnot表示不符合条件的// boolBuilder.must(QueryBuilders.matchQuery("id", tests.getId().toString()));SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(boolBuilder);sourceBuilder.from(0);sourceBuilder.size(10); // 获取记录数,默认10//sourceBuilder.fetchSource(new String[] { "user", "title","desc" }, new String[] {}); // 第一个是获取字段,第二个是过滤的字段,默认获取全部SearchRequest searchRequest = new SearchRequest(index);searchRequest.types(type);searchRequest.source(sourceBuilder);SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);System.out.println(new JSONObject(response).toString());return new JSONObject(response);}
}
- controller:
package com.elasticsearch.controller;import com.elasticsearch.pojo.dog;
import com.elasticsearch.service.Esteamplate;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;import java.io.IOException;@Controller
public class esController {@Autowiredprivate Esteamplate esteamplate;@ResponseBody@GetMapping("adddog")public String adddog(String name, String dogtype, String detail) throws IOException {dog dog=new dog(name, dogtype,2, detail);JSONObject jsonObject=esteamplate.addDogs("esindex","dog",dog);return jsonObject.toString();}@ResponseBody@GetMapping("searchdog")public String serchdog(String detail) throws IOException {return esteamplate.searchdog("esindex","dog",detail).toString();}
}
这样你就可以在controller调用。但是如果你是返回给前端调用的话。要注意返回格式。如果你返回json格式给前端,返回类型不要public JSONobject xx(),因为你如果查看JSONarray或者JSONobject源码会发现他只是将list,map等封装到内部,而无法被序列化返回,所以一般有两个解决思路
转成map返回
转成String返回
这样前端就能正常接受不报错了进行测试
在浏览器输入http://localhost:8080/adddog?name=公众号&dogtype=bigsai&detail=bigsai
等类似进行插入
打开kiniba查询,可以发现查询成功:
然后进入查询:http://localhost:8080/searchdog?detail=舔狗
查询结果会根据相关性进行排序。其中score
就是相关度的分数。
ok,get简单的整合算是完成,但是es的安装,还有kibana安装需要自行百度。windows比较简单,linux也不难。
8.写在后面的话
es的水依然很深。这只是最简单的整合和入门。
es常用的场景有搜索、elk日志处理、集群检测等等。
es必备的一些组合有kibana、head插件、ik分词插件
es很吃内存,如果服务器安装es要找个教程好好看看。
es的各种查询方法可在kibana执行,也可在head中执行,也可直接发送http请求给es执行。现在还有开源的es查询转sql语句很火。
如果对
后端、爬虫、数据结构算法
等感性趣欢迎关注我的个人公众号交流:bigsai
Springboot整合Elasticsearch(High-level-Client)相关推荐
- 七、SpringBoot整合elasticsearch集群
@Author : By Runsen @Date : 2020/6/12 作者介绍:Runsen目前大三下学期,专业化学工程与工艺,大学沉迷日语,Python, Java和一系列数据分析软件.导致翘 ...
- SpringBoot整合Elasticsearch详细步骤以及代码示例(附源码)
准备工作# 环境准备# JAVA版本 Copy java version "1.8.0_121" Java(TM) SE Runtime Environment (build 1. ...
- es springboot 不设置id_原创 | 一篇解决Springboot 整合 Elasticsearch
ElasticSearch 结合业务的场景,在目前的商品体系需要构建搜索服务,主要是为了提供用户更丰富的检索场景以及高速,实时及性能稳定的搜索服务. ElasticSearch是一个基于Lucene的 ...
- SpringBoot整合ElasticSearch实现多版本的兼容
前言 在上一篇学习SpringBoot中,整合了Mybatis.Druid和PageHelper并实现了多数据源的操作.本篇主要是介绍和使用目前最火的搜索引擎ElastiSearch,并和Spring ...
- SpringBoot整合elasticsearch (java整合es)
欢迎大家进群,一起探讨学习 微信公众号,每天给大家提供技术干货 博主技术笔记 博主网站地址1 博主网站地址2 博主开源微服架构前后端分离技术博客项目源码地址,欢迎各位star SpringBoot整合 ...
- 【数据篇】SpringBoot 整合 Elasticsearch 实践数据搜索引擎
写在最前 Elasticsearch 入门必读 Docker安装ELK Spring Data Elasticsearch 参考文档 版本选择 Spring Data Release Train Sp ...
- 微服务商城系统(六)商品搜索 SpringBoot 整合 Elasticsearch
文章目录 一.Elasticsearch 和 IK 分词器的安装 二.Kibana 使用 三.数据导入 Elasticsearch 1.SpringData Elasticsearch 介绍 2.搜索 ...
- SpringBoot 整合ElasticSearch全文检索
ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口.Elasticsearch是用Java语言开发的,并作为Apa ...
- Elasticsearch的安装,以及Springboot整合Elasticsearch
*一.下载好elasticsearch并解压 我这里用的是elasticsearch-5.6.8,下面是下载地址 https://artifacts.elastic.co/downloads/elas ...
最新文章
- super返回不过来
- intellij IDEA debug android app之前执行adb命令
- python详细安装教程3.8-python3.8下载及安装步骤详解
- jap页面使用ajax动态加载列表数据,JSF - 使用AJAX调用基于DataTable中的mimetype值加载不同形式...
- tomcat端口被占用-----windows下如何查询某个端口被哪个进程占用以及如何杀死进程
- LeetCode 1952. 三除数
- Action 跳转的方法和详解
- 微信支付官方SDK V3 .NET版的坑
- Exchange 2013SP1和O365混合部署系列二
- mysql for oracle_模块与包 Mysql与Oracle区别
- Oracle体系结构一
- 使用RemotePotato0从普通用户提升至域管理员
- Excel中关于数组函数的研究
- 香港科大【526清水湾思享会@杭州】暨香港科大EMBA第四届校友会【浙江分会】启动仪式成功举行...
- Java+Servlet+Jsp(el, jstl)+MyBatis的CRUD练习小项目
- cdr怎么把矩形去掉一个边_cdr怎么消除图形的边框?
- 基于涂鸦智能开发的墨水屏座位管理器——2.嵌入式功能实现篇
- sRGB HDR概念性学习
- zip直链生成网站_防止赖床的闹钟软件、免费好用的看图软件、色卡生成器 今天有什么?...
- 使用sql server+jmail组件发送邮件
热门文章
- [原创]桓泽学音频编解码(7):MP3 和 AAC 中huffman解码原理,优化设计与参考代码中实现...
- python生成单位矩阵_python 实现一个反向单位矩阵示例
- 关于大屏展示自适应的处理
- ECC(Elliptic Curve Cryptography)椭圆曲线密码详解
- 通过ffmpeg实时读取宇视摄像头的高清帧流数据,并保存4张图片进行4合一照片的生成。
- c语言函数大全 pdf,C语言标准库函数大全.pdf
- 2021年东莞高新企业补贴政策
- 你最期待的热门思维导图测评在这里!
- 中南大学材料院matlab考试题,中南大学材料院matlab操作题集答案
- Ra-08系列开发板入门教程,标准LoRaWAN协议对接国外 TTN LoRaWAN 开源服务器。