Skip to content

Instantly share code, notes, and snippets.

@jtsaito
Last active December 7, 2015 21:23
Show Gist options
  • Save jtsaito/c2b1ac8e93f0fd24f04e to your computer and use it in GitHub Desktop.
Save jtsaito/c2b1ac8e93f0fd24f04e to your computer and use it in GitHub Desktop.
Put and query Dynamo DB with Ruby's AWS SDK v2

Prerequisites

  1. Created a dynamo db table. We use "travis-ci-example-with-filter" with a composite primary key (string partition key "id", integer range key "created_at").
  2. Made aws-sdk gem available.

Prepare AWS Dynamo DB client and database name

require 'aws-sdk'

Aws.config.update({
  region: 'eu-west-1',
  credentials: Aws::Credentials.new(ENV['ARTIFACTS_KEY'], ENV['ARTIFACTS_SECRET'])
})

dynamo_client= Aws::DynamoDB::Client.new(region: 'eu-west-1')

table_name = "travis-ci-example-with-filter"

Put a few items

Repeat the following put_item a few times.

result = dynamo_client.put_item(
  table_name: table_name,
  item: {
    id: "standard",
    created_at: Time.now.to_i,
    whatever: "Die Aufklaerung ist die Ausfuehrung des Menschen aus seiner selbstverschuldeten Unmuendigkeit."
  }
)

Query for the latest entry

The latest entry is the item with maximal range key "created_at".

resp = dynamo_client.query({
  table_name: table_name,
  select: "ALL_ATTRIBUTES",
  consistent_read: true,
  scan_index_forward: false,
  limit: 1,
  key_conditions: {
    "id" => {
      attribute_value_list: ["standard"],
      comparison_operator: "EQ"
    }
  }
})

Outputting this with puts resp.data gives following output.

=> #<struct Aws::DynamoDB::Types::QueryOutput
 items=
  [{"created_at"=>#<BigDecimal:7f91c0cd6fc8,'0.1449519921E10',18(27)>,
    "whatever"=>"Die Aufklaerung ist die Ausfuehrung des Menschen aus seiner selbstverschuldeten Unmuendigkeit.",
    "id"=>"standard"}],
 count=1,
 scanned_count=1,
 last_evaluated_key={"created_at"=>#<BigDecimal:7f91c0cd6a00,'0.1449519921E10',18(27)>, "id"=>"standard"},
 consumed_capacity=nil>

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment