2

I’m trying to save a dictionary to my DynamoDB table field using low-level API. I couldn’t figure out how to do it with object mapper. There is no example for this in AWS iOS documentation and I’ve tried to research and implement Java / .NET examples of the same subject unsuccessfully.

I want to update only the dictionary field in the row using updateExpression.

I stumbled to this question while searching for answer, but it didn't help: Best way to make Amazon AWS DynamoDB queries using Swift?

Here’s the function to update 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
    }
}
1
  • You can take a look at the object mapper test for some sample code. Commented Oct 20, 2015 at 18:19

1 Answer 1

2

I solved it, the problem was that AWS requires dictionary keys to always be in the form of String, any other type is not allowed.

The working solution snippet:

...
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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.