概要:
目录:
一、生成JSON
创建索引的第一步是要把对象转换为JSON字符串.官网给出了四种创建JSON文档的方法:
1.1手写方式生成
1 String json = "{" +
2 "\"user\":\"kimchy\"," +
3 "\"postDate\":\"2013-01-30\"," +
4 "\"message\":\"trying out Elasticsearch\"" +
5 "}";
手写方式很简单,但是要注意日期格式:Date Formate
1.2使用集合
集合是key:value数据类型,可以代表json结构.
1 Map json = new HashMap();2 json.put("user","kimchy");3 json.put("postDate","2013-01-30");4 json.put("message","trying out Elasticsearch");
1.3使用JACKSON序列化
ElasticSearch已经使用了jackson,可以直接使用它把javabean转为json.
1 //instance a json mapper
2 ObjectMapper mapper = new ObjectMapper(); //create once, reuse3
4 //generate json
5 byte[] json = mapper.writeValueAsBytes(yourbeaninstance);
1.4使用ElasticSearch 帮助类
1 import static org.elasticsearch.common.xcontent.XContentFactory.*;2
3 XContentBuilder builder =jsonBuilder()4 .startObject()5 .field("user", "kimchy")6 .field("postDate", newDate())7 .field("message", "trying out Elasticsearch")8 .endObject()9
10 String json = builder.string();
二、创建索引
下面的例子把json文档写入所以,索引库名为twitter、类型为tweet,id为1:
1 import static org.elasticsearch.common