首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DynamoDB:如果putItem中不存在键,我该如何做putItem?

DynamoDB:如果putItem中不存在键,我该如何做putItem?
EN

Stack Overflow用户
提问于 2016-05-04 13:13:57
回答 1查看 5.2K关注 0票数 3

我现在使用的是亚马逊AWS DynamoDB。在未来,我想把项目放在我的表中,但是仅仅是如果一个键相同的项目不存在,这样我就不会覆盖现有的值。你知道我怎么做到的吗?我的代码:

代码语言:javascript
复制
from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

dynamodb = boto3.resource('dynamodb', region_name='eu-central-1')

table = dynamodb.Table('Movies')

title = "The Big New Movie"
year = 2015

response = table.put_item(
    Item={
        'year': year,
        'title': title,
        'info': {
             'plot':"Nothing happens at all.",
             'rating': decimal.Decimal(0)
        }
    },
 )

我听说过ConditionExpression。但我不知道怎么把这个加上去。不是这样的:

代码语言:javascript
复制
response = table.put_item(
    Item={
        'year': year,
        'title': title,
        'info': {
             'plot':"Nothing happens at all.",
             'rating': decimal.Decimal(0)
        }
    },
     ConditionExpression = "attribute_not_exists",
 )

因为这样我就会得到以下错误:

代码语言:javascript
复制
Traceback (most recent call last):
  File "/Users/iTom/ownCloud/Documents/Workspace/PyCharm/DynamoDBTest/MoviesItemOps1.py", line 32, in <module>
ConditionExpression = "attribute_not_exists",
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/boto3/resources/factory.py", line 518, in do_action
response = action(self, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/boto3/resources/action.py", line 83, in __call__
response = getattr(parent.meta.client, operation_name)(**params)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/botocore/client.py", line 252, in _api_call
return self._make_api_call(operation_name, kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/botocore/client.py", line 542, in _make_api_call
raise ClientError(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the PutItem operation: Invalid ConditionExpression: Syntax error; token: "<EOF>", near: "attribute_not_exists"
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-04 13:27:29

必须在条件表达式中指定一个属性,如下所示:

代码语言:javascript
复制
ConditionExpression = "attribute_not_exists(title)"
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37028898

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档