使用Boto在带有LSI的dynamoDB中创建表

Mar*_*ark 2 python boto amazon-dynamodb

我知道如何使用boto创建表,但是在创建还包含LSI的表时找不到任何在线帮助。我搜索了boto文档和AWS文档。如果您有一个有关如何创建这样一个表的简单示例,那么我可以从那里开始。

谢谢

小智 5

在我的研究中遇到您的问题时发现了同样的事情。不知道您是否已找到答案,但我想我会将我的发现发布给其他可能需要知道这一点的人。

在我的情况下,我需要能够查询并基于两个不同的排序键(“日期”和“ post_id”)返回要创建的表(称为“帖子”)和本地二级索引(LSI)的结果,想要创建一个名为“ PostsByDate”的文件。

这是我下面的解决方案。它使用Python,但是我敢肯定,您可以根据自己选择的语言弄清楚如何处理它。

from __future__ import print_function # Python 2/3 compatibility
import boto3

dynamodb = boto3.resource('dynamodb', endpoint_url="http://localhost:8000", region_name="us-west-2")


table = dynamodb.create_table(
    TableName='Posts',
    KeySchema=[
        {
            'AttributeName': 'user_id',
            'KeyType': 'HASH'  #Partition key
        },
        {
            'AttributeName': 'post_id',
            'KeyType': 'RANGE'  #Sort key
        },
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'user_id',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'post_id',
            'AttributeType': 'N'
        },
        {
            'AttributeName': 'date',
            'AttributeType': 'N'
        },

    ],
    LocalSecondaryIndexes=[
        {
            'IndexName': 'PostsByDate',
            'KeySchema': [
                {
                    'AttributeName': 'user_id',
                    'KeyType': 'HASH'  #Partition key
                },
                {
                    'AttributeName': 'date',
                    'KeyType': 'RANGE'  #Sort key
                },
            ],
            'Projection': {
                'ProjectionType': 'ALL'
            }
        }
    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 10,
        'WriteCapacityUnits': 10,
        }
)

print("Table status:", table.table_status)
Run Code Online (Sandbox Code Playgroud)