【问题标题】:How to fetch the null value of a dynamodb table attribute using boto如何使用 boto 获取 dynamodb 表属性的空值
【发布时间】:2019-03-13 21:09:51
【问题描述】:

我正在处理一个类似这样的表。 表名:沙盒

Id               name                        type

 1                xyz                         
 2                xx                          
 3                xxx                         
 4                yyyy                        private

我面临的问题是。 1) 如果属性值type 为空,我将无法获取它。基本上,如果此值为空,我想设置一些东西。但是 dynamodb 扫描只是跳过将其放入 json 响应中。

下面给出的是我写的python脚本。

dynamodb_resource = session.resource('dynamodb')
table_sandboxes = dynamodb_resource.Table('sandboxes')
response_sandboxes = table_sandboxes.scan()
def _myfun(box_id)
    for i in response_sandboxes['Items']:
                if box_id == i['id']:
                        if i['type'] == 'private':
                                return 'true'
                        else:
                                return 'false'

        return 1


_myfun(2)

我得到的错误是。

KeyError: 'type'

所以, 1)有没有一种方法可以扫描并获取属性值,即使它为空? 2)如果扫描是正确的方法吗? 3)如果表格更大,我是否还必须考虑分页器并处理它?

我是新手,任何帮助将不胜感激。

【问题讨论】:

    标签: python amazon-dynamodb boto3


    【解决方案1】:

    DynamoDB 将 null 视为实际的 data type,类似于数字或字符串。在上面的示例中,ID 为 1、2 和 3 的项目中的type 属性不是null,它只是不存在。在项目 ID 4 中,它的数据类型是字符串。在 DynamoDB 中拥有具有各种属性(缺失或项目之间不同)的项目是可能的,因为它是无模式的。

    解决代码中的错误的最简单方法是测试项目中是否存在type

    return True if i.get('type') == 'private' else False
    

    您还可以将type 属性中的值存储为null 类型(此处的命名法令人困惑),但是您不能在该属性中存储值private。我想这不是你想要的。

    关于你的第二个问题,scan,正如你所怀疑的那样,不是最好的方法。 DynamoDB 中的数据建模本身就是一个主题。 DynamoDB docs 是开始了解它的好方法。如果您想通过 type 属性检索项目,您可以做的一件事是创建一个 GSI 来执行此操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 2018-10-09
      相关资源
      最近更新 更多