0

I have created a table TEST which has 4 columns:

column1 : Range key

column2: Sort key

column3: GSI

column4: normal attribute

Now I want to update value of column4 based on GSI value. I tried with the following code but it works only when I pass both the range and sort key. In my usecase at the time of update I would have only the value of GSI not the range/sort key.

Map<String, AttributeValue> key = new HashMap<>();
key.put(“column1”, new AttributeValue().withS(column1Value));
key.put(“column2”, new AttributeValue().withS(column2Value));
Map<String, AttributeValue> attributeValues = new HashMap<>();

attributeValues.put(“column4”, new AttributeValue().withS(column4Value));
attributeValues.put(“column3”, new AttributeValue().withS(column3Value));

UpdateItemRequest updateItemRequest = new UpdateItemRequest()
                .withTableName(emailsTableName)
                .withKey(key)
                .withUpdateExpression(“set column4 = :column4”)
                .withConditionExpression(“column3 = :column3”)
                .withExpressionAttributeValues(attributeValues);
UpdateItemResult updateItemResult = dynamoDBClient.updateItem(updateItemRequest);

Is this possible to update column of Dynamo DB based on GSI only?

priyadhingra19
  • 333
  • 4
  • 15
  • Is there a connection between the column3 value and an actual Global Secondary index on the table? Why are you storing GSI? – jarmod Feb 04 '20 at 18:14
  • @jarmod Column name is not GSI . Column name is column4 only and we have created GSI over this column. – priyadhingra19 Feb 04 '20 at 18:15
  • 1
    To update an item you need its primary key. If you have a secondary index that will help you locate the item of interest then you can do that, retrieve the primary key, then perform an update. – jarmod Feb 04 '20 at 18:19
  • @jarmod So you are saying GSI is only used for locating . we cannot perform updated based on them? – priyadhingra19 Feb 04 '20 at 18:26
  • 1
    To issue an update, you need a primary key. That will be available if you used a GSI query, because the base table's primary key attributes are always projected into an index. – jarmod Feb 04 '20 at 18:37
  • Alright @jarmod I got it. Thanks for this update. – priyadhingra19 Feb 04 '20 at 18:38
  • You're welcome. DynamoDB forces you to think a little differently about databases. – jarmod Feb 04 '20 at 18:41

1 Answers1

4

GSIs are for querying data, so to do this you'd need to first query the data with the GSI, and then use the results from that to know what record(s) to update, using the keys in the response. Keep in ming that with a GSI it is potentially records, plural. There is no guarantee of uniqueness.

Jason Wadsworth
  • 8,059
  • 19
  • 32