How to query 'Not Equal to' in boto3 dynamoDB python

Viewed 4764

I am new to AWS and python. I have been trying to get the records from dynamoDB using boto3 in python. Could anyone please suggest how to get records when value1 not equal to value2. I am able to query with eq but not ne. Below is my code.

response = table.query(
    KeyConditionExpression=Key('Id').eq('123') & Key('status').ne('Booked')
)

I am getting below error when I execute the above code.

Lambda execution failed with status 200 due to customer function error: 'Key' object has no attribute 'ne'.
3 Answers

KeyCondition does not include ne. It's only available for filterExpression. But filterExpression can't have any of the primary key (neither partition key nor sort key). If you are trying to add not equal condition to a sort key, there were suggestions to create a GSI and use that sort key as a regular attribute instead.

I am stuck in the same situation and hope this help.

link from aws

As previous answers mentioned, you need to use FilterExpression, and then set the ExpressionAttributeValues. Also, call .scan rather than .query. Below is how you would write it in Python 3.8 or higher.

dynamodb = boto3.resource('dynamodb', region_name='xx-xxxx-1')
table = dynamodb.Table("tableName")

response = table.scan(
     FilterExpression = 'Id = :i AND status <> :s',
     ExpressionAttributeValues = {':i' : '123', ':s' : 'Booked',}
)['Items'] 
Related