dynamodb如何只按排序键查询?

sco*_*ott 7 amazon-web-services amazon-dynamodb boto3

我写了一些python代码,我想通过sort键查询dynamoDB数据.我记得我可以使用后续代码成功:

 table.query(KeyConditionExpression=Key('event_status').eq(event_status))
Run Code Online (Sandbox Code Playgroud)

我的表结构列

primary key:event_id
sort key: event_status
Run Code Online (Sandbox Code Playgroud)

Ben*_*son 12

如果您不想扫描(也许您不应该),则需要为此创建一个GSI(全局二级索引)event_status ,并将其设置为 GSIPK。

所以你的表配置将是:

 table = dynamodb.create_table(
        TableName="your_table",
        KeySchema=[
            {"AttributeName": "event_id", "KeyType": "HASH"},  # Partition key
            {"AttributeName": "event_status", "KeyType": "RANGE"},  # Sort key
        ],
        AttributeDefinitions=[
            {"AttributeName": "event_id, "AttributeType": "S"},
            {"AttributeName": "event_status", "AttributeType": "S"},
            {"AttributeName": "gsi_event_status", "AttributeType": "S"},
            {"AttributeName": "gsi_event_id", "AttributeType": "S"},
        ],
        GlobalSecondaryIndexes=[
            {
                "IndexName": "gsiIndex",
                "KeySchema": [
                    {"AttributeName": "gsi_event_status", "KeyType": "HASH"},
                    {"AttributeName": "gsi_event_id", "KeyType": "RANGE"},
                ],
                "Projection": {"ProjectionType": "ALL"},
            },
        ],
        BillingMode="PAY_PER_REQUEST",
    )
Run Code Online (Sandbox Code Playgroud)

请注意,GSI 可能很昂贵,如果不需要所有属性,您可能需要更改ProjectionType 。

现在可以通过pk查询:

table.query(KeyConditionExpression=Key('event_id').eq(event_id))
Run Code Online (Sandbox Code Playgroud)

或通过设置为您的 sk 的 GSI PK:

lookup.query(
        IndexName="gsiIndex",
        KeyConditionExpression=Key("gsi_event_status").eq(event_status),
    )
Run Code Online (Sandbox Code Playgroud)


man*_*xxl 7

您必须为排序键创建一个二级索引,以便单独对其进行查询。

  • 这是不正确的,您需要创建一个GSI,您不能单独查询排序键。LSI是附加LSI (3认同)

not*_*est 6

如果您想在不使用哈希键属性值的情况下从DynamoDB获取数据,则应使用扫描API。

例:-

fe = Attr('event_status').eq("new");

response = table.scan(
        FilterExpression=fe        
    )

for i in response['Items']:

print(json.dumps(i, cls=DecimalEncoder))

while 'LastEvaluatedKey' in response:
    response = table.scan(        
        FilterExpression=fe,        
        ExclusiveStartKey=response['LastEvaluatedKey']
        )

    for i in response['Items']:
        print(json.dumps(i, cls=DecimalEncoder))
Run Code Online (Sandbox Code Playgroud)

  • 请注意,扫描与查询不同。您将遍历所有值,因此它的效率比查询低得多。如果您确实需要有效地查询``event_status'',则应考虑为该字段创建一个GSI。 (7认同)