繁体   English   中英

如何查询 dynamoDB 字典中的特定值?

[英]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'},

我想做的事情:

  1. 查询时间戳 - 在 2018 年之后只有字典
  2. 查询消息 - 仅包含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",
    },
)

这个例子告诉你:

  1. FilterExpression参数指定查询只应返回时间戳属性大于“2018-01-01 00:00:00”的项目。 (由于您的错误,我们将timestamp关键字更改为ts 。)

  2. KeyConditionExpression参数指定查询只应返回消息属性等于“AAA”事件属性等于“A”的项目。

  3. ExpressionAttributeValues参数定义将在KeyConditionExpressionFilterExpression参数中使用的值。

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM