KJ Price
KJ Price

Reputation: 5964

Query on non-key attribute

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.

Upvotes: 37

Views: 29982

Answers (2)

tschumann
tschumann

Reputation: 3246

If you have a Global Secondary Index, the partition key of the index is the attribute name.

e.g.

      Properties:
        TableName: entries
        BillingMode: PAY_PER_REQUEST
        AttributeDefinitions:
          - AttributeName: name
            AttributeType: S
          - AttributeName: display-name
            AttributeType: S
        KeySchema:
          - AttributeName: name
            KeyType: HASH
        GlobalSecondaryIndexes:
          - IndexName: display-name-index
            KeySchema:
              - AttributeName: display-name
                KeyType: HASH
            Projection:
              ProjectionType: ALL

Then you can use the query function (this is using the PHP SDK but the parameter names should be the same in the other SDKs - https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-dynamodb-2012-08-10.html covers it well):

        $dynamoDB->query([
            'TableName' => 'entries',
            'IndexName' => 'display-name-index',
            'ExpressionAttributeNames' => [
                '#idx' => 'display-name'
            ],
            'ExpressionAttributeValues' => [
               ':arg' => [
                   'S' => $key,
               ],
            ],
            'KeyConditionExpression' => '#idx = :arg'
        ]);

Upvotes: 0

Unsigned
Unsigned

Reputation: 9916

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.

Upvotes: 36

Related Questions