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?
CodePudding user response:
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:
- 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.
- 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.
- Creating a filter expression string is more annoying than a batch get.
CodePudding user response:
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 |