Spring Data Elasticsearch标准仓库索引时是否需指定路由键?
背景信息
文档实体类
@Document(indexName = "example") @Setting(shards = 4) @Routing(value = "routingKey") public class ExampleEntity { @Id private String id; @Field(type = FieldType.Keyword) private String routingKey; @Field(type = FieldType.Keyword) private String otherField; // 省略其他代码 }
关联仓库
@Repository public interface ExampleRepository extends ElasticsearchRepository<ExampleEntity, String> {}
查询相关文档说明
Currently native queries must be used to query the data, so there is no support from standard repository methods. Custom Implementations for Spring Data Repositories can be used instead.
(翻译:目前必须使用原生查询来查询数据,因此标准仓库方法不提供支持,可改用Spring Data仓库的自定义实现。)
疑问
查询数据时需通过自定义仓库实现结合原生查询才能使用路由键,但文档未提及索引数据时的机制:使用标准仓库方法repository.save(document)或repository.saveAll(documentList)时,路由键是否会被默认使用,还是需要自定义机制?
Spring Data Elasticsearch的save和saveAll方法会自动利用你在实体类上通过@Routing注解指定的路由键,不需要额外自定义机制。
当你调用这些标准保存方法时,框架会读取@Routing(value = "routingKey")配置中指定的字段(也就是实体里的routingKey属性)的值,将其作为路由参数传递给Elasticsearch,确保文档被路由到正确的分片上。
这一点和查询场景不同:查询时标准仓库方法确实不支持传递路由键,必须通过自定义实现或原生查询来指定,但保存操作是框架自动处理了路由键的传递逻辑的。
内容的提问来源于stack exchange,提问作者Marius Manastireanu

