SpringBoot 配置 ElasticSearch7.4.0 java 封装Post 使用 Elasticsearch 的sql插件
Es配置
引入依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.0</version>
</dependency>
配置类
@Configuration
public class BaseElasticConfig {
private Logger logger= LoggerFactory.getLogger(BaseElasticConfig.class);
@Bean
public RestHighLevelClient esRestClient(){
logger.info("Es初始化开始==========");
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
//在这里配置你的elasticsearch的情况
new HttpHost("127.0.0.1", 9200, "http")
)
);
logger.info("Es初始化结束==========");
return client;
}
}
Es操作
新增索引:当索引存在时候会报错
@RequestMapping("/createindex")
public ResponseInfo createIndex() {
try {
CreateIndexRequest createIndexRequest = new CreateIndexRequest("test");
CreateIndexResponse createIndexResponse=client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
return null;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
判断索引是否存在
@RequestMapping("/exist")
public boolean testExistIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("test");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
return exists;
}
封装Post请求使用Sql插件查询结果
用java模拟发送如下的Post请求,使用sql插件
使用该方式,查询结果如下:得到Columns和Rows
Java封装Post请求模拟发送Post请求
/**
* 封装Post查询Es中的结果
*/
public String getEsResultBysql( String sql) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
// 请求的Url
String url_location = "http://127.0.0.1:9200/_sql";
// 请求体
String content = "{\"query\":\"" + sql + "\"}";
URL realUrl = new URL(url_location);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
((HttpURLConnection) conn).setRequestMethod("POST");
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(content);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
就可以写sql进行Es查询了,很Nice