这里索引,实际就是增加数据的意思,ES中常用叫法,本篇及后续都是参照高级REST-API实现的。提交的数据的格式有多种,下面介绍几种常用的。
创建Client
public static RestHighLevelClient getClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost(ES_IP, ES_PORT, "http")));
return client;
}
1、map形式
/**
* 索引数据
* @param index 索引
* @param type 类型
* @param id 文档的id
* @param json 数据格式
* @return
* @throws Exception
*/
public static IndexResponse index(String index,String type,String id, Map<String,Object> json) throws Exception{
RestHighLevelClient restClient = getClient();
IndexResponse indexResponse = null;
try {
IndexRequest indexRequest = new IndexRequest(index, type, id);
indexRequest.source(json);
indexResponse = restClient.index(indexRequest, RequestOptions.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}finally {
restClient.close();
}
return indexResponse;
}
2、Json格式
/**
* json形式索引数据
*
* @param index 索引
* @param type 类型
* @param id 文档id
* @param jsonString json格式数据
* @return
* @throws Exception
*/
public static IndexResponse index(String index,String type,String id, String jsonString) throws Exception{
RestHighLevelClient restClient = getClient();
IndexResponse indexResponse = null;
try {
IndexRequest indexRequest = new IndexRequest(index, type, id);
indexRequest.source(jsonString, XContentType.JSON);
indexResponse = restClient.index(indexRequest, RequestOptions.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}finally {
restClient.close();
}
return indexResponse;
}
main函数
public static void main(String [] args) throws Exception{
String index = "robot";
String type ="t_user";
String id = UUID.randomUUID().toString();
/* String json = "{" +
"\"name\":\"kimchy\"," +
"\"age\":\"18\"," +
"\"birth\":\"36542869\"" +
"}"; */
Map<String, Object> json = new HashMap<>();
jsonMap.put("name", "李逍遥");
jsonMap.put("age", 24);
jsonMap.put("birth", "564822559865");
IndexResponse indexResponse = index(index, type, id, json);
// TODO: 2018/9/9
}
数据的格式远不止以上2中,可以自己看看indexRequest.source()的实现方法。