环境:

  ES:  7.12.0

  

1、springboot工程引入es相关jar

<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.12.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.12.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>reindex-client</artifactId>
<version>7.12.0</version>
</dependency>
<!-- Java High Level REST Client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.12.0</version>
</dependency>

2、增加es自定义配置

elasticsearch:
configs:
sport:        #索引配置
userName: 1
password: 2
host: 127.0.0.1
port: 9200
indexName: sport  #索引名称
timeOut: 1000    #请求超时时间,单位秒
study:
indexName: study
help: sssssssssssssssssssss

3、JAVA代码

package com.example.elasticSearch;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration; import java.util.Map; @Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ESConfig { Map<String, Config> configs; String help; public String getHelp() {
return help;
} public void setHelp(String help) {
this.help = help;
} public Map<String, Config> getConfigs() {
return configs;
} public void setConfigs(Map<String, Config> configs) {
this.configs = configs;
} static class Config {
private String userName;
private String password;
private String host;
private Integer port;
private String indexName;
private long timeout; public long getTimeout() {
return timeout;
} public void setTimeout(long timeout) {
this.timeout = timeout;
} public String getIndexName() {
return indexName;
} public void setIndexName(String indexName) {
this.indexName = indexName;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getHost() {
return host;
} public void setHost(String host) {
this.host = host;
} public Integer getPort() {
return port;
} public void setPort(Integer port) {
this.port = port;
} }
}

配置类


package com.example.elasticSearch;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
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.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.ScoreSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody; import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; public class ESClient { RestHighLevelClient restHighLevelClient; ESConfig.Config config; /**
* 获取连接
* @param config
*/
public ESClient(ESConfig.Config config) {
this.config = config; String[] hosts = config.getHost().split(",");
String[] ports = config.getPort().split(",");
HttpHost[] httpHostList = new HttpHost[hosts.length];
for (int i = 0; i < hosts.length; i++) {
httpHostList[i] = new HttpHost(hosts[i],Integer.parseInt(ports[i]),"http");
}
RestHighLevelClient restHighLevelClient=new RestHighLevelClient(
RestClient.builder(httpHostList));
this.restHighLevelClient = restHighLevelClient;
} /**
* 新建索引
* @param sport
*/
public void saveIndex(Sport sport){
try {
boolean exists = restHighLevelClient.indices().exists(new GetIndexRequest(config.getIndexName()), RequestOptions.DEFAULT);
if (!exists) {
CreateIndexRequest qyf = new CreateIndexRequest(config.getIndexName());
restHighLevelClient.indices().create(qyf, RequestOptions.DEFAULT);
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 保存文档
* @param sport
*/
public void saveDocument(Sport sport) {
IndexRequest request = new IndexRequest(config.getIndexName()); request.source(JSON.toJSONString(sport), XContentType.JSON);
request.id(sport.getTitle());
request.timeout(TimeValue.timeValueSeconds(config.getTimeout()));
try {
IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 根据ID获取文档
* @param sport
* @return
*/
public String getDocument(Sport sport) {
GetRequest getRequest = new GetRequest(config.getIndexName(), sport.getId());
GetResponse getResponse1 = null;
try {
getResponse1 = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
return getResponse1.toString();
} /**
* @param index
* @param from
* @param size
* @param where
* @param sortFieldsToAsc
* @param includeFields
* @param excludeFields
* @param timeOut
* @return
*/
public List<Map<String, Object>> searchIndex(String index, int from, int size, Map<String, Object> where,
Map<String, Boolean> sortFieldsToAsc, String[] includeFields, String[] excludeFields,
int timeOut) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
try {
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//条件
if (where != null && !where.isEmpty()) {
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
where.forEach((k, v) -> {
if (v instanceof Map) {
//范围选择map 暂定时间
Map<String, Date> mapV = (Map<String, Date>) v;
if (mapV != null) {
boolQueryBuilder.must(
QueryBuilders.rangeQuery(k).
gte(format.format(mapV.get("start"))).
lt(format.format(mapV.get("end"))));
}
} else {
//普通模糊匹配
boolQueryBuilder.must(QueryBuilders.wildcardQuery(k, v.toString()));
}
});
sourceBuilder.query(boolQueryBuilder);
} //分页
from = from <= -1 ? 0 : from;
size = size >= 1000 ? 1000 : size;
size = size <= 0 ? 15 : size;
sourceBuilder.from(from);
sourceBuilder.size(size); //超时
sourceBuilder.timeout(new TimeValue(timeOut, TimeUnit.SECONDS)); //排序
if (sortFieldsToAsc != null && !sortFieldsToAsc.isEmpty()) {
sortFieldsToAsc.forEach((k, v) -> {
sourceBuilder.sort(new FieldSortBuilder(k).order(v ? SortOrder.ASC : SortOrder.DESC));
});
} else {
sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));
} //返回和排除列
if ((includeFields != null && includeFields.length != 0) || (excludeFields != null && excludeFields.length != 0)) {
sourceBuilder.fetchSource(includeFields, excludeFields);
} SearchRequest rq = new SearchRequest();
//索引
rq.indices(index);
//各种组合条件
rq.source(sourceBuilder); //请求
System.out.println(rq.source().toString());
SearchResponse rp = restHighLevelClient.search(rq, null); //解析返回
if (rp.status() != RestStatus.OK || rp.getHits().getTotalHits().value <= 0) {
return Collections.emptyList();
} //获取source
return Arrays.stream(rp.getHits().getHits()).map(b -> {
return b.getSourceAsMap();
}).collect(Collectors.toList()); } catch (Exception ex) {
ex.printStackTrace();
}
return Collections.emptyList();
} /**
* 搜索
* @param keyword
* @param pageNo
* @param pageSize
* @return
* @throws IOException
*/
public List<Map<String ,Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException { SearchRequest searchRequest = new SearchRequest(config.getIndexName()); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
pageNo = pageNo * pageSize;
pageSize = pageSize == 0 ? 10 : pageSize;
searchSourceBuilder.from(pageNo);
searchSourceBuilder.size(pageSize); //输入的关键字匹配的字段
QueryBuilder termQueryBuilder = QueryBuilders.matchQuery("content", keyword); searchSourceBuilder.query(termQueryBuilder);
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); //执行
searchRequest.source(searchSourceBuilder);
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); ArrayList<Map<String,Object>> list = new ArrayList<>(); if (search.getHits().getHits().length!=0){
for (SearchHit documentFields : search.getHits().getHits()) {
list.add(documentFields.getSourceAsMap());
}
return list;
}else {
HashMap<String, Object> map = new HashMap<>();
map.put("code",404);
map.put("msg","没有相关数据");
list.add(map);
return list;
}
}
}

工具类-ES客户端


package com.example.elasticSearch;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; @Component
public class ESClientFactory { @Autowired
ESConfig esConfig; public ESClient getClient(String type){ ESConfig.Config config = esConfig.configs.get(type); return new ESClient(config);
} }

工厂类-客户端

package com.example.elasticSearch;

public class Sport{

    String id;

    String title;

    String content;

    public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} 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;
}
}

