ElasticSearch中json字符串的拼接

本文详细介绍了在Elasticsearch (ES) 中如何通过JSON格式进行数据存储和操作,包括新建索引时指定字段及属性,以及向ES中插入数据的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值