Is it possible in DynamoDb to get all the items with a given Sort Key?

As primary key I have an id for a recipe and the sort key is the type of food (breakfast, meal, snack, etc).

Is there a way with scan or query to get all the items with a given sort key?

Upvotes: 5

Views: 9564

Answers (1)

Mike Dinescu
Mike Dinescu

Reputation: 55760

As others have pointed in the comments, you can't query a sort key in the sense that there is no operation that gives a list of items that have the same sort key.

In fact, the whole reason for a sort key is generally to order items in a particular partition.

Putting the two together, what you need is a way to partition the items by the food type and then query on that. Enter the Global Secondary Index (GSI).

With the help of a GSI you can index the data in your table in a way that the food type becomes the partition key, and some other attribute becomes the sort key. Then, getting all the items that match a particular food type becomes possible with a Query.

There are a few things to keep in mind:

  • a GSI is like another table: it consumes capacity that you will be charged for
  • a GSI is eventually consistent, meaning changes in the table could take a bit of time before being reflected in the GSI
  • if you end up creating a GSI where the choice of partition key results in very large partitions, it can lead to throttling (reduced throughput) if any one partition receives a lot of requests

Some more guidelines: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-indexes-general.html

But before you start creating GSIs, consider for a moment the schema of your table: your choice of partition key seems less than ideal. On the one hand, using the recipe id as the partition key is great because it probably results in very good spread of data but on the other hand, you have no ability to use queries on your table without creating GSIs.

Instead of recipe id as the partition key, consider creating a partition key composed of food type, and perhaps another attribute. This way, you can actually query on food type, or perhaps issue several queries to retrieve all items of a particular food type.

Upvotes: 10

Related Questions