2、Elasticsearch创建和获取Index

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

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

上篇使用讲解了创建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 字符串,这样反序列化就非常简单。

往期精彩

01 漫谈发版哪些事,好课程推荐

02 Linux的常用最危险的命令

03 精讲Spring&nbsp;Boot—入门+进阶+实例

04 优秀的Java程序员必须了解的GC哪些

05 互联网支付系统整体架构详解

关注我

每天进步一点点

很干!在看吗?☟

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BUG弄潮儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值