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:
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.