DynamoDb存储的对象重复

2024-09-29 21:40:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写这个函数是为了看看一个对象是否已经存储在dynamo中。在

def doesIDExist(key):
    print(key)
    info=key.split("/")
    #set properties
    try:
        id=info[1]+info[2]
        results = dynamoConn.query(swfTable,id)
        if results is not None:
            return True
    except:
        return False
    return False

我在给任何数据库写信之前先打个支票:

^{pr2}$

但我仍然有重复出现。我错过了什么?在

编辑:

我没有收到错误: 我得到一个table对象,我的函数返回True。但什么都没有添加?在

第二次编辑: 我在下面解决了这个问题。


Tags: 对象key函数infoidfalsetrue编辑
2条回答

我解决了这个问题。问题是返回的对象不是表。我需要得到一张桌子和一张桌子,然后数一数。在

def doesIDExist(key):
    print(key)
    info=key.split("/")
    #set properties
    #try:
    id=info[1]+info[2]
    results = dynamoConn.query(swfTable,id).table.item_count
    print results
    if results > 0:
        return True
    #except:
    #    return False
    return False

为了避免重复,最好的方法是使用“Conditional Put”,这样,如果带有键的项已经存在,新项将不会覆盖现有项。在

请参见python的doc

Create a new item or replace an old item with a new item (including all attributes). If an item already exists in the specified table with the same primary key, the new item will completely replace the old item. You can perform a conditional put by specifying an expected rule.

some examples

您只需要将“expected”作为字典传递到put_item调用。在

expected={
    'yourHashKeyName': {'Exists': False}
}

上面的代码不起作用的原因是dynamoConn.查询将始终返回TableGenerator对象,即使不存在具有该哈希键的项。在

query函数接受一个Count parameter,它返回“查询操作的项目总数,即使该操作没有与指定的筛选器匹配的项目。”

^{pr2}$

然后检查

results.count > 0

如果这个id已经存在,结果.计数应该是1。否则应为0。在

另一个选择是使用get_item API。您的表没有范围键,可以使用“id”作为hashkey调用get_项。在

相关问题 更多 >

    热门问题