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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章