您的位置:首页 > Web前端 > JavaScript

ElasticSearch中json字符串的拼接

2015-06-17 11:10 731 查看
在ES中,所有的查询结果信息,包括doc,都是以json的形式返回的。在es中,提供了拼接json的特定接口,主要分为两种形式。

1、在新建索引的时候,需要指定索引的字段以及字段的属性,这个时候可以借助于json,具体代码如下:
XContentBuilder mapping = jsonBuilder().startObject()
.startObject("properties")
.startObject("ID").field("type", "string").field("store", "yes")
.endObject()
.startObject("title").field("type", "string").field("store", "yes")
.endObject()
.startObject("description").field("type", "string").field("index", "analyzed")
.endObject()
.startObject("number").field("type", "integer")
.endObject()
.startObject("price").field("type", "double")
.endObject()
.startObject("inDate").field("type", "string")
.endObject()
.startObject("outDate").field("type", "string")
.endObject()
.startObject("type").field("type", "boolean")
.endObject().endObject().endObject();

client.prepareIndex("product","wxt").setSource(mapping).execute().actionGet();
client.close();

2、是向es中插入数据时,也是需要将要插入的数据以json的格式送至es中,具体代码如下:

public static XContentBuilder getXContentBuilder(Product product) throws IOException {
return XContentFactory.jsonBuilder()
.startObject()
.field("ID", product.getID())
.field("title", product.getTitle())
.field("description", product.getDescription())
.field("number", product.getNumber())
.field("price", product.getPrice())
.field("inDate", product.getInDate())
.field("outDate", product.getOutDate())
.field("type", product.isType())
.endObject();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: