ElasticSearch 6.x 学习笔记:26.Java API之文档添加

1、官网参考

https://www.elastic.co/guide/en/elasticsearch/client/java-api/6.1/java-docs-index.html

Generate JSON document

There are several different ways of generating a JSON document:

  • Manually (aka do it yourself) using native byte[] or as a String (把JSON格式文档手动转换为 byte[]或String)
  • Using a Map that will be automatically converted to its JSON equivalent (使用Map,代表一个JSON机构)
  • Using a third party library to serialize your beans such as Jackson (使用Jackson 等第三方库把JavaBean转换为JSON)
  • Using built-in helpers XContentFactory.jsonBuilder() (使用内置帮助类XContentFactory的.jsonBuilder()方法)

2、实例演示

package cn.hadron;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import cn.hadron.es.*;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
public class PutDocDemo {
    public static void main(String[] args) throws Exception{
        TransportClient client=ESUtil.getClient();
        String json = "{" +
                "\"id\":\"1\"," +
                "\"title\":\"Java设计模式之装饰模式\"," +
                "\"content\":\"在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。\"," +
                "\"postdate\":\"2018-02-03 14:38:00\"," +
                "\"url\":\"csdn.net/79239072\"" +
                "}";
        System.out.println(json);
        IndexResponse response =client.prepareIndex("index1", "blog","1")
                .setSource(json, XContentType.JSON)
                .get();
        System.out.println(response.status());

        XContentBuilder doc1 = jsonBuilder()
                    .startObject()
                    .field("id","2")
                    .field("title","Java设计模式之单例模式")
                    .field("content","枚举单例模式可以防反射攻击。")
                    .field("postdate","2018-02-03 19:27:00")
                    .field("url","csdn.net/79247746")
                    .endObject();
        System.out.println(doc1.toString());
        response = client.prepareIndex("index1", "blog", "2")
                .setSource(doc1)
                .get();
        System.out.println(response.status());
    }

}

ElasticSearch 6.x 学习笔记:26.Java API之文档添加_第1张图片

3、Kibana验证

GET index1/blog/1
{
  "_index": "index1",
  "_type": "blog",
  "_id": "1",
  "_version": 1,
  "found": true,
  "_source": {
    "id": "1",
    "title": "Java设计模式之装饰模式",
    "content": "在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。",
    "postdate": "2018-02-03 14:38:00",
    "url": "csdn.net/79239072"
  }
}
GET index1/blog/2
{
  "_index": "index1",
  "_type": "blog",
  "_id": "2",
  "_version": 1,
  "found": true,
  "_source": {
    "id": "2",
    "title": "Java设计模式之单例模式",
    "content": "枚举单例模式可以防反射攻击。",
    "postdate": "2018-02-03 19:27:00",
    "url": "csdn.net/79247746"
  }
}

你可能感兴趣的:(Elasticsearch,6.x,学习笔记)