DynamoDB Scan的IN条件无法正常工作的问题排查
Ah, I see the issue here—you're misusing the IN condition with a String Set (SS) type when you should be passing a list of individual string values instead.
Why Your Current Code Fails
Your Roles table stores the role attribute as a single string (S type), not a string collection (SS). When you pass {'SS': ['system-admin', 'test']} as the value for :user_roles, DynamoDB interprets this as looking for items where the role attribute equals that entire set. Since none of your role values are sets (they're single strings), no matches are found.
When you use {'S': 'system-admin'}, you're correctly targeting items where role equals that single string—hence why that works.
Correct Code Implementation
To make the IN condition work as intended, you need to pass a list of individual string values (either using boto3's simplified type inference or explicit S type definitions):
Simplified Version (boto3 Auto-Infers Types)
client.scan( TableName='Roles', FilterExpression='#attr IN (:user_roles)', ExpressionAttributeNames={ '#attr': 'role', '#target': 'permissions' }, ExpressionAttributeValues={ ':user_roles': ['system-admin', 'test'] }, ProjectionExpression='#target' )['Items']
Explicit Type Definition (More Rigorous)
client.scan( TableName='Roles', FilterExpression='#attr IN (:user_roles)', ExpressionAttributeNames={ '#attr': 'role', '#target': 'permissions' }, ExpressionAttributeValues={ ':user_roles': [{'S': 'system-admin'}, {'S': 'test'}] }, ProjectionExpression='#target' )['Items']
Key Note
The IN operator in DynamoDB is designed to check if a single-valued attribute exists within a list of individual values. If your attribute were a string set (SS), you'd use operators like CONTAINS instead—but in your use case, since role is a single string, passing a list of strings to IN is the right approach.
内容的提问来源于stack exchange,提问作者Martin Schulze

