当地图尚不存在时如何设置DynamoDB地图属性值 [英] How to set a DynamoDB Map property value, when the map doesn't exist yet
问题描述
如何将属性追加到DynamoDB行。例如。 SET address.state = MA
对于某些项目,当地址
还不存在时?
How do you "upsert" a property to a DynamoDB row. E.g. SET address.state = "MA"
for some item, when address
does not yet exist?
我觉得我遇到了鸡与蛋的问题,因为DynamoDB不允许您提前定义草率的模式。
I feel like I'm having a chicken-and-egg problem because DynamoDB doesn't let you define a sloppy schema in advance.
如果该项目上已经存在地址
DID,且类型为 M
(对于地图),则互联网会告诉我我可以发出像这样的UpdateExpression:
If address
DID already exist on that item, of type M
(for Map), the internet tells me I could issue an UpdateExpression like:
SET#address。#state =:value
带有 #address
, #state
和:值
适当地映射到地址
,州
和 MA
。
with #address
, #state
, and :value
appropriately mapped to address
, state
, and MA
, respectively.
但是,如果地址
属性不是已经存在,这将产生错误:
But if the address
property does not already exist, this gives an error:
'''
ValidationException:更新表达式中提供的文档路径对于更新
'是无效的
''' ValidationException: The document path provided in the update expression is invalid for update '''
所以..看来我要么需要:
So.. it appears I either need to:
- 图出一种更新
address.state
的方法(例如,SET地址= {};在单个命令中设置address.state ='MA'
)
- Figure out a way to "upsert"
address.state
(e.g.,SET address = {}; SET address.state = 'MA'
in a single command)
或
- 在我尝试的三个(!!!)往返中,
SET地址= {};
失败,然后再试一次。
- Issue three (!!!) roundtrips in which I try it,
SET address = {};
on failure, and then try it again.
如果是后者....如何设置空白地图?!?
If the latter.... how do I set a blank map?!?
哎呀。我喜欢Dynamo,但除非我缺少明显的东西,否则这有点疯狂。
Ugh.. I like Dynamo, but unless I'm missing something obvious this is a bit crazy..
推荐答案
如果父文档不存在,则无法设置嵌套属性。由于地址
不存在,因此无法在其中设置属性省
。如果在创建商品时将 address
设置为空地图,就可以实现自己的目标。然后,您可以使用以下参数对属性 address.province
尚不存在的条件进行更新。
You cannot set nested attributes if the parent document does not exist. Since address
does not exist you cannot set the attribute province
inside it. You can achieve your goal if you set address
to an empty map when you create the item. Then, you can use the following parameters to condition an update on an attribute address.province
not existing yet.
var params = {
TableName: 'Image',
Key: {
Id: 'dynamodb.png'
},
UpdateExpression: 'SET address.province = :ma',
ConditionExpression: 'attribute_not_exists(address.province)',
ExpressionAttributeValues: {
':ma': 'MA'
},
ReturnValues: 'ALL_NEW'
};
docClient.update(params, function(err, data) {
if (err) ppJson(err); // an error occurred
else ppJson(data); // successful response
});
顺便说一句,由于州是保留字,我不得不用省替换州。
By the way, I had to replace state with province as state is a reserved word.
这篇关于当地图尚不存在时如何设置DynamoDB地图属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!