DynamoDB CLI命令行工具 #

一、CLI概述 #

1.1 基本语法 #

bash
aws dynamodb <command> [options]

# 常用命令
aws dynamodb create-table      # 创建表
aws dynamodb delete-table      # 删除表
aws dynamodb describe-table    # 查看表信息
aws dynamodb list-tables       # 列出所有表
aws dynamodb put-item          # 写入数据
aws dynamodb get-item          # 获取数据
aws dynamodb update-item       # 更新数据
aws dynamodb delete-item       # 删除数据
aws dynamodb query             # 查询数据
aws dynamodb scan              # 扫描数据

1.2 输出格式 #

bash
# JSON格式(默认)
aws dynamodb list-tables --output json

# 表格格式
aws dynamodb list-tables --output table

# 文本格式
aws dynamodb list-tables --output text

二、表管理命令 #

2.1 创建表 #

简单主键表:

bash
aws dynamodb create-table \
  --table-name Users \
  --attribute-definitions \
    AttributeName=UserId,AttributeType=S \
  --key-schema \
    AttributeName=UserId,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST

复合主键表:

bash
aws dynamodb create-table \
  --table-name Orders \
  --attribute-definitions \
    AttributeName=UserId,AttributeType=S \
    AttributeName=OrderId,AttributeType=S \
  --key-schema \
    AttributeName=UserId,KeyType=HASH \
    AttributeName=OrderId,KeyType=RANGE \
  --billing-mode PAY_PER_REQUEST

带GSI的表:

bash
aws dynamodb create-table \
  --table-name Products \
  --attribute-definitions \
    AttributeName=ProductId,AttributeType=S \
    AttributeName=CategoryId,AttributeType=S \
    AttributeName=ProductName,AttributeType=S \
  --key-schema \
    AttributeName=ProductId,KeyType=HASH \
  --global-secondary-indexes \
    '[
      {
        "IndexName": "CategoryIndex",
        "KeySchema": [
          {"AttributeName": "CategoryId", "KeyType": "HASH"}
        ],
        "Projection": {"ProjectionType": "ALL"},
        "ProvisionedThroughput": {
          "ReadCapacityUnits": 5,
          "WriteCapacityUnits": 5
        }
      }
    ]' \
  --billing-mode PAY_PER_REQUEST

预置容量表:

bash
aws dynamodb create-table \
  --table-name Logs \
  --attribute-definitions \
    AttributeName=LogId,AttributeType=S \
  --key-schema \
    AttributeName=LogId,KeyType=HASH \
  --provisioned-throughput \
    ReadCapacityUnits=5,WriteCapacityUnits=5

2.2 查看表信息 #

bash
# 查看表详情
aws dynamodb describe-table \
  --table-name Users

# 查看表状态
aws dynamodb describe-table \
  --table-name Users \
  --query 'Table.TableStatus'

# 查看表ARN
aws dynamodb describe-table \
  --table-name Users \
  --query 'Table.TableArn' \
  --output text

2.3 列出表 #

bash
# 列出所有表
aws dynamodb list-tables

# 列出指定数量的表
aws dynamodb list-tables \
  --max-items 10

# 分页列出
aws dynamodb list-tables \
  --starting-token <token>

2.4 更新表 #

bash
# 更新容量
aws dynamodb update-table \
  --table-name Users \
  --provisioned-throughput \
    ReadCapacityUnits=10,WriteCapacityUnits=10

# 启用TTL
aws dynamodb update-time-to-live \
  --table-name Sessions \
  --time-to-live-specification \
    Enabled=true,AttributeName=ExpirationTime

# 添加GSI
aws dynamodb update-table \
  --table-name Users \
  --attribute-definitions \
    AttributeName=Email,AttributeType=S \
  --global-secondary-index-updates \
    '[
      {
        "Create": {
          "IndexName": "EmailIndex",
          "KeySchema": [{"AttributeName": "Email", "KeyType": "HASH"}],
          "Projection": {"ProjectionType": "ALL"}
        }
      }
    ]'

