首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >ES使用json字符串索引文档时报错

ES使用json字符串索引文档时报错

作者头像
heasy3
发布于 2020-08-02 15:53:09
发布于 2020-08-02 15:53:09
1.7K0
举报

ES使用json字符串索引文档时报错 The number of object passed must be even but was [1]

在索引新文档时,如果只给request指定source为一个json字符串 会报错 因为他调用的是这个方法

代码语言:javascript
复制
public IndexRequest source(Object... source) {
	return this.source(Requests.INDEX_CONTENT_TYPE, source);
}

public IndexRequest source(XContentType xContentType, Object... source) {
	if (source.length % 2 != 0) {
		throw new IllegalArgumentException("The number of object passed must be even but was [" + source.length + "]");
	} else if (source.length == 2 && source[0] instanceof BytesReference && source[1] instanceof Boolean) {
		throw new IllegalArgumentException("you are using the removed method for source with bytes and unsafe flag, the unsafe flag was removed, please just use source(BytesReference)");
	} else {
		try {
			XContentBuilder builder = XContentFactory.contentBuilder(xContentType);
			builder.startObject();

			for(int i = 0; i < source.length; ++i) {
				builder.field(source[i++].toString(), source[i]);
			}

			builder.endObject();
			return this.source(builder);
		} catch (IOException var5) {
			throw new ElasticsearchGenerationException("Failed to generate", var5);
		}
	}
}

解决办法 将json字符串转为map 调用的就是另一个方法

Json转Map可以通过Gson 或者fastJson 我使用的是fastjson

fastjson的JSONObject 实现了Map接口 所以直接传入JSONObjcet即可

代码语言:javascript
复制
String j = "";//json字符串
IndexRequest request = new IndexRequest();
request.index("indexName");
request.type("doc");
JSONObject jsonObject = JSONObject.parseObject(j);
request.source(jsonObject);
restHighLevelClient.index(request,RequestOptions.DEFAULT);
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/03/11 ,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档