You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot集成Apache Solr:嵌套对象返回异常解决方法

解决Solr嵌套对象返回toString字符串的问题

原因分析

你的Address类未被标记为Solr可识别的嵌套实体,同时自动生成的managed schema中缺少address字段的嵌套结构配置,导致Solr在索引时直接调用Address对象的toString()方法存储内容,查询自然返回该字符串形式。

解决方案

1. 标记Address类为Solr嵌套实体

给Address类添加@Nested(Spring Data Solr 4.x及以上版本支持)或@SolrDocument注解,并为其字段添加@Indexed注解,让Solr识别这是嵌套对象:

@NoArgsConstructor
@Data
@Nested
public class Address {
    @Indexed
    private String addressLine;
    @Indexed
    private String zipcode;
    @Indexed
    private String state; // 建议改为小写开头,符合Java命名规范,避免序列化冲突
    @Indexed
    private String country;
}

2. 调整Employee类中address字段的注解

明确指定address字段的类型为nested,让Spring Data Solr正确映射嵌套结构:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@SolrDocument(collection = "Employee")
public class Employee {
    @Indexed
    private String name;
    @Indexed
    @Id
    private String id;
    @Indexed(name = "address", type = "nested")
    private List<Address> address;
}

3. 更新Solr的Managed Schema

自动生成的schema没有嵌套字段定义,需手动添加以下配置(可通过Solr Admin UI或API修改):

<field name="address" type="nested" indexed="true" stored="true"/>
<field name="address_addressLine" type="string" indexed="true" stored="true"/>
<field name="address_zipcode" type="string" indexed="true" stored="true"/>
<field name="address_state" type="string" indexed="true" stored="true"/>
<field name="address_country" type="string" indexed="true" stored="true"/>

字段命名采用父字段名_子字段名的格式,Solr会自动关联嵌套对象的属性。

4. 重新索引数据

删除现有索引后,通过SolrCrudRepository重新插入数据,确保新的嵌套结构被正确存储。

完成上述步骤后,查询返回的address字段将呈现正常的对象结构:

{
  "name": "employee1",
  "id": "1",
  "address": [
    {
      "addressLine": "xyz street",
      "zipcode": "12345",
      "state": "AP",
      "country": "India"
    }
  ]
}

内容的提问来源于stack exchange,提问作者siva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:07:15