-
Notifications
You must be signed in to change notification settings - Fork 228
/
Copy pathquery-consistent-read.py
39 lines (32 loc) · 1.23 KB
/
query-consistent-read.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return str(o)
return super(DecimalEncoder, self).default(o)
dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
table = dynamodb.Table('Music')
try:
response = table.query(
ExpressionAttributeNames={
'#pk': 'Artist',
},
ExpressionAttributeValues={
':pk': 'Michael Jackson',
},
KeyConditionExpression='#pk = :pk',
ConsistentRead=True
)
except ClientError as e:
print(e.response['Error']['Message'])
else:
if 'LastEvaluatedKey' in response:
print('Not all items have been retrieved by this query. At least one another request is required to get all available items. The last evaluated key corresponds to',
json.dumps(response['LastEvaluatedKey'], indent=4, cls=DecimalEncoder))
print('Query response:', json.dumps(response, indent=4, cls=DecimalEncoder))