如何通过PocoDynamo创建全局二级索引而非AWS控制台?
如何通过PocoDynamo创建全局二级索引
要确保全局二级索引能被PocoDynamo正确创建,需按以下步骤操作:
1. 正确定义全局二级索引类
索引类必须继承自GlobalIndex<T>(T为主表类型,此处为Order),且类中声明的属性需与主表Order中的字段名称、类型完全匹配,以此指定索引的分区键和可选的排序键:
public class OrderCostGlobalIndex : GlobalIndex<Order> { // 索引分区键:对应Order表中的Cost字段 public decimal Cost { get; set; } // 可选:索引排序键,对应Order表中的OrderDate字段 public DateTime OrderDate { get; set; } }
2. 注册表时关联全局索引
仅注册主表不会自动创建索引,需在注册时显式关联索引:
方式一:通过CreateTableRequest指定
db.RegisterTable<Order>(new CreateTableRequest { GlobalSecondaryIndexes = new List<GlobalSecondaryIndex> { db.CreateGlobalSecondaryIndex<OrderCostGlobalIndex>() } }); db.InitSchema();
方式二:使用扩展方法简化
db.RegisterTable<Order>() .WithGlobalIndex<OrderCostGlobalIndex>(); db.InitSchema();
关键注意事项
- 仅当表未创建时,
InitSchema()才会生成带索引的表;若表已存在,PocoDynamo不会修改现有表结构,需先删除旧表后重新初始化。 - 可通过
db.DescribeTable<Order>()查询表结构,验证索引是否创建成功。
内容的提问来源于stack exchange,提问作者M. Akar
相关产品推荐
相关产品推荐

