How to query AWS DynamoDB in python?

I am new to NoSQL and am using AWS DynamoDB. I call it from AWS Lambda using python 2.7. I'm trying to get the value from the "order_number" field.
This is what my table looks like (only one entry):
enter image description here

section primary key: subscription_id enter image description here


and my secondary global index: order_number
enter image description here

Is my installation configured correctly? If order_number is given, how to get a record using python?
I cannot understand the syntax to do this. I tried

response = table.get_item( Key = {'order_number': myordernumber} ) 

But I get:
An error (ValidationException) occurred while calling the GetItem operation: the provided key element does not match the scheme: ClientError

+5
source share
2 answers

DynamoDB does not automatically index all fields of your object. By default, you can define a hash key ( subscription_id in your case) and, if necessary, a range key, and they will be indexed. So you can do this:

 response = table.get_item(Key={'subscription_id': mysubid}) 

and it will work as expected. However, if you want to get an element based on order_number , you will need to use the scan operation, which scans all the elements in your table to find one with the correct value. This is a very expensive operation. Or you can create a global secondary index in your table that uses order_number as the primary key. If you did this and called the new order_number-index , you could query for objects matching a specific sequence number, as follows:

 response = table.query( IndexName='order_number-index', KeyConditionExpression=Key('order_number').eq(myordernumber)) 

DynamoDB is a very fast, scalable and efficient database, but it takes a lot of thought about what fields you can look for and how to do it efficiently.

The good news is that now you can add GSI to your existing table. Previously, you had to delete the table and start all over again.

+8
source

Make sure you import this:

 from boto3.dynamodb.conditions import Key, Attr 

If you don’t have one, you will probably get an error. This is in the documentation .

Thanks to @altoids for the comment above, as this is the right answer for me. I wanted to draw attention to this with a β€œformal” answer.

+4
source

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


All Articles