Elasticsearch创建和获取Index
  TEZNKK3IfmPf 2023年11月14日 17 0

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 互联网支付系统整体架构详解

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2023年11月14日   35   0   0 elasticsearchDocker
  TEZNKK3IfmPf   2023年11月14日   36   0   0 elasticsearch
TEZNKK3IfmPf