BEAN

package com.example.elasticSearch;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RestController
@RequestMapping("/es")
public class ESController { @Autowired
ESClientFactory esClientFactory; @RequestMapping("/saveIndex")
public void saveIndex(@RequestBody Sport sport){
ESClient esClient = esClientFactory.getClient("sport");
esClient.saveIndex(sport);
} @RequestMapping("/saveDocument")
public void saveDocument(@RequestBody Sport sport) {
ESClient esClient = esClientFactory.getClient("sport");
esClient.saveDocument(sport);
} @RequestMapping("/getDocument")
public String getDocument(@RequestBody Sport sport) {
ESClient esClient = esClientFactory.getClient("sport");
return esClient.getDocument(sport);
}
}

测试类-Controller

springboot集成es7(基于high level client)的更多相关文章

  1. SpringBoot集成文件 - 如何基于POI-tl和word模板导出庞大的Word文件?

    前文我们介绍了通过Apache POI通过来导出word的例子:那如果是word模板方式,有没有开源库通过模板方式导出word呢?poi-tl是一个基于Apache POI的Word模板引擎,也是一个 ...

  2. springboot整合elasticsearch(基于es7.2和官方high level client)

    前言 最近写的一个个人项目(传送门:全终端云书签)中需要用到全文检索功能,目前 mysql,es 都可以做全文检索,mysql 胜在配置方便很快就能搞定上线(参考这里),不考虑上手难度,es 在全文检 ...

  3. 基于Springboot集成security、oauth2实现认证鉴权、资源管理

    1.Oauth2简介 OAuth(开放授权)是一个开放标准,允许用户授权第三方移动应用访问他们存储在另外的服务提供者上的信息,而不需要将用户名和密码提供给第三方移动应用或分享他们数据的所有内容,OAu ...

  4. SpringBoot集成Mybatis实现多表查询的两种方式(基于xml)

     下面将在用户和账户进行一对一查询的基础上进行介绍SpringBoot集成Mybatis实现多表查询的基于xml的两种方式.   首先我们先创建两个数据库表,分别是user用户表和account账户表 ...

  5. 基于Netty和SpringBoot实现一个轻量级RPC框架-Client端请求响应同步化处理

    前提 前置文章: <基于Netty和SpringBoot实现一个轻量级RPC框架-协议篇> <基于Netty和SpringBoot实现一个轻量级RPC框架-Server篇> & ...

  6. SpringBoot集成rabbitmq(二)

    前言 在使用rabbitmq时,我们可以通过消息持久化来解决服务器因异常崩溃而造成的消息丢失.除此之外,我们还会遇到一个问题,当消息生产者发消息发送出去后,消息到底有没有正确到达服务器呢?如果不进行特 ...

  7. SpringBoot集成Zipkin实现分布式全链路监控

    目录 Zipkin 简介 Springboot 集成 Zipkin 安装启动 zipkin 版本说明 项目结构 工程端口分配 引入 Maven 依赖 配置文件.收集器的设置 编写 Controller ...

  8. SpringBoot集成ssm-druid-通用mapper

    简单介绍 springboot 首先什么是springboot? springboot是spring的另外一款框架,设计目的是用来简化新的spring应用的搭建和开发时所需要的特定的配置,从而使开发过 ...

  9. ElasticSearch基础学习(SpringBoot集成ES)

    一.概述 什么是ElasticSearch? ElasticSearch,简称为ES, ES是一个开源的高扩展的分布式全文搜索引擎. 它可以近乎实时的存储.检索数据:本身扩展性很好,可以扩展到上百台服 ...

  10. Spring Security 集成 CAS(基于HTTP协议版本)

    Spring Security 集成 CAS(基于HTTP协议版本) 近段时间一直研究Spring Security 集成 CAS,网上资料相关资料也很多,不过大都是基于Https的安全认证;使用ht ...

