Use .contains() to retrieve values from DynamoDB

Question:

I’m new with NoSQL Databases and am stuck with a problem. I just want to get keys from a table in DynamoDB that contains a specific value. I know that for key equals I can use:

response = table.query(
    KeyConditionExpression=Key('year').eq(1992) 
) 

But I can’t use:

 response = table.query(
    KeyConditionExpression=Key('year').contain('1992') 
) 

The error is:

Key object has no attribute contain.

Asked By: Redair

||

Answers:

Here you can check all the methods for Key class:

https://github.com/boto/boto3/blob/develop/boto3/dynamodb/conditions.py

Key class is inherited from class AttributeBase and here are nothing like contains, only greater than or starts with etc.

Answered By: Olia

DynamoDB doesn’t follow to use contain for key attribute on Query API. You can use only equals for partition key attribute.

CONTAINS can be used with LIST or SET data type only. Also, it can be used only on FilterExpression.

CONTAINS : Checks for a subsequence, or value in a set.

CONTAINS is supported for lists: When evaluating “a CONTAINS b”, “a”
can be a list; however, “b” cannot be a set, a map, or a list.

Answered By: notionquest

People looking at this question in 2023 (At least with the current version of Boto!) are going to be misled to the other answers here.

You can now check if a value contains a substring by using the Attr object, not Key.

  response = table.scan(
        FilterExpression=Attr('key').contains(string)
  )
Answered By: AirmanEpic