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

时间:2022-07-22
本文章向大家介绍ES使用json字符串索引文档时报错,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

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

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即可

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