2.5 删除表 #

bash
# 删除表
aws dynamodb delete-table \
  --table-name Users

# 确认删除
aws dynamodb describe-table \
  --table-name Users 2>/dev/null || echo "Table deleted"

三、数据操作命令 #

3.1 写入数据(PutItem) #

基本写入:

bash
aws dynamodb put-item \
  --table-name Users \
  --item '{
    "UserId": {"S": "user123"},
    "Name": {"S": "John Doe"},
    "Email": {"S": "john@example.com"},
    "Age": {"N": "30"},
    "IsActive": {"BOOL": true}
  }'

使用JSON文件:

bash
# 创建item.json
cat > item.json << 'EOF'
{
  "UserId": {"S": "user456"},
  "Name": {"S": "Jane Doe"},
  "Email": {"S": "jane@example.com"},
  "Age": {"N": "25"},
  "Tags": {"SS": ["premium", "verified"]}
}
EOF

# 写入数据
aws dynamodb put-item \
  --table-name Users \
  --item file://item.json

条件写入:

bash
# 仅当项目不存在时写入
aws dynamodb put-item \
  --table-name Users \
  --item '{
    "UserId": {"S": "user123"},
    "Name": {"S": "John Doe"}
  }' \
  --condition-expression 'attribute_not_exists(UserId)'

3.2 获取数据(GetItem) #

基本获取:

bash
aws dynamodb get-item \
  --table-name Users \
  --key '{"UserId": {"S": "user123"}}'

指定属性:

bash
aws dynamodb get-item \
  --table-name Users \
  --key '{"UserId": {"S": "user123"}}' \
  --projection-expression 'Name, Email'

强一致性读取:

bash
aws dynamodb get-item \
  --table-name Users \
  --key '{"UserId": {"S": "user123"}}' \
  --consistent-read

3.3 更新数据(UpdateItem) #

基本更新:

bash
aws dynamodb update-item \
  --table-name Users \
  --key '{"UserId": {"S": "user123"}}' \
  --update-expression 'SET Age = :age, #n = :name' \
  --expression-attribute-names '{"#n": "Name"}' \
  --expression-attribute-values \
    '{":age": {"N": "31"}, ":name": {"S": "John Smith"}}'

原子计数器:

bash
aws dynamodb update-item \
  --table-name Counters \
  --key '{"CounterId": {"S": "visits"}}' \
  --update-expression 'SET #v = #v + :inc' \
  --expression-attribute-names '{"#v": "Value"}' \
  --expression-attribute-values '{":inc": {"N": "1"}}' \
  --return-values UPDATED_NEW

条件更新:

bash
aws dynamodb update-item \
  --table-name Users \
  --key '{"UserId": {"S": "user123"}}' \
  --update-expression 'SET Age = :age' \
  --condition-expression 'Age < :max_age' \
  --expression-attribute-values \
    '{":age": {"N": "35"}, ":max_age": {"N": "100"}}'

添加到集合:

bash
aws dynamodb update-item \
  --table-name Users \
  --key '{"UserId": {"S": "user123"}}' \
  --update-expression 'ADD Tags :tag' \
  --expression-attribute-values \
    '{":tag": {"SS": ["new_tag"]}}'

删除属性:

bash
aws dynamodb update-item \
  --table-name Users \
  --key '{"UserId": {"S": "user123"}}' \
  --update-expression 'REMOVE TempField'

3.4 删除数据(DeleteItem) #

基本删除:

bash
aws dynamodb delete-item \
  --table-name Users \
  --key '{"UserId": {"S": "user123"}}'

条件删除:

bash
aws dynamodb delete-item \
  --table-name Users \
  --key '{"UserId": {"S": "user123"}}' \
  --condition-expression 'IsActive = :active' \
  --expression-attribute-values \
    '{":active": {"BOOL": false}}'

返回删除的项目:

