yoges nsamy
yoges nsamy

Reputation: 1435

DynamoDB Query Input: How to retrieve all items where key value is not null

I have the following schema:

resources:
 Resources:
   ChatDynamoDbTable:
     Type: "AWS::DynamoDB::Table"
     DeletionPolicy: Retain
     Properties:
       TableName: "chats-admin-${opt:stage, self:provider.stage}"
       ProvisionedThroughput:
         ReadCapacityUnits: 1
         WriteCapacityUnits: 1
       AttributeDefinitions:
         - AttributeName: id
           AttributeType: S         
         - AttributeName: user_id
           AttributeType: S         
         - AttributeName: admin_type
           AttributeType: S         
       KeySchema:
         - AttributeName: id
           KeyType: HASH
       GlobalSecondaryIndexes:
       -
         IndexName: user_id-admin_type-index
         KeySchema:
           -
             AttributeName: user_id
             KeyType: HASH
           -
             AttributeName: admin_type
             KeyType: RANGE
         Projection:
           ProjectionType: ALL
         ProvisionedThroughput:
           ReadCapacityUnits: 1
           WriteCapacityUnits: 1

I need to fetch all items where the admin_type matches the key I supply.

I tried the following and it failed because I've not specified the value for user_id:

"error_message":"ValidationException: Query condition missed key schema element: user_id

input := &dynamodb.QueryInput{
        TableName:              aws.String(table),
        IndexName:              aws.String("user_id-admin_type-index"),
        KeyConditionExpression: aws.String("#admin_type = :admin_type"),
        ExpressionAttributeNames: map[string]*string{
            "#admin_type": aws.String("admin_type"),
        },
        ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
            ":admin_type": {
                S: aws.String(a.AdminType),
            },
        },
    }

How can I modify the above to fetch all items where admin_type matches my key? (basically all items matching admin_type without worrying about the value of user_id.)

Upvotes: 0

Views: 1559

Answers (1)

Seth Geoghegan
Seth Geoghegan

Reputation: 5747

The DynamoDB API offers two basic means of fetching data; query and scan.

The query operation requires you to specify the primary key. When you have a composite primary key (partition key + sort key), you can:

  • Specify only the partition key (you'll get back everything in the partition)
  • Specify both the partition key and sort key (you'll get back a single item)

There is no option with the query operation to specify only the sort key.

To fetch items by sort key only, you'll need to use the scan operation. Alternatively, you could create a secondary index with a primary key set to your sort key (in your case, the admin_type). This would allow you to fetch items by admin_type, regardless of the user_id.

Upvotes: 1

Related Questions