Skip to content

Instantly share code, notes, and snippets.

@mmyoji
Last active May 15, 2024 05:33
Show Gist options
  • Save mmyoji/eafd3a6b7b5ef3569d1f6d4978fa0c64 to your computer and use it in GitHub Desktop.
Save mmyoji/eafd3a6b7b5ef3569d1f6d4978fa0c64 to your computer and use it in GitHub Desktop.
DynamoDB Scan paging w/ Ruby SDK

Resources

http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html

http://docs.aws.amazon.com/sdkforruby/api/Aws/DynamoDB/Client.html

Summary

DynamoDB's scan operation fetches only 1MB at one time and it adds LastEvaluatedKey (LEK) in the response if it has a next page.

I didn't know the spec and troubled a bit in my project.

Solution

items = []

scan_opts = {
  table_name: "MyDynamoTable",
  scan_filter: {
    "PublishedAt" => {
      attribute_value_list: ["2017-08-25"],
      comparison_operator: "GE",
    },
    "Host" => {
      attribute_value_list: ["example.com"],
      comparison_operator: "EQ",
    }
  },
  consistent_read: true,
}

scan_output = client.scan scan_opts

loop do
  items << scan_output.items

  break unless (lek = scan_output.last_evaluated_key)

  scan_output = client.scan scan_opts.merge(exclusive_start_key: lek)
end

items.flatten
@mmyoji
Copy link
Author

mmyoji commented May 6, 2020

@miry I updated original one. Thanks 👍

@namdv-1375
Copy link

@mmyoji If you follow the method of passing in the page and the number of items on a page, how should you write it? @@ Thanksss

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