1、使用Jackson生成Index
public static IndexResponse getIndexResponseWithJackson(TransportClientclient) {
IndexResponse response = null;
try{
//instance a json mapper
ObjectMappermapper = new ObjectMapper();
UserModel um = new UserModel();
um.setId(111);
um.setMessage("huangjinjin");
um.setSendTime(new Date());
//generate json
byte[] json = mapper.writeValueAsBytes(um);
response= client.prepareIndex
("twitter2", "tweet2", "2")
.setSource(json, XContentType.JSON)
.get();
}catch (Exception e){
e.printStackTrace();
}
returnresponse;
}
2、 使用XContentBuilder生成Index
public static IndexResponse getIndexResponseWithXContentBuilder(TransportClient client) {
IndexResponse response = null;
try{
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject() // 数组的话是 startArray(String
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elasticsearch")
.endObject(); // 数组的话是 endArray()
// String json = builder.string();// 甚至可以通过 builder 来代替 Jackson 转换
response = client.prepareIndex("fendo", "fendodata")
.setSource(builder).get();
}catch (Exception e){
e.printStackTrace();
}
return response;
}
使用Jackson需要时需要在pom.xml文件中引入
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
掌握了如何使用Index API创建Document后,下面讲解如何使用Get Index获取Document。
public static GetResponse getGetResponse(TransportClient client,
String index,
String type,
String id) {
GetResponse response = client.prepareGet(index, type, id).get();
return response;
}
测试获取Index
GetResponse getResponse = IndexGet.getGetResponse(client,"twitter2", "tweet2", "2");
String str = getResponse.getSourceAsString();
System.out.println(str);
使用GetResponse的getSourceAsString() 可以返回 JSON 字符串,这样反序列化就非常简单。
☆
往期精彩
☆
01 漫谈发版哪些事,好课程推荐
02 Linux的常用最危险的命令
03 精讲Spring Boot—入门+进阶+实例
04 优秀的Java程序员必须了解的GC哪些
05 互联网支付系统整体架构详解