33

It appears that dynamodb's query method must include the partition key as part of the filter. How can a query be performed if you do not know the partition key?

For example, you have a User table with the attribute userid set as the partition key. Now we want to look up a user by their phone number. Is it possible to perform the query without the partition key? Using the scan method, this goal can be achieved, but at the expense of pulling every item from the table before the filter is applied, as far as I know.

KJ Price
  • 5,774
  • 3
  • 21
  • 34

1 Answers1

31

You'll need to set up a global secondary index (GSI), using your phoneNumber column as the index hash key.

You can create a GSI by calling UpdateTable.

Once you create the index, you'll be able to call Query with your IndexName, to pull user records based on the phone number.

Unsigned
  • 9,640
  • 4
  • 43
  • 72
  • 1
    Ah, I must have overlooked that. Perfect! – KJ Price Apr 12 '17 at 13:37
  • What if I want to query based on multiple attributes, and the set of those attributes may vary per request (for example one time I can query based on 2 attributes, next time on 5, next time on 1, and so on)? Does your suggestion work in this scenario also? – Jose Quijada Dec 10 '21 at 22:54
  • 1
    @JoseQuijada Querying on arbitrary combinations of keys is not something DynamoDB supports. If you have a few fixed multi-key queries you need to perform, you should likely create compound attributes: https://aws.amazon.com/blogs/database/querying-on-multiple-attributes-in-amazon-dynamodb/ – Unsigned Jul 27 '22 at 21:34