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)
如果您想在不使用哈希键属性值的情况下从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)
| 归档时间: |
|
| 查看次数: |
11489 次 |
| 最近记录: |