我在 dynamodb 中有一张表。它存储帐户统计信息。帐户统计数据可能每天会更新多次。所以表记录可能如下所示:
+------------+--------------+-------+-------+
| account_id | record_id | views | stars |
+------------+--------------+-------+-------+
| 3 | 2019/03/16/1 | 29 | 3 |
+------------+--------------+-------+-------+
| 2 | 2019/03/16/2 | 130 | 21 |
+------------+--------------+-------+-------+
| 1 | 2019/03/16/3 | 12 | 2 |
+------------+--------------+-------+-------+
| 2 | 2019/03/16/1 | 57 | 12 |
+------------+--------------+-------+-------+
| 1 | 2019/03/16/2 | 8 | 2 |
+------------+--------------+-------+-------+
| 1 | 2019/03/16/1 | 3 | 0 |
+------------+--------------+-------+-------+
account_id
是主分区键。record_id
是主排序键
我如何才能只获取每个的最新记录account_id
是?所以从上面的例子我期望得到:
+------------+--------------+-------+-------+
| account_id | record_id | views | stars |
+------------+--------------+-------+-------+
| 3 | 2019/03/16/1 | 29 | 3 |
+------------+--------------+-------+-------+
| 2 | 2019/03/16/2 | 130 | 21 |
+------------+--------------+-------+-------+
| 1 | 2019/03/16/3 | 12 | 2 |
+------------+--------------+-------+-------+
该数据可方便地用于报告目的。
如果您知道以下列表,则可以非常有效地完成此操作account_id
是您存储在表中的。
在这种情况下,您需要做的就是逐一查询主键,并使用以下命令对值进行排序ScanIndexForward=False
并将结果限制为 1 项,使用Limit=1
.
这是Python中的代码
import boto3
import json
client = boto3.client('dynamodb')
account_ids = ['1', '2', '3']
results = []
for aid in account_ids:
result = client.query(
TableName='test-table',
KeyConditionExpression="#aid = :aid",
ExpressionAttributeNames={
'#aid': 'account_id'
},
ExpressionAttributeValues={
':aid': {
'N': aid
}
},
ScanIndexForward=False,
Limit=1,
)
results.append(result['Items'])
print(json.dumps(results, indent=2))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)