so-random-dude
so-random-dude

Reputation: 16465

How to get all the Sort keys for a given Partition key (HASH) efficiently?

I am new to DynamoDB and I am coming from an RDBMS background. Is there any way to get all the sortkey (RANGE) for a given Partition key (HASH). I am not interested in the data, just the sort keys. What is the efficient way to achieve this?

Upvotes: 2

Views: 3605

Answers (4)

Chris McLaughlin
Chris McLaughlin

Reputation: 340

You can use KeyConditionExpression as part of the DynamoDB QueryAPI.

Here is roughly how you could do it in python:

import boto3
from boto3.dynamodb.conditions import Key
from botocore.exceptions import ClientError

session = boto3.session.Session(region_name = 'us-east-1')
dynamodb = session.resource('dynamodb')

table_object = dynamodb.Table(table_name)

return_list = []

try:
    response = table_object.query(
        KeyConditionExpression = Key(partition_key_name).eq(partition_key_value),
        ProjectionExpression = sort_key_name
    )
except ClientError:
    return False

if 'Items' in response:
    for response_result in response['Items']:
        if sort_key_name in response_result:
            return_list.append(response_result.get(sort_key_name))
        
    return return_list
else:
    return False

Updated thanks to @Hernan for suggesting including ProjectionExpression

Upvotes: 1

Hernan C. Vazquez
Hernan C. Vazquez

Reputation: 166

You can improve the @Chris McLaughlin solution adding a ProjectionExpression attribute to the query. ProjectionExpression need to be a string that identifies one ("attribute_name") or more attributes ("attribute_name1,attribute_name2") to retrieve from the table.

response = table_object.query(
        KeyConditionExpression = Key(partition_key_name).eq(partition_key_value),
        ProjectionExpression = sort_key_name
    )

This will give you all the sort_keys in your table. It is not necessary to create an additional column to do this since the sort_key is already a column in the table.

Upvotes: 1

SIDDHARTH J MEHTA
SIDDHARTH J MEHTA

Reputation: 165

I'm assuming that HashKey & RangeKey are specified while creating DynamoDB Table. You can use DynamoDB's Query API and specify range key's column name in AttributesToGet field of this API request. Please use the pagination support provided in Query API, else your system will suffer in case large number of values are returned.

Upvotes: 1

Mark Hayward
Mark Hayward

Reputation: 444

I don't know if it's possible to do exactly as you asked but you could add the sort key value as a separate column in the table.

Perhaps it would be simpler to have two separate columns in the table, one for your partition key and one for your range/sort key. Create a secondary index on the partition key to query and then return values from your new column representing your sort key.

Upvotes: 1

Related Questions