首页 > 解决方案 > 无法为持久文档时看到的类型类的未知值写入 xcontent

问题描述

Getting the following error while updating phone

lang.IllegalArgumentException: cannot write xcontent for unknown value of type class com.company.Phone]
http://localhost/users/vfu1i3cB1FVgFWdzuLfj/update
{
 "nu": "9823456344",
 "cc": "91"
}

转换器看起来像这样

@WritingConverter
public static class ToMap implements Converter<Phone, Map<String, Object>> {

    @Override
    public Map<String, Object> convert(Phone source) {

        LinkedHashMap<String, Object> target = new LinkedHashMap<>(8);
        target.put(NAME, source.name);
        target.put(NUMBER, source.number);
        target.put(COUNTRY_CODE, source.countryCode);

        return target;
    }   
}   

    @ReadingConverter
    public static class ToPhone implements Converter<Map<String, Object>, Phone> {
    
        @Override
        public Phone convert(Map<String, Object> source) {
            Phone phone = new Phone();
            phone.setName((String)source.get(NAME));
            phone.setNumber((String)source.get(NUMBER));
            phone.setCountryCode((String)source.get(COUNTRY_CODE));
    
            return phone;
        }   
    }  

标签: elasticsearchspring-data-elasticsearch

解决方案


除了设置转换器之外,您还需要注册转换器实现:

@Bean
public ElasticsearchCustomConversions elasticsearchCustomConversions() {
    return new ElasticsearchCustomConversions(
        Arrays.asList(new ToPhone(), new ToMap())
    );
}

在此处查看详细信息:https ://docs.spring.io/spring-data/elasticsearch/docs/current-SNAPSHOT/reference/html/#elasticsearch.mapping.meta-model.conversions


推荐阅读