com.jl.JLEsSearchSql Maven / Gradle / Ivy
package com.jl;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.http.HttpHost;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.*;
import org.springframework.util.StringUtils;
import java.util.*;
/**
* es sql查询工具
*/
public class JLEsSearchSql {
/**
* 连接es
*/
public static void connect(String ip, int port) {
HttpHost[] httpHosts = new HttpHost[1];
httpHosts[0] = new HttpHost(ip, port);
RestClientBuilder builder = RestClient.builder(httpHosts);
RestClient restClient = RestClient.builder(httpHosts).build();
while (true) {
Scanner sc = new Scanner(System.in);
System.out.print("sql: ");
String sql = sc.nextLine();
if (!StringUtils.isEmpty(sql)) {
sqlExec(restClient, builder, sql);
}
}
}
private static void sqlExec(RestClient restClient, RestClientBuilder builder, String sql) {
String way = sql.substring(0, 4);
if (way.toLowerCase().equals("drop")) {
drop(builder, sql);
} else {
query(restClient, sql);
}
}
public static void drop(RestClientBuilder builder, String sql) {
String indexName = sql.substring(sql.lastIndexOf(" ") + 1);
DeleteIndexRequest request = new DeleteIndexRequest(indexName);
RestHighLevelClient client = new RestHighLevelClient(builder);
try {
AcknowledgedResponse deleteIndexResponse = client.indices().delete(request, RequestOptions.DEFAULT);
boolean acknowledged = deleteIndexResponse.isAcknowledged();
if (acknowledged) {
System.out.println("\n\n删除成功\n\n");
} else {
System.out.println("\n\n删除失败\n\n");
}
} catch (Exception e) {
System.out.println("\n\nsql或连接错误\n\n");
}
}
public static void query(RestClient restClient, String sql) {
List