ElasticSearch中json字符串的拼接

在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();

}