You need to enable JavaScript to run this app. 如何使用Serverless Framework为DynamoDB配置Post表的复合排序键
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Serverless Framework为DynamoDB配置Post表的复合排序键

项目背景

刚接触DynamoDB与Serverless架构,已了解复合排序键的设计思路,判断该类设计可以匹配自身业务的查询需求,但暂时不清楚具体落地实现方式。
当前需要存储的核心实体为Post,对应表的字段结构如下:

post_id <string> | user_id <string> | tags <string[]> | public <boolean> | 其他Post数据属性...

可选的属性设计规则:仅对标记为公开的Post设置public属性,非公开Post无需配置该字段。
预想的复合排序键格式参考为sort key: tag#public。

核心查询需求
  • 获取所有标记为公开的Post
  • 按标签维度筛选匹配的Post
  • 按用户维度查询其名下所有Post(包含公开、非公开两种状态)
  • 根据Post ID获取单条Post的完整信息
现有表配置

当前基于Serverless Framework编写的DynamoDB表CloudFormation配置如下:

PostsDynamoDBTable:
  Type: 'AWS::DynamoDB::Table'
  Properties:
    AttributeDefinitions:
      - AttributeName: postId
        AttributeType: S
      - AttributeName: userId
        AttributeType: S
      - AttributeName: createdAt
        AttributeType: S
    KeySchema:
      - AttributeName: postId
        KeyType: HASH
      - AttributeName: userId
        KeyType: RANGE
    BillingMode: PAY_PER_REQUEST
    TableName: ${self:provider.environment.POSTS_TABLE}
    GlobalSecondaryIndexes:
      - IndexName: ${self:provider.environment.USER_ID_INDEX}
        KeySchema:
          - AttributeName: userId
            KeyType: HASH
          - AttributeName: public
            KeyType: RANGE
        Projection:
          ProjectionType: ALL
待解决问题

如何基于Serverless Framework定义符合需求的复合排序键,让表结构完整覆盖上述所有查询场景?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 03:24:05