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

前端 未结 2 592
没有蜡笔的小新
没有蜡笔的小新 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 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;
    }
    

提交回复
热议问题