pox.xml文件添加以下内容

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.3.2</version>
</dependency>

新建ESHighLevelRestUtil.java

package com;

import java.util.HashMap;
import java.util.Map; import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchException;
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.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus; public class ESHighLevelRestUtil { static RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("172.19.12.249", 9200, "http"))); /**
* 验证索引是否存在
*
* @param index
* 索引名称
* @return
* @throws Exception
*/
public boolean indexExists(String index) throws Exception {
GetIndexRequest request = new GetIndexRequest();
request.indices(index);
request.local(false);
request.humanReadable(true); boolean exists = client.indices().exists(request);
return exists;
} /**
*
* @param index
* @param indexType
* @param properties
* 结构: {name:{type:text}} {age:{type:integer}}
* @return
* @throws Exception
*/
public boolean indexCreate(String index, String indexType,
Map<String, Object> properties) throws Exception { if (indexExists(index)) {
return true;
}
CreateIndexRequest request = new CreateIndexRequest(index);
request.settings(Settings.builder().put("index.number_of_shards", 3)
.put("index.number_of_replicas", 2)); Map<String, Object> jsonMap = new HashMap<>();
Map<String, Object> mapping = new HashMap<>();
mapping.put("properties", properties);
jsonMap.put(indexType, mapping);
request.mapping(indexType, jsonMap); CreateIndexResponse createIndexResponse = client.indices().create(
request);
boolean acknowledged = createIndexResponse.isAcknowledged();
return acknowledged;
} /**
* 删除索引
*
* @param index
* @return
* @throws Exception
*/
public boolean indexDelete(String index) throws Exception {
try {
DeleteIndexRequest request = new DeleteIndexRequest(index);
DeleteIndexResponse deleteIndexResponse = client.indices().delete(
request);
return deleteIndexResponse.isAcknowledged();
} catch (ElasticsearchException exception) {
if (exception.status() == RestStatus.NOT_FOUND) {
return true;
} else {
return false;
}
}
} /**
* 创建更新文档
*
* @param index
* @param indexType
* @param documentId
* @param josonStr
* @return
* @throws Exception
*/
public boolean documentCreate(String index, String indexType,
String documentId, String josonStr) throws Exception {
IndexRequest request = new IndexRequest(index, indexType, documentId); request.source(josonStr, XContentType.JSON);
IndexResponse indexResponse = client.index(request); if (indexResponse.getResult() == DocWriteResponse.Result.CREATED
|| indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
return true;
}
ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
return true;
}
if (shardInfo.getFailed() > 0) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo
.getFailures()) {
throw new Exception(failure.reason());
}
}
return false;
} /**
* 创建更新索引
*
* @param index
* @param indexType
* @param documentId
* @param map
* @return
* @throws Exception
*/
public boolean documentCreate(String index, String indexType,
String documentId, Map<String, Object> map) throws Exception {
IndexRequest request = new IndexRequest(index, indexType, documentId); request.source(map);
IndexResponse indexResponse = client.index(request); if (indexResponse.getResult() == DocWriteResponse.Result.CREATED
|| indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
return true;
}
ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
return true;
}
if (shardInfo.getFailed() > 0) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo
.getFailures()) {
throw new Exception(failure.reason());
}
}
return false;
} /**
* 创建索引
*
* @param index
* @param indexType
* @param josonStr
* @return
* @throws Exception
*/
public String documentCreate(String index, String indexType, String josonStr)
throws Exception {
IndexRequest request = new IndexRequest(index, indexType); request.source(josonStr, XContentType.JSON);
IndexResponse indexResponse = client.index(request); String id = indexResponse.getId();
if (indexResponse.getResult() == DocWriteResponse.Result.CREATED
|| indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
return id;
}
ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
return id;
}
if (shardInfo.getFailed() > 0) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo
.getFailures()) {
throw new Exception(failure.reason());
}
}
return null;
} /**
* 创建索引
*
* @param index
* @param indexType
* @param map
* @return
* @throws Exception
*/
public String documentCreate(String index, String indexType,
Map<String, Object> map) throws Exception {
IndexRequest request = new IndexRequest(index, indexType); request.source(map);
IndexResponse indexResponse = client.index(request); String id = indexResponse.getId();
if (indexResponse.getResult() == DocWriteResponse.Result.CREATED
|| indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
return id;
}
ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
return id;
}
if (shardInfo.getFailed() > 0) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo
.getFailures()) {
throw new Exception(failure.reason());
}
}
return null;
} public boolean documentDelete(String index, String indexType,
String documentId) throws Exception {
DeleteRequest request = new DeleteRequest(index, indexType, documentId);
DeleteResponse deleteResponse = client.delete(request);
if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) {
return true;
}
ReplicationResponse.ShardInfo shardInfo = deleteResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
return true;
}
if (shardInfo.getFailed() > 0) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo
.getFailures()) {
throw new Exception(failure.reason());
}
}
return false;
} }

新建ESHighLevelRestTest.java

package com;

