'Update Attribute In A DynamoDB Row With Ruby, AWS SDK
So I'm trying to update an attribute in a DynamoDB row using Ruby. What I need to do is to a "query" for one row. Then, I need to update an attribute in that row. I've picked through the documentation quite a bit, but I'm not having any luck.
Does anyone have a good way to do this? Thanks in advance for any help!
Solution 1:[1]
You can query a table thusly: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Query.html
# Queries for movies that were released in the specified year.
#
# @param year [Integer] The year to query.
# @return [Array] The list of movies that were released in the specified year.
def query_movies(year)
response = @table.query(
key_condition_expression: "#yr = :year",
expression_attribute_names: {"#yr" => "year"},
expression_attribute_values: {":year" => year})
rescue Aws::Errors::ServiceError => e
puts("Couldn't query for movies released in #{year}. Here's why:")
puts("\t#{e.code}: #{e.message}")
raise
else
response.items
end
And to update an item: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/example_dynamodb_UpdateItem_section.html
# Updates rating and plot data for a movie in the table.
#
# @param title [String] The title of the movie to update.
# @param year [Int] The release year of the movie to update.
# @param rating [Float] The updated rating to give the movie.
# @param plot [String] The updated plot summary to give the movie.
# @return [Hash] The fields that were updated, with their new values.
def update_movie(title:, year:, rating:, plot:)
response = @table.update_item(
key: {"year" => year, "title" => title},
update_expression: "set info.rating=:r, info.plot=:p",
expression_attribute_values: { ":r" => rating, ":p" => plot },
return_values: "UPDATED_NEW")
rescue Aws::Errors::ServiceError => e
puts("Couldn't update movie #{title} in table #{@table.name}. Here's why:")
puts("\t#{e.code}: #{e.message}")
raise
else
response.attributes
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | NM Pennypacker |
