File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Use this when possible.
2+ # Query with a GSI is faster & cheaper.
3+
4+ import os
5+
6+ import boto3
7+ from botocore .exceptions import ClientError
8+ from dotenv import load_dotenv
9+
10+ load_dotenv () # Load environment variables from .env file
11+ db = boto3 .resource ("dynamodb" , region_name = os .getenv ("REGION" ))
12+ table = db .Table (os .getenv ("DATABASE" ))
13+
14+ column_name = os .getenv ("INDEX_KEY" )
15+ val_o = "Eng"
16+ val_n = "Engineering"
17+
18+ try :
19+ response = table .query (
20+ IndexName = os .getenv ("INDEX" ),
21+ KeyConditionExpression = boto3 .dynamodb .conditions .Key (os .getenv ("INDEX_KEY" )).eq (
22+ val_o
23+ ),
24+ )
25+
26+ for item in response .get ("Items" , []):
27+ table .update_item (
28+ Key = {
29+ "PK" : item ["PK" ],
30+ # 'SK': item['SK'] # If has Sort Key
31+ },
32+ UpdateExpression = "SET #col = :val" ,
33+ ExpressionAttributeNames = {"#col" : column_name },
34+ ExpressionAttributeValues = {":val" : val_n },
35+ )
36+ except ClientError as e :
37+ print (f"Error: { e .response ['Error' ]['Message' ]} " )
38+ except KeyError as e :
39+ print (f"Key Error. Missing: { e } " )
Original file line number Diff line number Diff line change 1+ # This scans the whole table, which costs RCUs.
2+ # Use Query with a GSI if possible.
3+
4+ import os
5+
6+ import boto3
7+ from botocore .exceptions import ClientError
8+ from dotenv import load_dotenv
9+
10+ load_dotenv () # Load environment variables from .env file
11+ db = boto3 .resource ("dynamodb" , region_name = os .getenv ("REGION" ))
12+ table = db .Table (os .getenv ("DATABASE" ))
13+
14+ column_name = os .getenv ("INDEX_KEY" )
15+ val_o = "Eng"
16+ val_n = "Engineering"
17+
18+ try :
19+ response = table .scan (
20+ FilterExpression = boto3 .dynamodb .conditions .Attr (column_name ).eq (val_o )
21+ )
22+
23+ for item in response .get ("Items" , []):
24+ table .update_item (
25+ Key = {
26+ "PK" : item ["PK" ],
27+ # 'SK': item['SK'] # If has Sort Key
28+ },
29+ UpdateExpression = "SET #col = :val" ,
30+ ExpressionAttributeNames = {"#col" : column_name },
31+ ExpressionAttributeValues = {":val" : val_n },
32+ )
33+ except ClientError as e :
34+ print (f"Error: { e .response ['Error' ]['Message' ]} " )
35+ except KeyError as e :
36+ print (f"Key Error. Missing: { e } " )
You can’t perform that action at this time.
0 commit comments