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);
发布了39 篇原创文章 · 获赞 11 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/he37176427/article/details/104797862