网站推荐、资源下载等 | 个人网站

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 的集群

posted @ 2022-08-09 22:59  xiaostudy  阅读(165)  评论(0编辑  收藏  举报
网站推荐
[理工最爱]小时百科 |  GitHub |  Gitee |  开源中国社区 |  牛客网 |  不学网论坛 |  r2coding |  冷熊简历 |  爱盘 |  零散坑 |  bootstrap中文网 |  vue.js官网教程 |  源码分享站 |  maven仓库 |  楼教主网站 |  廖雪峰网站 |  w3cschool |  在线API |  代码在线运行 |  [不学网]代码在线运行 |  JS在线运行 |  PHP中文网 |  深度开源eclipse插件 |  文字在线加密解密 |  菜鸟教程 |  慕课网 |  千图网 |  手册网 |  素材兔 |  盘多多 |  悦书PDF |  sumatra PDF |  calibre PDF |  Snipaste截图 |  shareX截图 |  vlc-media-player播放器 |  MCMusic player |  IDM下载器 |  格式工厂 |  插件网 |  谷歌浏览器插件 |  Crx搜搜 |  懒人在线计算器 |  leetcode算法题库 |  layer官网 |  layui官网 |  formSelects官网 |  Fly社区 |  程序员客栈 |  融云 |  华为云 |  阿里云 |  ztree官网API |  teamviewer官网 |  sonarlint官网 |  editormd |  pcmark10官网 |  crx4chrome官网 |  apipost官网 |  花生壳官网 |  serv-u官网 |  杀毒eset官网 |  分流抢票bypass官网 |  懒猴子CG代码生成器官网 |  IT猿网 |  natapp[内网穿透] |  ngrok[内网穿透] |  深蓝穿透[内网穿透] |  WakeMeOnLan[查看ip] |  iis7 |  [漏洞扫描]Dependency_Check官网 |  [图标UI]fontawesome官网 |  idea插件官网 |  路过图床官网 |  sha256在线解密 |  在线正则表达式测试 |  在线文件扫毒 |  KuangStudy | 
资源下载
电脑相关: Windows原装下载msdn我告诉你 |  U盘制作微PE工具官网下载 |  Linux_CentOS官网下载 |  Linux_Ubuntu官网下载 |  Linux_OpenSUSE官网下载 |  IE浏览器官网下载 |  firefox浏览器官网下载 |  百分浏览器官网下载 |  谷歌google浏览器历史版本下载 |  深度deepin系统官网下载 |  中兴新支点操作系统官网下载 |  文件对比工具Beyond Compare官网下载 |  开机启动程序startup-delayer官网下载 |  openoffice官网下载 |  utorrent官网下载 |  qbittorrent官网下载 |  cpu-z官网下载 |  蜘蛛校色仪displaycal官网下载 |  单文件制作greenone下载 |  win清理工具Advanced SystemCare官网下载 |  解压bandizip官网下载 |  内存检测工具memtest官网下载 |  磁盘坏道检测与修复DiskGenius官网下载 |  磁盘占用可视化SpaceSniffer官网下载 |  [磁盘可视化]WizTree官网下载 |  win快速定位文件Everything官网下载 |  文件定位listary官网下载 |  动图gifcam官网下载 |  7-Zip官网下载 |  磁盘分区工具diskgenius官网下载 |  CEB文件查看工具Apabi Reader官网下载 |  罗技鼠标options官网下载 |  [去除重复文件]doublekiller官网下载 | 
编程相关: ApacheServer官网下载 |  Apache官网下载 |  Git官网下载 |  Git高速下载 |  Jboss官网下载 |  Mysql官网下载 |  Mysql官网历史版本下载 |  NetBeans IDE官网下载 |  Spring官网下载 |  Nginx官网下载 |  Resin官网下载 |  Tomcat官网下载 |  jQuery历史版本下载 |  nosql官网下载 |  mongodb官网下载 |  mongodb_linux历史版本下载 |  mongodb客户端下载 |  VScode官网下载 |  cxf官网下载 |  maven官网下载 |  QT官网下载 |  SVN官网下载 |  SVN历史版本下载 |  nodeJS官网下载 |  oracle官网下载 |  jdk官网下载 |  STS官网下载 |  STS历史版本官网下载 |  vue官网下载 |  virtualbox官网下载 |  docker desktop官网下载 |  github desktop官网下载 |  EditPlus官网下载 |  zTree下载 |  layui官网下载 |  jqgrid官网下载 |  jqueryui官网下载 |  solr历史版本下载 |  solr分词器ik-analyzer-solr历史版本下载 |  zookeeper历史版本官网下载 |  nssm官网下载 |  elasticsearch官网下载 |  elasticsearch历史版本官网下载 |  redis官网下载 |  redis历史版本官网下载 |  redis的win版本下载 |  putty官网下载 |  查看svn密码TSvnPD官网下载 |  MongoDB连接工具Robo官网下载 |  dll查看exescope官网下载 |  dll2c官网下载 |  接口测试apipost官网下载 |  接口测试postman官网下载 |  原型设计工具AxureRP官网下载 |  canal官网下载 |  idea主题样式下载 |  vue的GitHub下载 |  finalShell官网下载 |  ETL工具kafka官网下载 |  cavaj[java反编译]官网下载 |  jd-gui[java反编译]官网下载 |  radmin[远程连接]官网下载 |  tcping[win ping端口]下载 |  jQueryUploadFile官网下载 |  RedisPlus下载 |  aiXcoder智能编程助手官网下载 |  [表单效验]validform官网下载 |  idea官网下载 |  RedisStudio下载 |  MD转word含公式pandoc官网下载 |  logviewer官网下载 |  Kafka官网下载 |  hbase高速下载 |  hadoop官网下载 |  hadooponwindows的GitHub下载 |  hive官网下载 |  soapui官网下载 |  flink官网下载 |  kafkatool官网下载 |  MinIO官网下载 |  MinIO中国镜像下载 | 
办公相关工具
免费在线拆分PDF【不超过30M】 |  免费在线PDF转Word【不超过10M】 |  在线文字识别转换【不超过1M】 |  PDF转换成Word【不超过50M】 |  在线OCR识别 |  Smallpdf |  文件转换器Convertio |  迅捷PDF转换器 |  字母大小写转换工具 |  档铺 |  快传airportal[可文字] |  快传-文叔叔 |  P2P-小鹿快传 |  [图床]ImgURL | 
网站入口
腾讯文档 |  有道云笔记网页版 |  为知笔记网页版 |  印象笔记网页版 |  蓝奏云 |  QQ邮箱 |  MindMaster在线思维导图 |  bilibili |  PDM文件在线打开 |  MPP文件在线打开 |  在线PS软件 |  在线WPS |  阿里云企业邮箱登陆入口 | 
其他
PDF转换 |  悦书PDF转换 |  手机号注册查询 |  Reg007 |  akmsg |  ip8_ip查询 |  ipip_ip查询 |  天体运行testtubegames |  测试帧率 |  在线网速测试 |