• Elasticsearch连接方式有两种;分别为TCP协议HTTP协议

最近使用es比较多,之前使用一直是使用spring封装的spring-data-elasticsearch;关于spring-data-elasticsearch有以下几点比较难受:

  • 基于TCP协议的使用(不确定是否支持http, 公司XX云大佬推荐使用HTTP协议,好像是官方推荐?)

  • 版本对应比较恶心人

  • 不好用

  • 基于以上几点,索性抛弃spring-data-elasticsearch,自己造轮子;

  • 根据 官方文档 描述,我们选择使用RestHighLevelClient来实现es基础查询;


官方描述:

The Java REST Client comes in 2 flavors:

Java Low Level REST Client: the official low-level client for Elasticsearch. It allows to communicate with an Elasticsearch cluster through http. Leaves requests marshalling and responses un-marshalling to users. It is compatible with all Elasticsearch versions.

Java High Level REST Client: the official high-level client for Elasticsearch. Based on the low-level client, it exposes API specific methods and takes care of requests marshalling and responses un-marshalling.

  • 提供Java Low Level REST Client 版本和 Java High Level REST Client 版本:

    • Java Low Level REST Client 与所有Elasticsearch版本兼容(版本问题舒服)
    • 通过HTTP协议与Elasticsearch集群进行通信(大佬推荐)
    • Java High Level REST Client 是基于Java Low Level REST Client 版本实现更多高级API
  • 很显然我们选择RestHighLevelClient


Spring整合RestHighLevelClient

  1. 构建ElasticsearchClient
  • 查看RestHighLevelClient构造器可以发现可以使用RestClientBuilder来构建,简单demo如下
    /**
* 连接超时时间
*/
private final static int CONNECT_TIMEOUT = 5000;
/**
* 连接超时时间
*/
private final static int SOCKET_TIMEOUT = 40000;
/**
* 获取连接的超时时间
*/
private final static int CONNECTION_REQUEST_TIMEOUT = 1000;
/**
* 最大连接数
*/
private final static int MAX_CONNECT_NUM = 100;
/**
* 最大路由连接数
*/
private final static int MAX_CONNECT_ROUTE = 100; @Bean(name = "elasticsearchClient", destroyMethod = "close")
public RestHighLevelClient client() {
RestClientBuilder builder = RestClient.builder(new HttpHost("host", "port", "http"));
// 配置一些请求配置的参数
builder.setRequestConfigCallback(requestConfigBuilder -> {
requestConfigBuilder.setConnectTimeout(CONNECT_TIMEOUT);
requestConfigBuilder.setSocketTimeout(SOCKET_TIMEOUT);
requestConfigBuilder.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT);
return requestConfigBuilder;
});
// 配置一些httpClient的参数
builder.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.setMaxConnTotal(MAX_CONNECT_NUM);
httpClientBuilder.setMaxConnPerRoute(MAX_CONNECT_ROUTE);
return httpClientBuilder;
});
builder.setFailureListener(new RestClient.FailureListener(){
@Override
public void onFailure(HttpHost host) {
// TODO do something when failed
super.onFailure(host);
}
});
return new RestHighLevelClient(builder);
}
  • 支持一些回调与参数的配置,具体的API可自行查看RestClientBuilder的源码
  • 配置完client后我们可以使用client造一些简单的轮子, 如es默认查询只可以查询1000条数据,我们可以封装查询所有数据
    public List<SearchHit> searchAll(SearchRequest searchRequest) {
try {
List<SearchHit> hits = new ArrayList<>(16);
int maxNum = searchRequest.source().size();
searchRequest.scroll(TimeValue.timeValueMinutes(10));
SearchResponse search = client.search(searchRequest);
hits.addAll(Arrays.asList(search.getHits().getHits()));
while (search.getHits().getHits().length == maxNum) {
SearchScrollRequest searchScrollRequest = new SearchScrollRequest(search.getScrollId());
searchScrollRequest.scroll(TimeValue.timeValueMinutes(10));
search = client.searchScroll(searchScrollRequest);
hits.addAll(Arrays.asList(search.getHits().getHits()));
}
return hits;
} catch (IOException e) {
log.error("Get message error.", e);
return null;
}
}
  • 有了以上接口,我们可以查询一些常用数据,如以下为查询数据的简单使用:
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
boolBuilder.filter(QueryBuilders.termQuery("type", 0));
boolBuilder.filter(QueryBuilders.termsQuery("id.keyword", id)); RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("createTime");
rangeQueryBuilder.gte(startTime);
rangeQueryBuilder.lte(endTime);
boolBuilder.filter(rangeQueryBuilder); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.size(9999);
sourceBuilder.fetchSource(new String[]{"field1", "field2", "field3"}, new String[]{});
sourceBuilder.query(boolBuilder); SearchRequest searchRequest = new SearchRequest("index");
searchRequest.source(sourceBuilder);
List<SearchHit> searchHits = repository.searchAll(searchRequest);
  • 具体API使用可查看官方文档

