1
votes

I have a list in a DynamoDB table and would like to move items to different positions in the same list, is there a way to do this in a single update?

At the moment, I'm looking at having to read the list, modify it, then write it back again, but would prefer doing it all in a single update, is there a way to do this?

Edit to add example

So here's some noddy data that shows what I'd like to do:

If the data started like this:

Item: { COLUMN: [ "Element_0", "Element_1", "Element_2", "Element_3" ] }

Then I'd give it from and to indices and it would move the element. So for example if I gave it a from index of 0 and to index of 2 the data should end up like this:

Item: { COLUMN: [ "Element_1", "Element_2", "Element_0", "Element_3" ] }

2
I assume you mean a list within a single item. Can you give example data? What does the item in the table look like? What information do you have when doing the update? What is the desired final state? - Jason Wadsworth
Yes that's right, all the information to locate the list is available and it's just one list within a single item - Nathan Adams

2 Answers

1
votes

You can do this with an Update Expression, but it's a little tricky, since you don't have the data.

Basically, you have to create a dynamic update statement that sets every value you want to move. Something like this works:

aws dynamodb update-item --table-name test --key '{"pk":{"S":"1"}}' --update-expression "SET #list[1] = #list[2], #list[2] = #list[1]" --region us-west-2 --profile jw-test --expression-attribute-names '{"#list": "list"}'

I created a table with a key of pk, with a value of 1. The list before the update was like this:

[
'one',
'two',
'three',
'four'
]

After the update it looks like this:

[
'one',
'three',
'two',
'four'
]
-1
votes

Default answer if this isn't possible in a single update.

Read out the list, modify it, then write it back. It's not elegant, but it works and isn't that ugly either.

It's not atomic though so any answer that can do it in a single update will get the check mark.