问题描述
如何将属性更新"到 DynamoDB 行.例如.SET address.state = "MA"
对于某些项目,当 address
尚不存在时?
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.
如果 address
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
和 :value
适当地映射到 address
、state
和 MA
.
with #address
, #state
, and :value
appropriately mapped to address
, state
, and MA
, respectively.
但如果 address
属性确实不 已经存在,则会报错:
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 = {}; 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 address = {};
失败,然后再试一次.
- 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
设置一个空映射,如果它不存在,第二个设置 state
:
You can do it with two round trips, the first conditionally sets an empty map for address
if it doesn't already exist, and the second sets the state
:
db.update({
UpdateExpression: 'SET #a = :value',
ConditionExpression: 'attribute_not_exists(#a)',
ExpressionAttributeValues: {
":value": {},
},
ExpressionAttributeNames: {
'#a': 'address'
}
}, ...);
然后:
db.update({
UpdateExpression: 'SET #a.#b = :v',
ExpressionAttributeNames: {
'#a': 'address',
'#b': 'state'
},
ExpressionAttributeValues: {
':v': 'whatever'
}
}, ...);
这篇关于当地图尚不存在时,如何设置 DynamoDB 地图属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2