更新于2019-10-28

IndexRequest indexRequest = new IndexRequest(index, type, id);
indexRequest.source(entityMapper.mapToString(map), Requests.INDEX_CONTENT_TYPE);
return client.index(indexRequest);
  • 官方API中IndexRequest提供以下几种source方法:

    • 值得注意的是source(Map source)source(Map source, XContentType contentType) 方法,对于Map的传参,会进行类型校验;
    • 源码如下:
     public IndexRequest source(Map source, XContentType contentType) throws ElasticsearchGenerationException {
    try {
    XContentBuilder builder = XContentFactory.contentBuilder(contentType);
    builder.map(source);
    return source(builder);
    } catch (IOException e) {
    throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
    }
  • 其中builder.map中的unknownValue方法会遍历参数进行逐一校验:

  • 源码如下:

   private XContentBuilder map(Map<String, ?> values, boolean ensureNoSelfReferences) throws IOException {
if (values == null) {
return this.nullValue();
} else {
if (ensureNoSelfReferences) {
ensureNoSelfReferences(values);
} this.startObject();
Iterator var3 = values.entrySet().iterator(); while(var3.hasNext()) {
Entry<String, ?> value = (Entry)var3.next();
this.field((String)value.getKey());
this.unknownValue(value.getValue(), false);
} this.endObject();
return this;
}
}
  • 检验方法源码
    private void unknownValue(Object value, boolean ensureNoSelfReferences) throws IOException {
if (value == null) {
this.nullValue();
} else {
XContentBuilder.Writer writer = (XContentBuilder.Writer)WRITERS.get(value.getClass());
if (writer != null) {
writer.write(this, value);
} else if (value instanceof Path) {
this.value((Path)value);
} else if (value instanceof Map) {
Map<String, ?> valueMap = (Map)value;
this.map(valueMap, ensureNoSelfReferences);
} else if (value instanceof Iterable) {
this.value((Iterable)value, ensureNoSelfReferences);
} else if (value instanceof Object[]) {
this.values((Object[])value, ensureNoSelfReferences);
} else if (value instanceof ToXContent) {
this.value((ToXContent)value);
} else {
if (!(value instanceof Enum)) {
throw new IllegalArgumentException("cannot write xcontent for unknown value of type " + value.getClass());
} this.value(Objects.toString(value));
} }
}
  • 为了避免这个坑,可以使用jsonString来规避,具体使用如下:
	IndexRequest indexRequest = new IndexRequest(index, type, id);
indexRequest.source(JSON.toJSONString(map), Requests.INDEX_CONTENT_TYPE);
client.index(indexRequest);

Spring与RestHighLevelClient的更多相关文章

  1. springboot使用RestHighLevelClient批量插入

    1.引入maven(注意版本要一致) <dependency> <groupId>org.springframework.boot</groupId> <ar ...

  2. 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 ...

  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. elasticsearch RestHighLevelClient 使用方法及封装工具

    目录 EsClientRHL 更新日志 开发原因: 使用前你应该具有哪些技能 工具功能范围介绍 工具源码结构介绍 开始使用 未来规划 git地址:https://gitee.com/zxporz/ES ...

  5. ElasticSearch使用RestHighLevelClient进行搜索查询

    Elasticsearch Java API有四类client连接方式:TransportClient.  RestClient .Jest. Spring_Data_Elasticsearch.其中 ...

  6. ElasticSearch RestHighLevelClient 通用操作

    项目中使用到ElasticSearch作为搜索引擎.而ES的环境搭建自然是十分简单,且本身就适应于分布式环境,因此这块就不多赘述.而其本身特性和查询语句这篇博文不会介绍,如果有机会会深入介绍. ​ 所 ...

  7. 20191127 Spring Boot官方文档学习(4.11)

    4.11.使用NoSQL技术 Spring Data提供了其他项目来帮助您访问各种NoSQL技术,包括: Redis MongoDB Neo4J Solr Elasticsearch Cassandr ...

  8. 3.3_springBoot2.1.x检索之RestHighLevelClient方式

    1.版本依赖 注意对 transport client不了解先阅读官方文档: transport client(传送门) 这里需要版本匹配,如失败查看官网或百度. pom.xml <?xml v ...

  9. Spring Boot 教程 - Elasticsearch

    1. Elasticsearch简介 Elasticsearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口.Elasticsearc ...

随机推荐

  1. PMP--1.6 项目经理

    本节都是理论的东西,可以在管理没有思路的或者管理陷入困境的时候当做提升或解决问题的思路来看. 一.项目经理 1. 项目经理.职能经理与运营经理的区别 (1)职能经理专注于对某个职能领域或业务部门的管理 ...

  2. Git操作:绑定上传已存在的仓库到Github

    之前使用github都是创建一个全新的仓库,然后clone下来用,但如果我已经有一个正在使用的仓库,想要绑定上传已存在的仓库到github,怎么做呢?其实在github创建仓库的时候会提示: …or ...

  3. Centos7之selinux配置

    selinux是一个重要的lunux安全机制,存在于linuxKernel中,默认是开启的,会对用户行为做出多种限制,为了方便操作,有时候需要关闭它: 查看selinux状态:/usr/sbin/se ...

  4. vue中keepalive怎么理解?​---vue中文社区

    vue中keepalive怎么理解? 说在前面: keep-alive是vue源码中实现的一个组件, 感兴趣的可以研究源码 https://github.com/vuejs/vue/blob/dev/ ...

  5. Dalvik虚拟机和Art虚拟机

    Dalvik虚拟机 DVM是Dalvik Virtual Machine的缩写,是Android4.4及以前使用的虚拟机,所有android程序都运行在android系统进程里,每个进程对应着一个Da ...

  6. NIO学习笔记,从Linux IO演化模型到Netty—— Linux零拷贝

    这里只是感性地认识Linux零拷贝,不涉及具体细节. 1.Linux传统的数据拷贝 用户进程是不能直接访问文件系统的,要先切换到内核态,发起系统调用,DMA把磁盘中的数据写入内核空间,内核再把数据拷贝 ...

  7. opencv —— erode、dilate 腐蚀与膨胀

    腐蚀与膨胀是形态学滤波.其中,腐蚀是最小值滤波,膨胀是最大值滤波,即分别选取内核中的最小值与最大值赋值给锚点.若内核为 N×1 或 1×N 形状,可用于横纵方向直线检测. 膨胀:dilate 函数 v ...

  8. 转:Laravel 项目开发规范

    文件介绍很好 值得细细看看 https://www.jianshu.com/p/e464a35e5ed2 https://learnku.com/docs/laravel-specification/ ...

  9. Sikerio --《只狼》

    “狼啊,替我断绝不死吧”

  10. D - Counting Squares

    Your input is a series of rectangles, one per line. Each rectangle is specified as two points(X,Y) t ...