[英]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.