24
votes

I have written some python code, I want to query dynamoDB data by sort key. I remember I can use follow-up code successful:

 table.query(KeyConditionExpression=Key('event_status').eq(event_status))

My table structure column

primary key:event_id
sort key: event_status
4

4 Answers

23
votes

You have to create a global secondary index (GSI) for the sort key in order to query on it alone.

8
votes

The scan API should be used if you would like to get data from DynamoDB without using Hash Key attribute value.

Example:-

fe = Attr('event_status').eq("new");

response = table.scan(
        FilterExpression=fe        
    )

for i in response['Items']:

print(json.dumps(i, cls=DecimalEncoder))

while 'LastEvaluatedKey' in response:
    response = table.scan(        
        FilterExpression=fe,        
        ExclusiveStartKey=response['LastEvaluatedKey']
        )

    for i in response['Items']:
        print(json.dumps(i, cls=DecimalEncoder))
0
votes

By using FilterExpression we can scan the table using Sort key

NOTE: here LastUpdated is sortkey

Example:

from_date = "fromdate"
to_date = "todate"

dynamodb = boto3.resource('dynamodb', region_name='ap-south-1')
table = dynamodb.Table("your-tablename")
response =table.scan(
    FilterExpression=Attr('LastUpdated').between(from_date,to_date))
    )
result = response['Items']
-1
votes

The query in dynamodb can be done using the primary key only

dynamodb = boto3.resource('dynamodb', region_name='your region name')
table = dynamodb.Table('database-dev')
response = table.query(KeyConditionExpression=Key('your primary key').eq("condition"))

but if you primary consists of both hash key and sort key then we can use hash key like this

dynamodb = boto3.resource('dynamodb', region_name='your region name')
table = dynamodb.Table('database-dev')
response = table.query(KeyConditionExpression=Key('your hash key').eq("condition"))