在测试Springboot整合Elasticsearch时,想向index下放入doc数据,调用indexRequest.source(String…) 方法抛出The number of object passed must be even but was [1]解决过程。
一、首先翻译一下异常的信息,看看能否找出蛛丝马迹
原文:The number of object passed must be even but was [1]
译文:传递的对象数必须为偶数,但为[1]
。。。从翻译的角度来看莫非这个方法强制要求传入两个对象,就是一次要求你传入偶数个对象才让你保存?答案肯定是否定的,毕竟不可能有这么坑的API,所以决定从源码下手
二、点入source这个方法源码如下
public IndexRequest source(XContentType xContentType, Object... source) {
// 异常就是这里抛出的,source是个可变长度的参数,这里确实会做校验,判断参数是否传偶数个进来,但是这里看不出为什么有这样的限定,继续往下看
if (source.length % 2 != 0) {
throw new IllegalArgumentException("The number of object passed must be even but was [" + source.length + "]");
}
// 这里就是一个简单的判断,限定第一个参数和第二个参数的类型不能为啥啥啥没什么问题
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)");
}
try {
// 看文档的意思是一个json内容的构建器
XContentBuilder builder = XContentFactory.contentBuilder(xContentType);
// 字面意思就是开始构建对象
builder.startObject();
// 重点就在这里了
for (int i = 0; i < source.length; i++) {
// 这里需要拆分下,首先builder.field应该就是设置对象属性的一个API
// 假设现在i=0,获取第一个参数source[i++].toString(),之后这里i变成1了
// 之后,source[i]获取第二个参数,真相大白!!
builder.field(source[i++].toString(), source[i]);
}
// 结束构建对象
builder.endObject();
return source(builder);
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate", e);
}
}
通过看源码可以直到,直接调用indexRequest.source(String…) 传偶数个参数的原因是因为,传入的参数是两两成一组的,例如
第一个参数为:属性名称
第二个参数为:属性值
第三个参数为:属性名称
第四个参数为:属性值
第五个参数为:属性名称
。。。依次类推
所以需要加上参数是否为偶数的判断,若为奇数下面的for循环会抛出数组越界异常
三、正确的用法
①传入偶数个参数,以键值对的方式一 一匹配
indexRequest.source("username","李四","age",11);
②用提供的另一个api直接传json字符串
String string = JSON.toJSONString(new User().setUsername("张三").setAge(2l));
indexRequest.source(string, XContentType.JSON); // 放入数据json格式
四、解决