使用java代码将对象转为JSON并且调用elastic search保存数据:
IndexRequest indexRequest = new IndexRequest(Constant.INDEX);
indexRequest.source(XContentType.JSON, JSON.toJSONString(model));
报错:
Exception:The number of object passed must be even but was [1]
错误原因:
这个方法有多个重载,以下是其中两个:
public IndexRequest source(String source, XContentType xContentType)
public IndexRequest source(XContentType xContentType, Object... source)
第一个重载是将JSON字符串传入,第二个参数是XContentType。
第二个重载是第一个参数是XContentType,再将对象的属性以键值对的形式传入
例如:
BulkRequest request = new BulkRequest();
request.add(new IndexRequest("posts", "doc", "1")
.source(XContentType.JSON,"field", "foo"));
所以说归根结底就是参数写反了。。。改成
IndexRequest indexRequest = new IndexRequest(Constant.INDEX);
indexRequest.source(JSON.toJSONString(model), XContentType.JSON,);
就可以了
注意:一定是JSON.toJSONString,而不是JSON.toJSON
不然就会变成另外一个重载方法
public IndexRequest source(Object... source)