How to put a new key-value pair into a map in DynamoDB? (java)

前端 未结 2 579
没有蜡笔的小新
没有蜡笔的小新 2020-12-28 16:55

I have a DynamoDB attribute whose value is a map from a Number to a String. I am trying to put in a new key-value pair. From what I\'ve read, this seems to be possible, but

相关标签:
2条回答
  • 2020-12-28 17:07

    Visit http://www.tryyourskill.com/aws/insert-or-append-key-values-map-in-dynamodb-using-java may help you with the code snippet to add or append values in map column

    public boolean insertKeyValue(String tableName, String primaryKey, String 
        primaryKeyValue, String updateColumn, String newKey, String newValue) {
    
        //Configuration to connect to DynamoDB
        Table table = dynamoDB.getTable(tableName);
        boolean insertAppendStatus = false;
        try {
            //Updates when map is already exist in the table
            UpdateItemSpec updateItemSpec = new UpdateItemSpec()
                .withPrimaryKey(primaryKey, primaryKeyValue)
                .withReturnValues(ReturnValue.ALL_NEW)
                .withUpdateExpression("set #columnName." + newKey + " = :columnValue")
                .withNameMap(new NameMap().with("#columnName", updateColumn))
                .withValueMap(new ValueMap().with(":columnValue", newValue))
                .withConditionExpression("attribute_exists("+ updateColumn +")");
    
            table.updateItem(updateItemSpec);
            insertAppendStatus = true;
        //Add map column when it's not exist in the table
        } catch (ConditionalCheckFailedException e) {
            HashMap<String, String> map =  new HashMap<>();
            map.put(newKey, newValue);
            UpdateItemSpec updateItemSpec = new UpdateItemSpec()
                .withPrimaryKey(primaryKey,primaryKeyValue)
                .withReturnValues(ReturnValue.ALL_NEW)
                .withUpdateExpression("set #columnName = :m")
                .withNameMap(new NameMap().with("#columnName", updateColumn))
                .withValueMap(new ValueMap().withMap(":m", map));
    
            table.updateItem(updateItemSpec);
            insertAppendStatus = true;
        } catch(Exception e) {
            e.printStackTrace();
        }
        return insertAppendStatus;
    }
    
    0 讨论(0)
  • 2020-12-28 17:26

    With the following arguments to UpdateItem, you can condition adding a map entry at #number when map.#number does not exist in the map already:

    UpdateExpression = "SET map.#number = :string"
    ExpressionAttributeNames = { "#number" : "1" }
    ExpressionAttributeValues = { ":string" : "the string to store in the map at key value 1" }
    ConditionExpression = "attribute_not_exists(map.#number)"
    
    0 讨论(0)
提交回复
热议问题