Java连接简单使用ElasticSearch
1. 添加依赖
<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>8.2.2</version>
</dependency>
<!--引入json进行HTTP序列化-->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
2. 代码,无账号密码
package com.xiaostudy.mycode;
import com.xiaostudy.mycode.entity.ESUser;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.lang.reflect.Field;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @author liwei
* @version 1.0
* @className TestJDBC
* @date 2022/5/31 11:05
* @description 测试solr
*/
public class TestES {
public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, IOException {
RestClient client = getClient();
// createIndices(client, "user");
// boolean type = createType(client, "user", ESUser.class);
// System.out.println("=============================================");
// System.out.println("添加类的所有类型:" + type);
// System.out.println("=============================================");
// ESUser user = new ESUser();
// user.setId("1");
// user.setName("11");
// user.setAge(1L);
// String add = addByPost(client, "user", user);
// System.out.println("=============================================");
// System.out.println("添加返回:" + add);
// System.out.println("=============================================");
// ESUser user2 = new ESUser();
// user2.setId("3");
// user2.setName("张三");
// user2.setAge(33L);
// String add2 = addByPut(client, "user", user2);
// System.out.println("=============================================");
// System.out.println("添加返回:" + add2);
// System.out.println("=============================================");
// getByIndicesAll(client, "user");
// getByIndicesId(client, "user", "2");
// getByIndicesType(client, "user", "id", "2");
// getByIndicesType(client, "user", "name", "11");
client.close();
}
/**
* 获取索引下所有数据
*
* @param client
* @param indices
* @return java.util.List<com.xiaostudy.mycode.entity.ESUser>
* @author liwei
* @date 2022/6/6 11:00
*/
public static List<ESUser> getByIndicesId(RestClient client, String indices, String id) {
try {
Request request = new Request("GET", String.format("/%s/_search", indices));
JSONObject jsonObject2 = new JSONObject();
JSONObject jsonObject3 = new JSONObject();
JSONObject jsonObject4 = new JSONObject();
jsonObject4.put("default_field", "id");
jsonObject4.put("query", id);
jsonObject3.put("query_string", jsonObject4);
jsonObject2.put("query", jsonObject3);
request.setJsonEntity(jsonObject2.toString());
// 发送HTTP请求
Response response = client.performRequest(request);
HttpEntity entity = response.getEntity();
String s = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(s);
JSONObject hits = jsonObject.getJSONObject("hits");
JSONArray jsonArray = hits.getJSONArray("hits");
List<Object> list = jsonArray.toList();
List<ESUser> userList = new ArrayList<>();
for (Object o : list) {
JSONObject jsonObject1 = null;
HashMap<String, Object> hashMap = null;
if (o instanceof JSONObject) {
jsonObject1 = ((JSONObject) o).getJSONObject("_source");
} else if (o instanceof HashMap) {
Object source = ((HashMap) o).get("_source");
if (source instanceof JSONObject) {
jsonObject1 = (JSONObject) source;
} else if (source instanceof HashMap) {
hashMap = (HashMap) source;
}
}
if (null == jsonObject1 && null == hashMap) {
System.out.println("这行取数据有问题");
continue;
}
ESUser user = new ESUser();
Object age;
if (null == jsonObject1) {
user.setId((String) hashMap.get("id"));
user.setName((String) hashMap.get("name"));
age = hashMap.get("age");
} else {
user.setId((String) jsonObject1.get("id"));
user.setName((String) jsonObject1.get("name"));
age = jsonObject1.get("age");
}
Long ageLong = null;
if (age instanceof Long) {
ageLong = (Long) age;
} else if (age instanceof Integer) {
ageLong = ((Integer) age).longValue();
}
user.setAge(ageLong);
userList.add(user);
}
System.out.println("=============================================");
System.out.println(userList);
System.out.println("=============================================");
return userList;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取索引下所有数据
*
* @param client
* @param indices
* @return java.util.List<com.xiaostudy.mycode.entity.ESUser>
* @author liwei
* @date 2022/6/6 11:00
*/
public static List<ESUser> getByIndicesType(RestClient client, String indices, String type, String typeValue) {
try {
Request request = new Request("GET", String.format("/%s/_search", indices));
JSONObject jsonObject2 = new JSONObject();
JSONObject jsonObject3 = new JSONObject();
JSONObject jsonObject4 = new JSONObject();
jsonObject4.put("default_field", type);
jsonObject4.put("query", typeValue);
jsonObject3.put("query_string", jsonObject4);
jsonObject2.put("query", jsonObject3);
request.setJsonEntity(jsonObject2.toString());
// 发送HTTP请求
Response response = client.performRequest(request);
HttpEntity entity = response.getEntity();
String s = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(s);
JSONObject hits = jsonObject.getJSONObject("hits");
JSONArray jsonArray = hits.getJSONArray("hits");
List<Object> list = jsonArray.toList();
List<ESUser> userList = new ArrayList<>();
for (Object o : list) {
JSONObject jsonObject1 = null;
HashMap<String, Object> hashMap = null;
if (o instanceof JSONObject) {
jsonObject1 = ((JSONObject) o).getJSONObject("_source");
} else if (o instanceof HashMap) {
Object source = ((HashMap) o).get("_source");
if (source instanceof JSONObject) {
jsonObject1 = (JSONObject) source;
} else if (source instanceof HashMap) {
hashMap = (HashMap) source;
}
}
if (null == jsonObject1 && null == hashMap) {
System.out.println("这行取数据有问题");
continue;
}
ESUser user = new ESUser();
Object age;
if (null == jsonObject1) {
user.setId((String) hashMap.get("id"));
user.setName((String) hashMap.get("name"));
age = hashMap.get("age");
} else {
user.setId((String) jsonObject1.get("id"));
user.setName((String) jsonObject1.get("name"));
age = jsonObject1.get("age");
}
Long ageLong = null;
if (age instanceof Long) {
ageLong = (Long) age;
} else if (age instanceof Integer) {
ageLong = ((Integer) age).longValue();
}
user.setAge(ageLong);
userList.add(user);
}
System.out.println("=============================================");
System.out.println(userList);
System.out.println("=============================================");
return userList;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取索引下所有数据
*
* @param client
* @param indices
* @return java.util.List<com.xiaostudy.mycode.entity.ESUser>
* @author liwei
* @date 2022/6/6 11:00
*/
public static List<ESUser> getByIndicesAll(RestClient client, String indices) {
try {
// endpoint直接指定为index/type的形式
Request request = new Request("GET", String.format("/%s/_search", indices));
// 发送HTTP请求
Response response = client.performRequest(request);
System.out.println("=============================================");
// System.out.println(response);
HttpEntity entity = response.getEntity();
String s = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(s);
JSONObject hits = jsonObject.getJSONObject("hits");
JSONArray jsonArray = hits.getJSONArray("hits");
List<Object> list = jsonArray.toList();
List<ESUser> userList = new ArrayList<>();
for (Object o : list) {
JSONObject jsonObject1 = null;
HashMap<String, Object> hashMap = null;
if (o instanceof JSONObject) {
jsonObject1 = ((JSONObject) o).getJSONObject("_source");
} else if (o instanceof HashMap) {
Object source = ((HashMap) o).get("_source");
if (source instanceof JSONObject) {
jsonObject1 = (JSONObject) source;
} else if (source instanceof HashMap) {
hashMap = (HashMap) source;
}
}
if (null == jsonObject1 && null == hashMap) {
System.out.println("这行取数据有问题");
continue;
}
ESUser user = new ESUser();
Object age;
if (null == jsonObject1) {
user.setId((String) hashMap.get("id"));
user.setName((String) hashMap.get("name"));
age = hashMap.get("age");
} else {
user.setId((String) jsonObject1.get("id"));
user.setName((String) jsonObject1.get("name"));
age = jsonObject1.get("age");
}
Long ageLong = null;
if (age instanceof Long) {
ageLong = (Long) age;
} else if (age instanceof Integer) {
ageLong = ((Integer) age).longValue();
}
user.setAge(ageLong);
userList.add(user);
}
System.out.println(userList);
System.out.println("=============================================");
return userList;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 添加,id就是实体里面的id
*
* @param client
* @param indices
* @param user
* @return java.lang.String
* @author liwei
* @date 2022/6/2 23:18
*/
public static String addByPut(RestClient client, String indices, ESUser user) {
try {
// endpoint直接指定为index/type的形式
Request request = new Request("PUT", String.format("/%s/_doc/%s", indices, user.getId()));
JSONObject jsonObject = new JSONObject(user);
// 设置请求体并指定ContentType,如果不指定默认为APPLICATION_JSON
request.setJsonEntity(jsonObject.toString());
// 发送HTTP请求
Response response = client.performRequest(request);
// 获取响应体, id: AWXvzZYWXWr3RnGSLyhH
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 添加,id随机生成
*
* @param client
* @param indices
* @param user
* @return java.lang.String
* @author liwei
* @date 2022/6/2 23:18
*/
public static String addByPost(RestClient client, String indices, ESUser user) {
try {
// endpoint直接指定为index/type的形式
Request request = new Request("POST", String.format("/%s/_doc", indices));
JSONObject jsonObject = new JSONObject(user);
// 设置请求体并指定ContentType,如果不指定默认为APPLICATION_JSON
request.setJsonEntity(jsonObject.toString());
// 发送HTTP请求
Response response = client.performRequest(request);
// 获取响应体, id: AWXvzZYWXWr3RnGSLyhH
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 创建类型,创建类的所有类型,已有的类型就不再创建
*
* @param client
* @param indices
* @param clazz
* @return boolean
* @author liwei
* @date 2022/6/2 23:19
*/
public static boolean createType(RestClient client, String indices, Class clazz) {
try {
Request request = new Request("PUT", String.format("%s/_mapping", indices));
Field[] declaredFields = clazz.getDeclaredFields();
JSONObject jsonObject1 = new JSONObject();
JSONObject jsonObject2 = new JSONObject();
for (Field field : declaredFields) {
Class<?> type = field.getType();
String typeValue;
if (type == String.class) {
typeValue = "text";
} else if (type == Integer.class) {
typeValue = "integer";
} else if (type == Long.class) {
typeValue = "long";
} else if (type == Short.class) {
typeValue = "short";
} else if (type == Byte.class) {
typeValue = "byte";
} else if (type == Double.class) {
typeValue = "double";
} else if (type == Float.class) {
typeValue = "float";
} else if (type == Boolean.class) {
typeValue = "boolean";
} else {
typeValue = "text";
}
String fieldName = field.getName();
String s = getType(client, indices, fieldName);
if (null != s) {
continue;
}
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("type", typeValue);
jsonObject2.put(fieldName, jsonObject3);
}
if (jsonObject2.keySet().isEmpty()) {
return false;
}
jsonObject1.put("properties", jsonObject2);
// 设置请求体并指定ContentType,如果不指定默认为APPLICATION_JSON
request.setJsonEntity(jsonObject1.toString());
Response response = client.performRequest(request);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 创建类型,指定类型
*
* @param client
* @param indices
* @param type
* @param typeValue
* @return java.lang.String
* @author liwei
* @date 2022/6/2 23:19
*/
public static String createType(RestClient client, String indices, String type, String typeValue) {
String s = getType(client, indices, type);
if (null != s) {
return null;
}
try {
Request request = new Request("PUT", String.format("%s/_mapping", indices));
JSONObject jsonObject1 = new JSONObject();
JSONObject jsonObject2 = new JSONObject();
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("type", typeValue);
jsonObject2.put(type, jsonObject3);
jsonObject1.put("properties", jsonObject2);
// 设置请求体并指定ContentType,如果不指定默认为APPLICATION_JSON
request.setJsonEntity(jsonObject1.toString());
Response response = client.performRequest(request);
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 查询索引是否有该类型
*
* @param client
* @param indices
* @param type
* @return java.lang.String
* @author liwei
* @date 2022/6/2 23:18
*/
public static String getType(RestClient client, String indices, String type) {
try {
Request request = new Request("GET", String.format("%s/_mapping", indices));
Response response = client.performRequest(request);
String responseBody = EntityUtils.toString(response.getEntity());
if (null == responseBody) {
return null;
}
JSONObject jsonObject = new JSONObject(responseBody);
JSONObject jsonObject1 = jsonObject.getJSONObject(indices);
if (null == jsonObject1) {
return null;
}
JSONObject mappings = jsonObject1.getJSONObject("mappings");
System.out.println("=============================================");
System.out.println(mappings);
System.out.println("=============================================");
if (null == mappings) {
return null;
}
JSONObject properties = mappings.getJSONObject("properties");
if (null == properties) {
return null;
}
return properties.has(type) ? type : null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 创建索引,不存在则创建
*
* @param client
* @param indices
* @return java.lang.String
* @author liwei
* @date 2022/6/2 20:24
*/
public static String createIndices(RestClient client, String indices) {
String index = getIndices(client, indices);
if (null != index) {
return null;
}
try {
// 构造HTTP请求,第一个参数是请求方法,第二个参数是服务器的端点,host默认是http://localhost:9200,
// endpoint直接指定为index/type的形式
Request request = new Request("PUT", indices);
// 发送HTTP请求
Response response = client.performRequest(request);
// 获取响应体, id: AWXvzZYWXWr3RnGSLyhH
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 查询索引是否存在,存在返回,不存在返回null
*
* @param client
* @param indices
* @return java.lang.String
* @author liwei
* @date 2022/6/2 20:24
*/
public static String getIndices(RestClient client, String indices) {
try {
Request request = new Request("GET", indices);
Response response = client.performRequest(request);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("=============================================");
System.out.println(responseBody);
System.out.println("=============================================");
return responseBody;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 获取客户端
*
* @return org.elasticsearch.client.RestClient
* @author liwei
* @date 2022/6/2 23:18
*/
public static RestClient getClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
// 如果有多个从节点可以持续在内部new多个HttpHost,参数1是ip,参数2是HTTP端口,参数3是通信协议
RestClientBuilder clientBuilder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
// 最后配置好的clientBuilder再build一下即可得到真正的Client
return clientBuilder.build();
}
}
3. 代码,有账号密码,并且是https方式
package com.xiaostudy.mycode;
import com.xiaostudy.mycode.entity.ESUser;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @author liwei
* @version 1.0
* @className TestJDBC
* @date 2022/5/31 11:05
* @description 测试solr
*/
public class TestES {
public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, IOException, CertificateException {
RestClient client = getClient();
// createIndices(client, "user");
// boolean type = createType(client, "user", ESUser.class);
// System.out.println("=============================================");
// System.out.println("添加类的所有类型:" + type);
// System.out.println("=============================================");
// ESUser user = new ESUser();
// user.setId("1");
// user.setName("11");
// user.setAge(1L);
// String add = addByPost(client, "user", user);
// System.out.println("=============================================");
// System.out.println("添加返回:" + add);
// System.out.println("=============================================");
// ESUser user2 = new ESUser();
// user2.setId("3");
// user2.setName("张三");
// user2.setAge(33L);
// String add2 = addByPut(client, "user", user2);
// System.out.println("=============================================");
// System.out.println("添加返回:" + add2);
// System.out.println("=============================================");
// getByIndicesAll(client, "user");
// getByIndicesId(client, "user", "2");
// getByIndicesType(client, "user", "id", "2");
getByIndicesType(client, "user", "name", "11");
client.close();
}
/**
* 获取索引下所有数据
*
* @param client
* @param indices
* @return java.util.List<com.xiaostudy.mycode.entity.ESUser>
* @author liwei
* @date 2022/6/6 11:00
*/
public static List<ESUser> getByIndicesId(RestClient client, String indices, String id) {
try {
Request request = new Request("GET", String.format("/%s/_search", indices));
JSONObject jsonObject2 = new JSONObject();
JSONObject jsonObject3 = new JSONObject();
JSONObject jsonObject4 = new JSONObject();
jsonObject4.put("default_field", "id");
jsonObject4.put("query", id);
jsonObject3.put("query_string", jsonObject4);
jsonObject2.put("query", jsonObject3);
request.setJsonEntity(jsonObject2.toString());
// 发送HTTP请求
Response response = client.performRequest(request);
HttpEntity entity = response.getEntity();
String s = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(s);
JSONObject hits = jsonObject.getJSONObject("hits");
JSONArray jsonArray = hits.getJSONArray("hits");
List<Object> list = jsonArray.toList();
List<ESUser> userList = new ArrayList<>();
for (Object o : list) {
JSONObject jsonObject1 = null;
HashMap<String, Object> hashMap = null;
if (o instanceof JSONObject) {
jsonObject1 = ((JSONObject) o).getJSONObject("_source");
} else if (o instanceof HashMap) {
Object source = ((HashMap) o).get("_source");
if (source instanceof JSONObject) {
jsonObject1 = (JSONObject) source;
} else if (source instanceof HashMap) {
hashMap = (HashMap) source;
}
}
if (null == jsonObject1 && null == hashMap) {
System.out.println("这行取数据有问题");
continue;
}
ESUser user = new ESUser();
Object age;
if (null == jsonObject1) {
user.setId((String) hashMap.get("id"));
user.setName((String) hashMap.get("name"));
age = hashMap.get("age");
} else {
user.setId((String) jsonObject1.get("id"));
user.setName((String) jsonObject1.get("name"));
age = jsonObject1.get("age");
}
Long ageLong = null;
if (age instanceof Long) {
ageLong = (Long) age;
} else if (age instanceof Integer) {
ageLong = ((Integer) age).longValue();
}
user.setAge(ageLong);
userList.add(user);
}
System.out.println("=============================================");
System.out.println(userList);
System.out.println("=============================================");
return userList;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取索引下所有数据
*
* @param client
* @param indices
* @return java.util.List<com.xiaostudy.mycode.entity.ESUser>
* @author liwei
* @date 2022/6/6 11:00
*/
public static List<ESUser> getByIndicesType(RestClient client, String indices, String type, String typeValue) {
try {
Request request = new Request("GET", String.format("/%s/_search", indices));
JSONObject jsonObject2 = new JSONObject();
JSONObject jsonObject3 = new JSONObject();
JSONObject jsonObject4 = new JSONObject();
jsonObject4.put("default_field", type);
jsonObject4.put("query", typeValue);
jsonObject3.put("query_string", jsonObject4);
jsonObject2.put("query", jsonObject3);
request.setJsonEntity(jsonObject2.toString());
// 发送HTTP请求
Response response = client.performRequest(request);
HttpEntity entity = response.getEntity();
String s = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(s);
JSONObject hits = jsonObject.getJSONObject("hits");
JSONArray jsonArray = hits.getJSONArray("hits");
List<Object> list = jsonArray.toList();
List<ESUser> userList = new ArrayList<>();
for (Object o : list) {
JSONObject jsonObject1 = null;
HashMap<String, Object> hashMap = null;
if (o instanceof JSONObject) {
jsonObject1 = ((JSONObject) o).getJSONObject("_source");
} else if (o instanceof HashMap) {
Object source = ((HashMap) o).get("_source");
if (source instanceof JSONObject) {
jsonObject1 = (JSONObject) source;
} else if (source instanceof HashMap) {
hashMap = (HashMap) source;
}
}
if (null == jsonObject1 && null == hashMap) {
System.out.println("这行取数据有问题");
continue;
}
ESUser user = new ESUser();
Object age;
if (null == jsonObject1) {
user.setId((String) hashMap.get("id"));
user.setName((String) hashMap.get("name"));
age = hashMap.get("age");
} else {
user.setId((String) jsonObject1.get("id"));
user.setName((String) jsonObject1.get("name"));
age = jsonObject1.get("age");
}
Long ageLong = null;
if (age instanceof Long) {
ageLong = (Long) age;
} else if (age instanceof Integer) {
ageLong = ((Integer) age).longValue();
}
user.setAge(ageLong);
userList.add(user);
}
System.out.println("=============================================");
System.out.println(userList);
System.out.println("=============================================");
return userList;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取索引下所有数据
*
* @param client
* @param indices
* @return java.util.List<com.xiaostudy.mycode.entity.ESUser>
* @author liwei
* @date 2022/6/6 11:00
*/
public static List<ESUser> getByIndicesAll(RestClient client, String indices) {
try {
// endpoint直接指定为index/type的形式
Request request = new Request("GET", String.format("/%s/_search", indices));
// 发送HTTP请求
Response response = client.performRequest(request);
System.out.println("=============================================");
// System.out.println(response);
HttpEntity entity = response.getEntity();
String s = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(s);
JSONObject hits = jsonObject.getJSONObject("hits");
JSONArray jsonArray = hits.getJSONArray("hits");
List<Object> list = jsonArray.toList();
List<ESUser> userList = new ArrayList<>();
for (Object o : list) {
JSONObject jsonObject1 = null;
HashMap<String, Object> hashMap = null;
if (o instanceof JSONObject) {
jsonObject1 = ((JSONObject) o).getJSONObject("_source");
} else if (o instanceof HashMap) {
Object source = ((HashMap) o).get("_source");
if (source instanceof JSONObject) {
jsonObject1 = (JSONObject) source;
} else if (source instanceof HashMap) {
hashMap = (HashMap) source;
}
}
if (null == jsonObject1 && null == hashMap) {
System.out.println("这行取数据有问题");
continue;
}
ESUser user = new ESUser();
Object age;
if (null == jsonObject1) {
user.setId((String) hashMap.get("id"));
user.setName((String) hashMap.get("name"));
age = hashMap.get("age");
} else {
user.setId((String) jsonObject1.get("id"));
user.setName((String) jsonObject1.get("name"));
age = jsonObject1.get("age");
}
Long ageLong = null;
if (age instanceof Long) {
ageLong = (Long) age;
} else if (age instanceof Integer) {
ageLong = ((Integer) age).longValue();
}
user.setAge(ageLong);
userList.add(user);
}
System.out.println(userList);
System.out.println("=============================================");
return userList;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 添加,id就是实体里面的id
*
* @param client
* @param indices
* @param user
* @return java.lang.String
* @author liwei
* @date 2022/6/2 23:18
*/
public static String addByPut(RestClient client, String indices, ESUser user) {
try {
// endpoint直接指定为index/type的形式
Request request = new Request("PUT", String.format("/%s/_doc/%s", indices, user.getId()));
JSONObject jsonObject = new JSONObject(user);
// 设置请求体并指定ContentType,如果不指定默认为APPLICATION_JSON
request.setJsonEntity(jsonObject.toString());
// 发送HTTP请求
Response response = client.performRequest(request);
// 获取响应体, id: AWXvzZYWXWr3RnGSLyhH
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 添加,id随机生成
*
* @param client
* @param indices
* @param user
* @return java.lang.String
* @author liwei
* @date 2022/6/2 23:18
*/
public static String addByPost(RestClient client, String indices, ESUser user) {
try {
// endpoint直接指定为index/type的形式
Request request = new Request("POST", String.format("/%s/_doc", indices));
JSONObject jsonObject = new JSONObject(user);
// 设置请求体并指定ContentType,如果不指定默认为APPLICATION_JSON
request.setJsonEntity(jsonObject.toString());
// 发送HTTP请求
Response response = client.performRequest(request);
// 获取响应体, id: AWXvzZYWXWr3RnGSLyhH
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 创建类型,创建类的所有类型,已有的类型就不再创建
*
* @param client
* @param indices
* @param clazz
* @return boolean
* @author liwei
* @date 2022/6/2 23:19
*/
public static boolean createType(RestClient client, String indices, Class clazz) {
try {
Request request = new Request("PUT", String.format("%s/_mapping", indices));
Field[] declaredFields = clazz.getDeclaredFields();
JSONObject jsonObject1 = new JSONObject();
JSONObject jsonObject2 = new JSONObject();
for (Field field : declaredFields) {
Class<?> type = field.getType();
String typeValue;
if (type == String.class) {
typeValue = "text";
} else if (type == Integer.class) {
typeValue = "integer";
} else if (type == Long.class) {
typeValue = "long";
} else if (type == Short.class) {
typeValue = "short";
} else if (type == Byte.class) {
typeValue = "byte";
} else if (type == Double.class) {
typeValue = "double";
} else if (type == Float.class) {
typeValue = "float";
} else if (type == Boolean.class) {
typeValue = "boolean";
} else {
typeValue = "text";
}
String fieldName = field.getName();
String s = getType(client, indices, fieldName);
if (null != s) {
continue;
}
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("type", typeValue);
jsonObject2.put(fieldName, jsonObject3);
}
if (jsonObject2.keySet().isEmpty()) {
return false;
}
jsonObject1.put("properties", jsonObject2);
// 设置请求体并指定ContentType,如果不指定默认为APPLICATION_JSON
request.setJsonEntity(jsonObject1.toString());
Response response = client.performRequest(request);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 创建类型,指定类型
*
* @param client
* @param indices
* @param type
* @param typeValue
* @return java.lang.String
* @author liwei
* @date 2022/6/2 23:19
*/
public static String createType(RestClient client, String indices, String type, String typeValue) {
String s = getType(client, indices, type);
if (null != s) {
return null;
}
try {
Request request = new Request("PUT", String.format("%s/_mapping", indices));
JSONObject jsonObject1 = new JSONObject();
JSONObject jsonObject2 = new JSONObject();
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("type", typeValue);
jsonObject2.put(type, jsonObject3);
jsonObject1.put("properties", jsonObject2);
// 设置请求体并指定ContentType,如果不指定默认为APPLICATION_JSON
request.setJsonEntity(jsonObject1.toString());
Response response = client.performRequest(request);
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 查询索引是否有该类型
*
* @param client
* @param indices
* @param type
* @return java.lang.String
* @author liwei
* @date 2022/6/2 23:18
*/
public static String getType(RestClient client, String indices, String type) {
try {
Request request = new Request("GET", String.format("%s/_mapping", indices));
Response response = client.performRequest(request);
String responseBody = EntityUtils.toString(response.getEntity());
if (null == responseBody) {
return null;
}
JSONObject jsonObject = new JSONObject(responseBody);
JSONObject jsonObject1 = jsonObject.getJSONObject(indices);
if (null == jsonObject1) {
return null;
}
JSONObject mappings = jsonObject1.getJSONObject("mappings");
System.out.println("=============================================");
System.out.println(mappings);
System.out.println("=============================================");
if (null == mappings) {
return null;
}
JSONObject properties = mappings.getJSONObject("properties");
if (null == properties) {
return null;
}
return properties.has(type) ? type : null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 创建索引,不存在则创建
*
* @param client
* @param indices
* @return java.lang.String
* @author liwei
* @date 2022/6/2 20:24
*/
public static String createIndices(RestClient client, String indices) {
String index = getIndices(client, indices);
if (null != index) {
return null;
}
try {
// 构造HTTP请求,第一个参数是请求方法,第二个参数是服务器的端点,host默认是http://localhost:9200,
// endpoint直接指定为index/type的形式
Request request = new Request("PUT", indices);
// 发送HTTP请求
Response response = client.performRequest(request);
// 获取响应体, id: AWXvzZYWXWr3RnGSLyhH
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 查询索引是否存在,存在返回,不存在返回null
*
* @param client
* @param indices
* @return java.lang.String
* @author liwei
* @date 2022/6/2 20:24
*/
public static String getIndices(RestClient client, String indices) {
try {
Request request = new Request("GET", indices);
Response response = client.performRequest(request);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("=============================================");
System.out.println(responseBody);
System.out.println("=============================================");
return responseBody;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 获取客户端
*
* @return org.elasticsearch.client.RestClient
* @author liwei
* @date 2022/6/2 23:18
*/
public static RestClient getClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, CertificateException, IOException {
// 如果有多个从节点可以持续在内部new多个HttpHost,参数1是ip,参数2是HTTP端口,参数3是通信协议
// RestClientBuilder clientBuilder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
RestClientBuilder clientBuilder = RestClient.builder(new HttpHost("localhost", 9200, "https"));
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("elastic", "123456"));
// TODO 注意安装路径
Path caCertificatePath = Paths.get("F:\\安装包\\elasticsearch-8.2.2\\config\\certs\\http_ca.crt");
CertificateFactory factory =
CertificateFactory.getInstance("X.509");
Certificate trustedCa;
try (InputStream is = Files.newInputStream(caCertificatePath)) {
trustedCa = factory.generateCertificate(is);
}
KeyStore trustStore = KeyStore.getInstance("pkcs12");
trustStore.load(null, null);
trustStore.setCertificateEntry("ca", trustedCa);
SSLContextBuilder sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(trustStore, null);
final SSLContext sslContext = sslContextBuilder.build();
clientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider));
return clientBuilder.build();
}
}
4. 参考文章
ElasticSearch入门篇(保姆级教程)
Java 连接ES方式
Elasticsearch:使用 Elasticsearch Java client 8.0 来连接带有 HTTPS 的集群
Java连接简单使用ElasticSearch的更多相关文章
- Java连接MySQL数据库及简单操作代码
1.Java连接MySQL数据库 Java连接MySql需要下载JDBC驱动MySQL-connector-java-5.0.5.zip(举例,现有新版本).然后将其解压缩到任一目录.我是解压到D盘, ...
- Java连接Sql Server 2008的简单数据库应用
1.从微软官网下载JDBC驱动包 sqljdbc_4.0.2206.100_chs.exe,双击解压文件到指定目录,我的指定目录是: C:\Program Files\Microsoft JDBC D ...
- java 模拟简单搜索
Java 模拟简单搜索 实体类 package org.dennisit.entity; /** * * * @version : 1.0 * * @author : 苏若年 <a href=& ...
- 几个主流java连接池
池(Pool)技术在一定程度上可以明显优化服务器应用程序的性能,提高程序执行效率和降低系统资源开销.这里所说的池是一种广义上的池,比如数据库连接池.线程池.内存池.对象池等.其中,对象池可以看成保存对 ...
- java连接sql server2000/2005
接触Java或者JSP,难免会使用到数据库SQL Server 2000/2005(我使用2005标准版[9.0.3054]测试),经过自己的搜索和研究,使用JDBC连接SQL Server成功,特此 ...
- Java 连接MongoDB
1.驱动 通过java连接MongoDB需要一个java版的驱动 下载地址:http://mongodb.github.io/mongo-java-driver/ 2.连接MongoDB 通过 com ...
- Java连接redis的使用演示样例
Java连接redis的使用演示样例 Redis是开源的key-value存储工具,redis通经常使用来存储结构化的数据,由于redis的key能够包括String.hash.listset和sor ...
- 转载:Java连接MySQL 数据库的正确操作流程
转载网址:http://www.bitscn.com/pdb/mysql/201005/186551.html 以下的文章主要介绍的是Java连接MySQL 数据库(以MySQL数据库为例 ...
- java实现简单的单点登录
java实现简单的单点登录 摘要:单点登录(SSO)的技术被越来越广泛地运用到各个领域的软件系统当中.本文从业务的角度分析了单点登录的需求和应用领域:从技术本身的角度分析了单点登录技术的内部机制和实现 ...
随机推荐
- C++ 之多态总结
前言 最近为了完成数据库系统的实验,又复习起了<C++ Primer>,上一次看这本巨著也是大二下的六月份,那时看面向对象程序编程这一章还云里雾里的,没有领会多态的奥妙,学完 Java 之 ...
- 第五章、Linux网络服务之yum仓库
目录 一.yum仓库简介 二.yum配置文件 1yum主配置文件 2日志文件 三.yum命令详解 1查询软件包命令 2查询软件包组命令 3yum安装升级 4 软件卸载 四.搭建yum仓库 本地仓库 h ...
- go-zero微服务实战系列(七、请求量这么高该如何优化)
前两篇文章我们介绍了缓存使用的各种最佳实践,首先介绍了缓存使用的基本姿势,分别是如何利用go-zero自动生成的缓存和逻辑代码中缓存代码如何写,接着讲解了在面对缓存的穿透.击穿.雪崩等常见问题时的解决 ...
- Java开发学习(六)----DI依赖注入之setter及构造器注入解析
一.DI依赖注入 首先来介绍下Spring中有哪些注入方式? 我们先来思考 向一个类中传递数据的方式有几种? 普通方法(set方法) 构造方法 依赖注入描述了在容器中建立bean与bean之间的依赖关 ...
- 期末人福音——用Python写个自动批改作业系统
一.亮出效果 最近一些软件的搜题.智能批改类的功能要下线. 退1024步讲,要不要自己做一个自动批改的功能啊?万一哪天孩子要用呢! 昨晚我做了一个梦,梦见我实现了这个功能,如下图所示:功能简介:作对了 ...
- Sentinel-流量防卫兵
1.背景 1.1 简介 Sentinel 以流量为切入点,从流量控制.熔断降级.系统负载保护等多个维度保护服务的稳定性. Sentinel 具有以下特征 丰富的应用场景:Sentinel 承接了阿里巴 ...
- java版第一个代码——HelloWorld!
java版第一个代码--HelloWorld! 今天来接触一下java代码: 事前准备 jdk的配置(推荐jdk8或jdk11) notepad++或idea软件 开始编写 建立文件夹存放代码 建立j ...
- jdbc 08: statement应用场景
jdbc连接mysql,statement的应用场景 package com.examples.jdbc.o8_statement应用场景; import java.sql.*; import jav ...
- 基于infiniband(IB)网的MVAPICH2安装
一.下载安装包 下载链接:http://mvapich.cse.ohio-state.edu/downloads/ 二.解压编译安装 mkdir /home/xujb/mvapich2 tar -x ...
- H5移动端实现一键复制或长摁复制
今天接到了一个新的需求,要求我们对表单中的某一个字段进行复制,这个表单是不可选的,拿到需求的时候有点懵,不清楚下手点在哪,后来网上找了找,终于有了点眉目,感觉网上有些是实现不了的,特地在这里记录下进行 ...