Query DynamoDB with a hash key and a range key with Boto3

I'm having trouble using AWS Boto3 to query DynamoDB with a hash key and a range key at the same time using the KeyConditionExpression recommendation. I added a sample request:

import boto3 from boto3 import dynamodb from boto3.session import Session dynamodb_session = Session(aws_access_key_id=AWS_KEY, aws_secret_access_key=AWS_PASS, region_name=DYNAMODB_REGION) dynamodb = dynamodb_session.resource('dynamodb') table=dynamodb.Table(TABLE_NAME) request = { 'ExpressionAttributeNames': { '#n0': 'hash_key', '#n1': 'range_key' }, 'ExpressionAttributeValues': { ':v0': {'S': MY_HASH_KEY}, ':v1': {'N': GT_RANGE_KEY} }, 'KeyConditionExpression': '(#n0 = :v0) AND (#n1 > :v1)', 'TableName': TABLE_NAME } response = table.query(**request) 

When I run it for a table with the following schema:

 Table Name: TABLE_NAME Primary Hash Key: hash_key (String) Primary Range Key: range_key (Number) 

I get the following error and I do not understand why:

 ClientError: An error occurred (ValidationException) when calling the Query operation: Invalid KeyConditionExpression: Incorrect operand type for operator or function; operator or function: >, operand type: M 

In my opinion, type M will be the type of a map or dictionary, and I use type N, which is a type of number and matches my table layout for a range key. If someone can explain why this error occurs, or I am also open to another way to execute the same request, even if you cannot explain why this error exists.

+5
source share
1 answer

The Boto 3 SDK creates a condition expression for you when you use the Key and Attr functions imported from boto3.dynamodb.conditions:

 response = table.query( KeyConditionExpression=Key('hash_key').eq(hash_value) & Key('range_key').eq(range_key_value) ) 

Link: http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.Python.04.html

Hope this helps

+15
source

Source: https://habr.com/ru/post/1234245/


All Articles