自定义ElasticSearch客户端(支持sql与dsl语句)

前言:公司需要升级es,项目原本采用的是6.x,需要升级到7.x,其中加了密码,导致了不能使用,公司标准项目采用的是es官方api文档,那个文档对于升级及其不友好,因为sql语句没有办法转换为api,无奈自己写了一个。

es连接:

根据官方文档我们知道es支持http协议,因此我们定义一个http客户端

首先先定义一个http配置文件,内容如下

//get和set就省略了    
    private String jdbcUrl;
    private String url;
    private String noIndexUrl;
    private String username;
    private String password;
    private String auth;
    private String index;
    private int connectTimeout;
    private int readTimeout;


    public EsConfig(String jdbcUrl, Properties props,String index) {
    	 this.index=index;
    	 init(jdbcUrl, props);
    }

    private void init(String jdbcUrl, Properties props) {
        this.jdbcUrl = jdbcUrl;
        noIndexUrl= (jdbcUrl.contains("http") ? "" : "http://")
                + (jdbcUrl.replaceFirst(EsTool.URL_PREFIX, "") + "/").replace("//", "/");
        this.url = noIndexUrl  + index ;
        // BASE64加密
        this.username = props.getProperty("user", props.getProperty("username"));
        this.password = props.getProperty("pass", props.getProperty("password"));
        this.auth = "Basic " + new BASE64Encoder().encode((username + ":" + password).getBytes(StandardCharsets.UTF_8));

        this.connectTimeout = EsTool.parseInt(props.getProperty("connectTimeout"), 30000);
        this.readTimeout = EsTool.parseInt(props.getProperty("readTimeout"), 60000);
    }

自定义http请求客户端

连接部分

  private final List<EsConfig> esConfig;
    
    /**
	 * 当前使用的是第几个连接
	 */
	private volatile int index = 0;


    public  EsHttpClient(List<EsConfig> esConfigs) throws SQLException {
        this.esConfig = esConfigs;
    }
/**
     * @param uri
     * @param method
     * @param auth
     * @param body   请求参数,Json串
     * @return
     */
    public String send(String uri, String method, String auth, String body) throws IOException {
    	
        String result = null;
        OutputStream out = null;
        InputStream in = null;
        try {
            URL url = new URL(uri);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setReadTimeout(esConfig.get(index).getReadTimeout());
            connection.setConnectTimeout(esConfig.get(index).getConnectTimeout());
            connection.setAllowUserInteraction(false);
            connection.setRequestMethod(EsTool.isEmpty(method) ? "POST" : method);
            connection.setRequestProperty("content-type", "application/json;charset=utf-8");
            if (!EsTool.isEmpty(auth)) {
                connection.setRequestProperty("Authorization", auth);
            }
            connection.connect();// 获取连接

            if (!EsTool.isEmpty(body)) {
                out = connection.getOutputStream();
                out.write(EsTool.bytes(body, StandardCharsets.UTF_8));
                // out.flush();
            }

            in = connection.getInputStream();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));

            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = buffer.readLine()) != null) {
                sb.append(line);
            }
            result = sb.toString();

            connection.disconnect();
        } catch (Exception e) {
        	e.printStackTrace();
        	index++;
			if (index == esConfig.size()) {
				/**
				 * es所有连接都不可用
				 */
				throw new RuntimeException("es所有连接都不可用");
			} else {
				return send(uri, method, auth, body);
			}
        } finally {
            try {
                if (null != in)
                    in.close();
                if (null != out)
                    out.close();
            } catch (Exception e2) {
                System.out.println("[关闭流异常][错误信息:" + e2.getMessage() + "]");
            }
        }
        return result;
    }

初始化连接客户端需要的es配置文件

public static final String esType="0";
	
	private static  Map<String,List<EsConfig>> esConfig = new HashMap<String, List<EsConfig>>();
	
	public static synchronized List<EsConfig> getEsConfig(String idnex){
		if(esConfig.get(idnex)==null){
			//初始化esConfig
			//单节点测试,服务器为多节点
			 String jdbcUrl="jdbc:es://ip:9200/";
			 Properties props = new Properties();
			 props.put("username", "用户名");
			 props.put("password", "密码");
			 EsConfig mEsConfig = new EsConfig(jdbcUrl,props,idnex);
			 List<EsConfig> list = new ArrayList<>();
			 list.add(mEsConfig);
			 esConfig.put(idnex, list);
		}
		return esConfig.get(idnex);
	}

sql转dsl语句

	 public static String sqlToEsQuery(String sql) throws Exception {
	        Map actions = new HashMap();
	        Settings settings = Settings.builder().build();

	        ThreadPool threadPool = new ThreadPool(settings);
	        NodeClient client = new NodeClient(settings, threadPool);
	        SearchDao searchDao = new SearchDao(client);
	        try {
	            return searchDao.explain(sql).explain().explain();
	        } catch (Exception e) {
	            throw e;
	        }
	    }
	 

项目地址:自定义ElasticSearch客户端(支持sql与dsl语句): 自定义ElasticSearch客户端(支持sql与dsl语句)其中nlpcn是摘自elasticsearch-sql-7.8.0.1.jar包内容 - Gitee.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值