[英]How to query over specific value in dictionary in dynamoDB?
我有一个存储在 dynamoDB 中的表,其示例字典如下:
{event': 'A',
'timestamp': '2017-10-15 16:20:47,009',
'message': 'AAA'},
{event': 'B',
'timestamp': '2018-10-15 16:20:47,009',
'message': 'BBB'},
{event': 'A',
'timestamp': '2019-10-15 16:20:47,009',
'message': 'BBB'},
{event': 'B',
'timestamp': '2020-10-15 16:20:47,009',
'message': 'AAA'},
我想做的事情:
message == AAA
的字典让我们专注于查询消息:
我使用以下代码加载表格:
import boto3
client = boto3.client("dynamodb", region_name="eu-central-1")
session = boto3.Session(profile_name="myprofile")
resource = session.resource("dynamodb", region_name="eu-central-1")
table = resource.Table("mytable")
我遇到的主要问题是,当我运行查询代码时:
response = table.query(
KeyConditionExpression="message = :message",
ExpressionAttributeValues={":message": "AAA"},
)
我收到以下错误:
ClientError: An error occurred (ValidationException) when calling the Query operation: Query condition missed key schema element: event
我阅读了有关此错误的一些信息,人们说我可以扫描表格(这在我的情况下是不可能的。因为我的整个表格很大)或使用二级索引(不幸的是我不明白它的意思)。 你能帮我解决这个问题吗?
编辑
回答后我试着做:
response = table.query(
KeyConditionExpression="message = :message",
FilterExpression="#ts >:timestamp",
ExpressionAttributeValues={":message": "AAA",
":timestamp": "2018-01-01 00:00:00"},
ExpressionAttributeNames={
"#ts": "timestamp"
}
)
但我收到错误: ClientError: An error occurred (ValidationException) when calling the Query operation: Query condition missed key schema element: event
如果不使用ExpressionAtrributeNames
,错误是相同的
要根据特定属性的值查询 DynamoDB 中的表,您需要在query
方法的KeyConditionExpression
参数中指定该属性。
KeyConditionExpression
参数定义表中的项目必须满足的条件才能由查询返回。
response = table.query(
KeyConditionExpression="message = :message",
ExpressionAttributeValues={":message": "AAA"},
)
在此示例中,查询只应返回message
属性等于"AAA"
的项目。
response = table.query(
KeyConditionExpression="event = :event and message = :message",
FilterExpression="#ts > :timestamp",
ExpressionAttributeValues={
":event": "A",
":message": "AAA",
":timestamp": "2018-01-01 00:00:00",
},
ExpressionAttributeNames={
"#ts": "timestamp",
},
)
这个例子告诉你:
FilterExpression
参数指定查询只应返回时间戳属性大于“2018-01-01 00:00:00”的项目。 (由于您的错误,我们将timestamp
关键字更改为ts
。)
KeyConditionExpression
参数指定查询只应返回消息属性等于“AAA”且事件属性等于“A”的项目。
ExpressionAttributeValues
参数定义将在KeyConditionExpression
和FilterExpression
参数中使用的值。
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.