0
点赞
收藏
分享

微信扫一扫

2、Elasticsearch创建和获取Index


阅读文本大概需要3分钟。

《简单的ECharts数据可视化,30分钟学会》点赞结束,Leo加下我的微信。

2、Elasticsearch创建和获取Index_payment

上篇使用讲解了创建Document的的两种方式,这篇讲解剩下的两种方式。

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 字符串,这样反序列化就非常简单。


2、Elasticsearch创建和获取Index_微软_02


举报

相关推荐

0 条评论