2019独角兽企业重金招聘Python工程师标准>>>
从ElasticSearch(后续简称ES)5.0开始,官方推出了自己的Rest Client(在此之前,我们使用Jest提供Rest风格的ES访问)。由于官网的Demo比较简单,在此列举几个常规的使用方法。
Java Rest Client官方地址:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html
Java API官方地址:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/index.html
初始化RestClient
RestClient restClient = RestClient.builder(
new HttpHost("127.0.0.1", 8310, "http"),
new HttpHost("127.0.0.1", 8210, "http"),
new HttpHost("127.0.0.1", 8110, "http"))
.build();
写入操作
// 可以使用json工具类、Pojo等方式生成json串
JSONObject demo = new JSONObject();
demo.put("user_id", 1L);
demo.put("user_name", "yan");
demo.put("age", 30);
String json = demo.toJSONString();
// http消息体
HttpEntity httpEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
// http uri, eg. /user/basic/${id}
String indexEndPoint = new StringBuffer()
.append("/").append(index)
.append("/").append(type)
.append("/").append(id)
.toString();
// 该方法会抛出IOException, 根据需要进行处理
Response response = restClient.performRequest("PUT",
indexEndPoint,
Collections.emptyMap(),
httpEntity);
// 获取http请求结果状态,可以与org.apache.http.HttpStatus的类聚类进行判断,新数据status_code = 201, 更新status_code = 200
int statusCode = response.getStatusLine().getStatusCode();
读取操作
// 构造Query DSL,推荐使用es官方java api
QueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("id", 1));
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(queryBuilder);
searchSourceBuilder.from(0).size(10);
HttpEntity httpEntity = new StringEntity(searchSourceBuilder.toString(), ContentType.APPLICATION_JSON);
// http uri, eg. /user/basic/_search
String searchEndPoint = new StringBuffer()
.append("/").append(index)
.append("/").append(type)
.append("/_search")
.toString();
// 该操作会抛出IOException;第三个参数paramMap可以添加es优化类属性,eg. pretty、rounting等
Response response = restClient.performRequest("GET",
searchEndPoint,
Collections.emptyMap(),
httpEntity);
/*
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "user",
"_type": "basic",
"_id": "1",
"_score": 1,
"_source": {
"age": 25,
"id": 1,
"name": "lee"
}
}
]
}
}
*/
String originReponseLine = EntityUtils.toString(response.getEntity());