Walter U.
Walter U.

Reputation: 341

Use string as parameter for FilterExpression in dynamoDB query

I have the following string in python :

fe = "Attr('COLOR').eq('RED')"

and I'm trying to use FilterExpression to query a dynamoDB table, this is what I'm calling:

response = table.query(KeyConditionExpression=Key('key').eq(key),
                       FilterExpression=fe        
)

but I'm getting:

An error occurred (ValidationException) when calling the Query operation: Invalid FilterExpression: Syntax error; token: "'", near: "('COLOR"

Is it possible to pass a string as a parameter for the FilterExpression query? It needs to come in as a string cause it's being fed by a dictionary. I tried stripping the quotes such as:

response = table.query(KeyConditionExpression=Key('key').eq(key),
                           FilterExpression=fe.replace('"', '')        
    )

but it hasn't worked. Any ideas as to what I might try next? Thanks!

Upvotes: 1

Views: 2403

Answers (1)

Mike Patrick
Mike Patrick

Reputation: 11007

I don't think you can pass a string for the FilterExpression, but you can obtain the Python expression you want using eval().

fe = "Attr('COLOR').eq('RED')"
key = 'myKey'
response = table.query(KeyConditionExpression=Key('key').eq(key),
                       FilterExpression=eval(fe))

Of course, you need to really trust your input when using eval().

Upvotes: 4

Related Questions