bash
aws dynamodb delete-item \
  --table-name Users \
  --key '{"UserId": {"S": "user123"}}' \
  --return-values ALL_OLD

四、批量操作命令 #

4.1 批量写入(BatchWriteItem) #

bash
aws dynamodb batch-write-item \
  --request-items '{
    "Users": [
      {
        "PutRequest": {
          "Item": {
            "UserId": {"S": "user1"},
            "Name": {"S": "User One"}
          }
        }
      },
      {
        "PutRequest": {
          "Item": {
            "UserId": {"S": "user2"},
            "Name": {"S": "User Two"}
          }
        }
      }
    ]
  }'

使用JSON文件:

bash
cat > batch-write.json << 'EOF'
{
  "RequestItems": {
    "Users": [
      {
        "PutRequest": {
          "Item": {
            "UserId": {"S": "user1"},
            "Name": {"S": "User One"}
          }
        }
      },
      {
        "DeleteRequest": {
          "Key": {
            "UserId": {"S": "old_user"}
          }
        }
      }
    ]
  }
}
EOF

aws dynamodb batch-write-item \
  --request-items file://batch-write.json

4.2 批量获取(BatchGetItem) #

bash
aws dynamodb batch-get-item \
  --request-items '{
    "Users": {
      "Keys": [
        {"UserId": {"S": "user1"}},
        {"UserId": {"S": "user2"}}
      ],
      "ProjectionExpression": "UserId, Name, Email"
    }
  }'

五、查询命令 #

5.1 Query查询 #

基本查询:

bash
aws dynamodb query \
  --table-name Orders \
  --key-condition-expression 'UserId = :uid' \
  --expression-attribute-values \
    '{":uid": {"S": "user123"}}'

带排序键条件:

bash
aws dynamodb query \
  --table-name Orders \
  --key-condition-expression 'UserId = :uid AND OrderId BETWEEN :start AND :end' \
  --expression-attribute-values \
    '{
      ":uid": {"S": "user123"},
      ":start": {"S": "ORDER#2024-01-01"},
      ":end": {"S": "ORDER#2024-12-31"}
    }'

使用索引查询:

bash
aws dynamodb query \
  --table-name Users \
  --index-name EmailIndex \
  --key-condition-expression 'Email = :email' \
  --expression-attribute-values \
    '{":email": {"S": "john@example.com"}}'

排序和限制:

bash
aws dynamodb query \
  --table-name Orders \
  --key-condition-expression 'UserId = :uid' \
  --expression-attribute-values \
    '{":uid": {"S": "user123"}}' \
  --scan-index-forward false \
  --limit 10

过滤表达式:

bash
aws dynamodb query \
  --table-name Orders \
  --key-condition-expression 'UserId = :uid' \
  --filter-expression 'TotalAmount > :min_amount' \
  --expression-attribute-values \
    '{
      ":uid": {"S": "user123"},
      ":min_amount": {"N": "100"}
    }'

5.2 Scan扫描 #

基本扫描:

bash
aws dynamodb scan \
  --table-name Users

带过滤条件:

bash
aws dynamodb scan \
  --table-name Users \
  --filter-expression 'Age > :min_age' \
  --expression-attribute-values \
    '{":min_age": {"N": "25"}}'

指定属性:

bash
aws dynamodb scan \
  --table-name Users \
  --projection-expression 'UserId, Name, Email'

分页扫描:

bash
# 第一页
aws dynamodb scan \
  --table-name Users \
  --limit 10

# 下一页(使用返回的LastEvaluatedKey)
aws dynamodb scan \
  --table-name Users \
  --limit 10 \
  --exclusive-start-key \
    '{"UserId": {"S": "user_last_id"}}'

并行扫描:

bash
# 总分段数
TOTAL_SEGMENTS=4

# 启动多个并行扫描(每个终端一个分段)
aws dynamodb scan \
  --table-name Users \
  --total-segments 4 \
  --segment 0 &

aws dynamodb scan \
  --table-name Users \
  --total-segments 4 \
  --segment 1 &

