tayfun
tayfun

Reputation: 3135

boto3 query using KeyConditionExpression

I'm having trouble understanding why below query on a DynamoDB table doesn't work:

dict_table.query(KeyConditionExpression='norm = :cihan', ExpressionAttributeValues={':cihan': {'S': 'cihan'}})

and throws this error:

ClientError: An error occurred (ValidationException) when calling the Query operation: One or more parameter values were invalid: Condition parameter type does not match schema type

while the following works:

dict_table.query(KeyConditionExpression=Key('norm').eq('cihan'))

norm is a field with type string. I'm using boto3 v 1.4.0 and following the docs:

In [43]: boto3.__version__
Out[43]: '1.4.0'

Can anyone see what's the error in the first query?

Bonus question: What's with all the tokens and the need to replace them all the time? Why can't I just say dict_table.query(KeyConditionExpression='norm = cihan')

Upvotes: 9

Views: 20956

Answers (3)

rayepps
rayepps

Reputation: 2092

The bonus question...

To answer your bonus question, all the tokens are a layer of abstraction dynamo uses to ensure type consistency across the http requests made when its communicated with. Using standard http/json there is room for ambiguity in cases like "2" and 2. So, dynamo forces the client to wrap values in objects that specifically define their type.

Back to the original question...

With that said... its kind of ridiculous the boto3 API doesn't abstract that away for you. Although I can understand its a little out of the scope of the boto3 tool. There is hope in a library called dynamof. Using it your query would look like:

from boto3 import client
from dynamof import db as make_db
from dynamof import query

client = client('dynamodb', endpoint_url='http://localstack:4569')
db = make_db(client)

results = db(query(
    table_name='dict_table',
    conditions=attr('norm').equals('cihan')
))

You get the same simple API for making dynamo requests in other commonly used operations like creating a table, adding an item, updating, deleting, and scanning. More operations and features are in dev now.

disclaimer: I wrote dynamof

Upvotes: 2

Ishan Ojha
Ishan Ojha

Reputation: 400

In current versions of boto3 (1.9.128) the query mentioned in the question asked works fine, and nothing else apart from that is working now, the query mentioned below worked for me:-

dynamo_client.query( KeyConditionExpression='campaign_id = :201906', ExpressionAttributeValues={':201906': {'S': '201906'}} )

Upvotes: 2

notionquest
notionquest

Reputation: 39226

Please change the ExpressionAttributeValues as mentioned below.

ExpressionAttributeValues={':cihan': 'cihan'}

Upvotes: 7

Related Questions