【java操作Elasticsearch之增加记录】
Elasticsearch之添加记录操作,核心代码如下:
public static void main(String[] args) throws Exception {
String url ="http://192.168.1.111:9200/";
//一、添加单个记录
UserVO user = new UserVO("庞涓", "地址不详", 1.3, true,39, "2012-09-08");
System.out.println(JSONObject.fromObject(user));
//IndexName/type/id
doPost(url+"index_users3/userinfo/002",JSONObject.fromObject(user) );
//二、批量添加记录
/**
The REST API endpoint is /_bulk, and it expects the following JSON structure:
action_and_meta_data\n
optional_source\n
action_and_meta_data\n
optional_source\n
....
action_and_meta_data\n
optional_source\n
NOTE: the final line of data must end with a newline character \n.
*/
UserVO user1 = new UserVO("庞涓01", "地址不详", 1.3, true,39, "2012-09-08");
UserVO user2 = new UserVO("庞涓02", "地址不详", 1.3, true,39, "2012-09-08");
List<UserVO> list = new ArrayList<UserVO>();
list.add(user1);
list.add(user2);
doPost(url+"index_users3/userinfo/_bulk",list);
}
----------------------------------------------------------------------------------------------------
VO类
public class UserVO {
private String name;
private String address;
private double sal;
private boolean sex;
private int age ;
private String createDate;
}
公共请求方法
/**
* post请求
*
* @param url
* @param json
* @return
*/
public static JSONObject doPost(String url, JSONObject json) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(json.toString(),HTTP.UTF_8);
s.setContentEncoding("UTF-8");
s.setContentType("application/json;charset=UTF-8");
// 发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(entity,"UTF-8");// 返回json格式:
System.out.println(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
private static void doPost(String url, List<UserVO> list) {
StringBuffer sb = new StringBuffer();
for (UserVO userVO : list) {
sb.append("{\"create\" :{ \"_index\" : \"test\"" ).append("}}\n");
sb.append(JSONObject.fromObject(userVO)).append("\n");
}
System.out.println(sb);
doPost(url, sb.toString());
}