版本:elasticsearch 7.13.4
1. 声明
当前内容主要为使用RestClient以及使用sql方式进行查询操作,主要参考官方文档
主要使用_sql方式进行查询
2. 主要demo
public static void main(String[] args) throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
Sniffer sniffer = Sniffer.builder(restClient).build();
try {
selectDataUsingNativeSql(restClient);
} finally {
sniffer.close();
restClient.close();
}
}
private static void selectDataUsingNativeSql(RestClient restClient) throws IOException {
Request request = new Request("GET", "/_sql");
request.setJsonEntity("{\"query\": \"SELECT * FROM book WHERE bookName is null and price>5 LIMIT 5\"}");
Response response = restClient.performRequest(request);
System.out.println(response);
String result = getResponseContent(response);
System.out.println(result);
}
private static String getResponseContent(Response response) throws UnsupportedOperationException, IOException {
if (response == null) {
return null;
}
HttpEntity entity = response.getEntity();
StringBuilder builder = new StringBuilder();
if (entity != null) {
InputStream content = entity.getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(content));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
builder.append("\n");
}
}
return builder.toString();
}
3.查询结果
format表示返回的格式,默认就是json
八月 01, 2021 1:18:43 下午 org.elasticsearch.client.RestClient logResponse
警告: request [GET http://localhost:9200/_nodes/http?timeout=1000ms] returned 1 warnings: [299 Elasticsearch-7.13.4-c5f60e894ca0c61cdbae4f5a686d9f08bcefc942 "Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.13/security-minimal-setup.html to enable security."]
八月 01, 2021 1:18:43 下午 org.elasticsearch.client.RestClient logResponse
警告: request [GET http://localhost:9200/_sql] returned 1 warnings: [299 Elasticsearch-7.13.4-c5f60e894ca0c61cdbae4f5a686d9f08bcefc942 "Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.13/security-minimal-setup.html to enable security."]
Response{requestLine=GET /_sql HTTP/1.1, host=http://localhost:9200, response=HTTP/1.1 200 OK}
{"columns":[{"name":"bookName","type":"text"},{"name":"count","type":"long"},{"name":"id","type":"long"},{"name":"price","type":"float"},{"name":"publishDate","type":"text"}],"rows":[[null,null,2,66.6,null]]}
查询成功
3. 缺点
1.不能使用分页查询,这个导致有点尴尬 ,而且具有多个限制官方描述限制
2.而且还可以支持其他的query?,感觉有点跑偏了,果然还是原生的查询好
|