我正在尝试使用低级 API 将字典保存到我的 DynamoDB 表字段。我不知道如何使用对象映射器来做到这一点。 AWS iOS 文档中没有这方面的示例,我尝试研究和实现同一主题的 Java/.NET 示例,但没有成功。
我只想使用 updateExpression 更新行中的字典字段。
我在寻找答案时偶然发现了这个问题,但没有帮助:Best way to make Amazon AWS DynamoDB queries using Swift?
这是更新 dynamoDB-table 的函数:
func saveMapToDatabase(hashKey:Int, rangeKey:Double, myDict:[Int:Double]){
let nsDict:NSDictionary = NSDictionary(dictionary: myDict)
var dictAsAwsValue = AWSDynamoDBAttributeValue();dictAsAwsValue.M = nsDict as [NSObject : AnyObject]
let updateInput:AWSDynamoDBUpdateItemInput = AWSDynamoDBUpdateItemInput()
let hashKeyValue:AWSDynamoDBAttributeValue = AWSDynamoDBAttributeValue();hashKeyValue.N = String(hashKey)
let rangeKeyValue:AWSDynamoDBAttributeValue = AWSDynamoDBAttributeValue(); rangeKeyValue.N = String(stringInterpolationSegment: rangeKey)
updateInput.tableName = "my_table_name"
updateInput.key = ["db_hash_key" :hashKeyValue, "db_range_key":rangeKeyValue]
//How I usually do low-level update:
//let valueUpdate:AWSDynamoDBAttributeValueUpdate = AWSDynamoDBAttributeValueUpdate()
//valueUpdate.value = dictAsAwsValue
//valueUpdate.action = AWSDynamoDBAttributeAction.Put
//updateInput.attributeUpdates = ["db_dictionary_field":valueUpdate]
//Using the recommended way: updateExpression
updateInput.expressionAttributeValues = ["dictionary_value":dictAsAwsValue]
updateInput.updateExpression = "SET db_dictionary_field = :dictionary_value"
self.dynamoDB.updateItem(updateInput).continueWithBlock{(task:BFTask!)->AnyObject! in
//do some debug stuff
println(updateInput.aws_properties())
println(task.description)
return nil
}
}
最佳答案
我解决了,问题是AWS要求字典键始终是String的形式,不允许任何其他类型。
工作解决方案片段:
...
updateInput.tableName = "my_table_name"
updateInput.key = ["db_hash_key" :hashKeyValue, "db_range_key":rangeKeyValue]
let dictionaryInRightFormat:NSDictionary = ["stringKey":dictAsAwsValue]
updateInput.expressionAttributeValues = updateInput.updateExpression = "SET db_dictionary_field = :stringKey"
关于ios - 如何使用 Swift 将字典( map 对象)保存到 DynamoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33201143/