import java.util.HashMap;
import java.util.Map; import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient; public class ESHighLevelRestTest {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ESHighLevelRestUtil util = new ESHighLevelRestUtil(); System.out.println(util.indexExists("indextest001")); Map<String, Object> map = new HashMap<String, Object>();
map.put("name", new HashMap() {
{
put("type", "text");
}
});
map.put("age", new HashMap() {
{
put("type", "double");
}
});
map.put("sex", new HashMap() {
{
put("type", "double");
}
});
map.put("address", new HashMap() {
{
put("type", "text");
}
}); // 创建主题
util.indexCreate("indextest005", "sx", map); //创建文档1
System.out.println(util.documentCreate("indextest005", "sx",
new HashMap<String,Object>() {
{
put("name", "名称1");
put("age", 18);
put("sex", 10);
put("address", "地址1");
}
})); //创建更新文档2
System.out.println(util.documentCreate("indextest005", "sx", "1",
new HashMap<String,Object>() {
{
put("name", "名称2");
put("age", 18);
put("sex", 10);
put("address", "地址2");
}
})); //删除文档
System.out.println(util.documentDelete("indextest005", "sx", "1"));
}
}

参考:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-overview.html

相互学习,如有不正确的地方欢迎指正

elasticsearch Java High Level REST 相关操作封装的更多相关文章

  1. java 线程 原子类相关操作演示样例 thinking in java4 文件夹21.3.4

    java 线程  原子类相关操作演示样例 package org.rui.thread.volatiles; import java.util.Timer; import java.util.Time ...

  2. 使用Java High Level REST Client操作elasticsearch

    Java高级别REST客户端(The Java High Level REST Client)以后简称高级客户端,内部仍然是基于低级客户端.它提供了更多的API,接受请求对象作为参数并返回响应对象,由 ...

  3. 使用Java Low Level REST Client操作elasticsearch

    Java REST客户端有两种风格: Java低级别REST客户端(Java Low Level REST Client,以后都简称低级客户端算了,难得码字):Elasticsearch的官方low- ...

  4. 数据结构Java实现04---树及其相关操作

    首先什么是树结构? 树是一种描述非线性层次关系的数据结构,树是n个数据结点的集合,这些集结点包含一个根节点,根节点下有着互相不交叉的子集合,这些子集合便是根节点的子树. 树的特点 在一个树结构中,有且 ...

  5. java 的Date 日期相关操作

    String 与 Date互转(1)基于SimpleDateFormat实现: package com.bky.df; import java.text.ParseException; import ...

  6. java实现安全证书相关操作

    https://blog.csdn.net/zhushanzhi/article/details/77864516 版权声明:本文为博主原创文章,未经博主允许不得转载. package test; i ...

  7. java实现二叉树的相关操作

    import java.util.ArrayDeque; import java.util.Queue; public class CreateTree { /** * @param args */ ...

  8. POI开发:Java中的Excel相关操作

    一.Apache POI 1.简介: Apache POI支持大多数中小规模的应用程序开发,提供API给Java程序对Microsoft Office格式档案读和写的功能,呈现和文本提取是它的主要特点 ...

  9. Elasticsearch Java Low Level REST Client(嗅探器)

    https://segmentfault.com/a/1190000016828977?utm_source=tag-newest#articleHeader0 嗅探器 允许从正在运行的Elastic ...

随机推荐

  1. Vue-cli3 环境的搭建

    Vue-cli3 环境的搭建 准备 浏览器插件:Vue.js devtools VsCode 和 VsCode 插件 WebStorm Nodejs vue-cli git 起飞 安装vue-cli3 ...

  2. 后缀自动机(SAM) 学习笔记

    最近学了SAM已经SAM的比较简单的应用,SAM确实不好理解呀,记录一下. 这里提一下后缀自动机比较重要的性质: 1,SAM的点数和边数都是O(n)级别的,但是空间开两倍. 2,SAM每个结点代表一个 ...

  3. JavaScript的三大组成部分

    JavaScript是一种属于网络的脚本语言,已经被广泛用于Web应用开发,常用来为网页添加各式各样的动态功能,为用户提供更流畅美观的浏览效果.通常JavaScript脚本是通过嵌入在HTML中来实现 ...

  4. ThreadPoolExecuotor源码参考

    Executor --> ExecutorService --> AbstractExecutorService --> ThreadPoolExecuotor Executor接口 ...

  5. BZOJ4710 [Jsoi2011]分特产 容斥

    题目传送门 https://lydsy.com/JudgeOnline/problem.php?id=4710 题解 本来想去找一个二项式反演的题的,结果被 https://www.cnblogs.c ...

  6. BZOJ2143 飞飞侠 & [校内NOIP2018模拟20181026] 最强大脑

    Time Limit: 50 Sec Memory Limit: 259 MB Description 飞飞国是一个传说中的国度,国家的居民叫做飞飞侠.飞飞国是一个N×M的矩形方阵,每个格子代表一个街 ...

  7. 【学习笔记】可持久化并查集(BZOJ3673)

    好久之前就想学了 然后今天恰巧一道题需要用到就学了 前置芝士 1.主席树[可持久化数组] 2.并查集 如果你掌握了前面两个那么这个东西你就会觉得非常沙茶.. 构造 可持久化并查集 = 主席树  + 并 ...

  8. shell编程之基础知识1

    1.shell脚本的基本格式 #!bin/bash   ->看到这个就是shell脚本 #filename:test.sh ->脚本名称 #auto echo hello world -& ...

  9. python自动刷新抢火车票

    #!/usr/bin/env python #-*- coding: utf-8 -*- """ 火车票 可以自动填充账号密码,同时,在登录时,也可以修改账号密码 然后手 ...

  10. 【转】跨域资源共享 CORS 详解

    本文来源:http://www.ruanyifeng.com/blog/2016/04/cors.html 阮一峰老师的网络日志 CORS是一个W3C标准,全称是"跨域资源共享"( ...