# ... 其他分段

六、表达式语法 #

6.1 更新表达式 #

bash
# SET - 设置或更新属性
--update-expression 'SET #n = :name, Age = :age'

# ADD - 添加到集合或数字增量
--update-expression 'ADD Tags :tag, ViewCount :inc'

# DELETE - 从集合中删除元素
--update-expression 'DELETE Tags :tag'

# REMOVE - 删除属性
--update-expression 'REMOVE TempField, OldField'

6.2 条件表达式 #

bash
# 属性存在检查
--condition-expression 'attribute_exists(Email)'

# 属性不存在检查
--condition-expression 'attribute_not_exists(UserId)'

# 比较运算
--condition-expression 'Age > :min_age AND Status = :status'

# 集合包含
--condition-expression 'contains(Tags, :tag)'

# 大小检查
--condition-expression 'size(Description) < :max_size'

6.3 表达式属性名 #

bash
# 使用保留字作为属性名
--expression-attribute-names '{"#n": "Name", "#s": "Status"}'
--update-expression 'SET #n = :name, #s = :status'

6.4 表达式属性值 #

bash
# 定义值占位符
--expression-attribute-values '{
  ":name": {"S": "John"},
  ":age": {"N": "30"},
  ":active": {"BOOL": true},
  ":tags": {"SS": ["tag1", "tag2"]}
}'

七、实用技巧 #

7.1 使用–query过滤输出 #

bash
# 只获取属性值
aws dynamodb get-item \
  --table-name Users \
  --key '{"UserId": {"S": "user123"}}' \
  --query 'Item.Name.S'

# 获取多个属性
aws dynamodb get-item \
  --table-name Users \
  --key '{"UserId": {"S": "user123"}}' \
  --query 'Item.{Name: Name.S, Email: Email.S}'

7.2 使用本地DynamoDB #

bash
# 连接本地DynamoDB
aws dynamodb list-tables \
  --endpoint-url http://localhost:8000

# 所有命令都可以添加endpoint参数
aws dynamodb create-table \
  --table-name TestTable \
  --attribute-definitions AttributeName=Id,AttributeType=S \
  --key-schema AttributeName=Id,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST \
  --endpoint-url http://localhost:8000

7.3 调试和详细输出 #

bash
# 显示详细调试信息
aws dynamodb query \
  --table-name Users \
  --key-condition-expression 'UserId = :uid' \
  --expression-attribute-values '{":uid": {"S": "user123"}}' \
  --debug

# 显示请求ID
aws dynamodb get-item \
  --table-name Users \
  --key '{"UserId": {"S": "user123"}}' \
  --query 'ResponseMetadata.RequestId'

7.4 使用配置文件 #

bash
# 使用指定配置
aws dynamodb list-tables \
  --profile dev \
  --region us-west-2

# 使用环境变量
export AWS_PROFILE=dev
export AWS_DEFAULT_REGION=us-west-2
aws dynamodb list-tables

八、常用命令速查 #

8.1 表操作 #

操作 命令
创建表 aws dynamodb create-table
删除表 aws dynamodb delete-table
查看表 aws dynamodb describe-table
列出表 aws dynamodb list-tables
更新表 aws dynamodb update-table

8.2 数据操作 #

操作 命令
写入 aws dynamodb put-item
获取 aws dynamodb get-item
更新 aws dynamodb update-item
删除 aws dynamodb delete-item
批量写入 aws dynamodb batch-write-item
批量获取 aws dynamodb batch-get-item

8.3 查询操作 #

操作 命令
查询 aws dynamodb query
扫描 aws dynamodb scan

九、总结 #

CLI使用要点:

类别 要点
表管理 create-table, delete-table, describe-table
数据操作 put-item, get-item, update-item, delete-item
批量操作 batch-write-item, batch-get-item
查询操作 query, scan
表达式 更新表达式、条件表达式、过滤表达式

下一步,让我们学习DynamoDB的数据类型!

最后更新:2026-03-27