2015-10-18 51 views
2

我试图使用低级API将字典保存到DynamoDB表字段。我无法弄清楚如何用对象映射器来做到这一点。在AWS iOS文档中没有这样的例子,我试图研究和实现相同主题的Java/.NET示例。如何使用Swift将字典(映射对象)保存到DynamoDB

我想仅使用updateExpression更新行中的字典字段。

我偶然发现了这个问题,同时寻找答案,但它并没有帮助:Best way to make Amazon AWS DynamoDB queries using Swift?

这里的更新dynamoDB表功能:

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 
    } 
} 
+0

你可以看看[对象映射器测试(https://github.com/aws/aws-sdk-ios/blob/master/AWSDynamoDBTests/AWSDynamoDBObjectMapperTests .m#L550)的一些示例代码。 –

回答

2

我解决了这个问题,问题是AWS需要字典键总是以字符串的形式,任何其他类型是不允许的。

工作溶液片断

... 
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" 
相关问题