简体   繁体   中英

DynamoDB: is it possible to Query array of specific items with the same PK?

I want to get an array of specific items with the same Primary Key (pk) and different Sort Keys (sk) .

Let's suppose that the keys of these items look like this:

[
  { pk: 1, sk: 1 },
  { pk: 1, sk: 3 },
  { pk: 1, sk: 6 }
]

Batch Get request of these items looks like this:

{
  RequestItems: {
    'TABLE_NAME': {
      Keys: [
        { pk: 1, sk: 1 },
        { pk: 1, sk: 3 },
        { pk: 1, sk: 6 }
      ]
    }
  }
}

Is it possible to get them by Query or do I have to use Batch Get command?

No. Queries using a sort key can only get items within a range of values.

You can apply a filterExpression and use the IN keyword to limit items to a set of specific values.

This approach has downsides:

  1. Query can only read 1 MB of data at once. If the query range exceeds 1 MB, you might not read all the data you need.
  2. You will pay for each 4KB of data queried. If your items are very small, and you know you will not be filtering out most items queried, this could save you money. But it could also cost you more if these conditions are not met.
  3. Creating a filter expression string is more annoying than a batch get.

TL;DR You probably want BatchGetItem .

With a Query , you can define your sk with a condition expression that can return multiple items, as in pk = 1 AND sk <= 6 . Primary key schema are often chosen to take advantage of this pattern. In your case, though, it's doubtful a single sk expression will be able to exactly match your arbitrary specific items. As @RossWilliams points out, Query does give you the option to overfetch with a broad sk > 0 condition and then filter the results.

So the fallback is BatchGetItem , for which you specify arbitrary pairs of pk and sk values. You'll get back 1 item for each primary key pair found in the table.

Here's a summary:

Operation Primary Key conditions # Items Returned if Found
Query pk equals and sk =, >=, begins_with, etc one or many
GetItem pk equals and sk equals one
BatchGetItem List of [pk equals and sk equals] one per List entry

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM