sid8491
sid8491

Reputation: 6800

Error in KeyConditionExpression when using contains on partition key

I have Tags as partition key in my table, and when I am trying to query I am getting AttributeError.

Below is my code:

kb_table = boto3.resource('dynamodb').Table('table_name')
result = kb_table.query(
        KeyConditionExpression=Key('Tags').contains('search term')
    )

return result['Items']

Error:

"errorMessage": "'Key' object has no attribute 'contains'"

Basically I want to search through the table where I the field is having that search term. I have achived it using scan but I have read everywhere that we should not use that.

result = kb_table.scan(
        FilterExpression="contains (Tags, :titleVal)", 
        ExpressionAttributeValues={ ":titleVal": "search term" }
    )

So I have changed my partition-key to Tags along with a sort-key so that I can achieve this using query but now I am getting this error. Any idea how to get this working?

Upvotes: 2

Views: 2190

Answers (1)

F_SO_K
F_SO_K

Reputation: 14799

In order to use Query you must specify one partition to access, you cannot wildcard a partition or specify multiple keys.

KeyConditionExpression

The condition that specifies the key value(s) for items to be retrieved by the Query action.

The condition must perform an equality test on a single partition key value.

Assuming you want to search the whole table for tags, a scan is the most appropriate approach.

EDIT: You can use Query with the exact search term, but im guessing that is not what you want.

kb_table = boto3.resource('dynamodb').Table('table_name')
result = kb_table.query(
        KeyConditionExpression=Key('Tags').eq('search term')
    )

return result['Items']

Upvotes: 1

Related Questions