Spring Data DynamoDB:同分区键多GSI的指定查询方法
解决指定查询GSI-2的问题
因为countryCode同时是两个GSI的分区键,框架默认会选择第一个注册的索引(GSI-1),要指定查询GSI-2,有两种可靠的实现方式:
方法1:使用@Query注解显式指定索引
直接在Repository方法上用@Query注解,通过index参数指定要使用的GSI名称,这是最直接的方式:
@EnableScan public interface PlayerRepository extends CrudRepository<PlayerDynamoEntity, String> { // 查询GSI-1的方法 Page<PlayerDynamoEntity> findByCountryCode(String countryCode, Pageable pageable); // 查询GSI-2的方法,显式指定索引 @Query(index = "GSI-2") Page<PlayerDynamoEntity> findByCountryCodeOrderByScore2Desc(String countryCode, Pageable pageable); }
注意方法名里的排序字段要和实体类中的score2属性名一致(实体类中score2对应表字段Score-2),框架会自动映射到GSI-2的排序键。
方法2:为不同索引单独声明分区键(可选)
如果想让方法名逻辑更清晰,可在实体类中为每个GSI单独声明分区键注解(属性值复用同一个countryCode):
@DynamoDBTable(tableName = "Player") public class PlayerDynamoEntity { @DynamoDBHashKey(attributeName = "PlayerId") private String player; @DynamoDBAttribute(attributeName = "CountryCode") private String countryCode; // GSI-1专属分区键映射 @DynamoDBIndexHashKey(attributeName = "CountryCode", globalSecondaryIndexName = "GSI-1") public String getCountryCodeForGSI1() { return countryCode; } @DynamoDBIndexRangeKey(attributeName = "Score-1", globalSecondaryIndexName = "GSI-1") private String score1; // GSI-2专属分区键映射 @DynamoDBIndexHashKey(attributeName = "CountryCode", globalSecondaryIndexName = "GSI-2") public String getCountryCodeForGSI2() { return countryCode; } @DynamoDBIndexRangeKey(attributeName = "Score-2", globalSecondaryIndexName = "GSI-2") private String score2; // 需添加对应setter方法,或用Lombok简化 }
随后在Repository中通过对应方法名查询:
@EnableScan public interface PlayerRepository extends CrudRepository<PlayerDynamoEntity, String> { Page<PlayerDynamoEntity> findByCountryCodeForGSI1(String countryCode, Pageable pageable); Page<PlayerDynamoEntity> findByCountryCodeForGSI2OrderByScore2Desc(String countryCode, Pageable pageable); }
两种方法中,方法1更简洁高效,无需修改实体类结构,直接通过注解指定索引即可满足需求。
内容的提问来源于stack exchange,提问作者Ahmet Orhan
相关产品推荐
相关产品推荐