随机推荐

  1. Vue进度条组件

    1.进度条颜色是渐变的 <template> <div id="progress_bar" ref="myChart"></div ...

  2. docker 安装 jFrog

    docker run --name artifactory-oss-6.18.1 -d -p 8083:8081 docker.bintray.io/jfrog/artifactory-oss:6.1 ...

  3. 从零开始升级基于RuleBased的聊天机器人

    这里记录从最基础的基于规则的聊天机器人,升级到基于逻辑的机器人,再升级到调用Google提供的API来让机器人能说.会听普通话. 最基本的完全基于规则式的问答:问什么就答什么,幼儿园水平. impor ...

  4. python socket 开发

    socket 服务端开发 #socket 服务端开发 import socket # 创建socket 对象 socket_server = socket.socket() # 绑定ip 地址和端口 ...

  5. JavaSE——金额转换

    package com.zhao.stringtest; import java.util.Scanner; public class Test3 { //金额转换 //查表法 public stat ...

  6. 去除Bam文件中的PCR 重复

    1.使用samtools 去除重复 samtools sort -n -@ 20 file.bam |samtools fixmate -m -@20 - - |samtools sort -@ 20 ...

  7. WPF 文本逐字一个个出现的动画效果

    一.效果图: 二.前台代码: <Grid> <TextBlock Foreground="Transparent" x:Name="text" ...

  8. IIS7无法访问.apk文件的解决方法

    随着智能手机的普及,越来越多的人使用手机上网,很多网站也应手机上网的需要推出了网站客户端,.apk文件就是安卓(Android)的应用程序后缀名,默认情况下,使用IIS作为Web服务器的无法访问下载此 ...

  9. ASP.NET Core Filter如何支持依赖注入

    通过Filter来支持:分别有IResourceFilter AuthorizeFilter ActionFilter ExceptionFilter ResultFilter,Filter也被称为拦 ...

  10. Java中创建线程的方式和线程中常用方法?

    Java中如何创建线程? 继承Thread类 实现Rnnable接口 实现Callable接口 通过线程池创建线程 线程中常用方法 线程等待:wait() 进入等待状态,只有等其他线程唤醒或中断才能运 ...