
보조 인덱스(Secondary index) 를 사용하는 이유
update_table 을 통해 인덱스 생성AttributeDefinitions 내부 AttributeName 인 Category와 AttributeType 인 String 명시GlobalSecondaryIndexUpdates=[{"Create": {...}}] 를 통해 secondary index 생성Projection 내부에 ProjectionType all 을 하겠다는 의미는 인덱스에 모든 걸 담겠다는 것. 즉 그 테이블 전체 돌아가면서 인덱스 생성하겠다는 거임ProvisionedThroughput 안에 있는 ReadCapacityUnits는 RCU, WriteCapacityUnits는 WCU를 의미함import boto3
client = boto3.client('dynamodb', region_name=‘ap-northeast-2')
try:
resp = client.update_table(
TableName="Books",
AttributeDefinitions=[
{
"AttributeName": "Category",
"AttributeType": "S"
},
],
GlobalSecondaryIndexUpdates=[
{
"Create": {
"IndexName": "CategoryIndex",
"KeySchema": [
{
"AttributeName": "Category",
"KeyType": "HASH"
}
],
"Projection": {
"ProjectionType": "ALL"
},
"ProvisionedThroughput": {
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1,
}
}
}
],
)
print("Secondary index added!")
except Exception as e:
print("Error updating table:")
print(e)
요약
Python → boto3 → AWS DynamoDB
1. Books 테이블에
2. CategoryIndex라는 글로벌 보조 인덱스를
3. Category를 키로 사용해서 추가
4. 결과를 성공/실패 출력



query 메서드를 사용해서 보조 인덱스 쿼리를 사용해서 데이터 조회KeyConditionExpression을 사용해서 조건 설정ExpressionAttributeValues을 사용해서 조건 구체화(String 형식의 Technology)import boto3
dynamodb = boto3.client('dynamodb',
region_name='us-east-1')
resp = dynamodb.query(
TableName='Books',
IndexName='CategoryIndex',
KeyConditionExpression='Category
= :categoryValue',
ExpressionAttributeValues={
':categoryValue': {'S': 'Technology'}
}
)
print(resp['Items'])
execute_statement 을 써도 상태 조회 가능Statement=... 에 쿼리를 넣으면 됨.import boto3
dynamodb = boto3.client('dynamodb',
region_name='ap-northeast-2')
resp =
dynamodb.execute_statement(Statement='
SELECT * FROM Books.CategoryIndex
WHERE Category = \'Technology\'')
print(resp['Items'])
UPDATE와 SET을 사용해서 함import boto3
dynamodb = boto3.client('dynamodb',
region_name='ap-northeast-2')
resp = dynamodb.execute_statement(
Statement="""
UPDATE Books
SET Formats.Audiobook = 'JCV555'
WHERE Author = 'Antje Barth' AND Title
= 'Data Science on AWS'
"""
)
print("Update completed.")
update_item을 사용해서 할 수 있음UPDATE와 REMOVE를 사용import boto3
dynamodb = boto3.client('dynamodb',
region_name='ap-northeast-2')
resp = dynamodb.execute_statement(
Statement="""
UPDATE Books
REMOVE Formats.Audiobook
WHERE Author = 'Antje Barth' AND Title
= 'Data Science on AWS'
"""
)
print("Attribute removed successfully.")
delete_item을 사용할 수도 있음put_item 을 사용하면 항목 속성 추가delete_table 사용하여 삭제import boto3
client = boto3.client('dynamodb',
region_name='ap-northeast-2')
try:
resp = client.delete_table(
TableName="Books",
)
print("Table deleted successfully!")
except Exception as e:
print("Error deleting table:")
prin
+) keyConditionExpression
table.query( IndexName = 'GenreRatingIndex', KeyConditionExpressio = Key('Genre').eq('Sci-Fi') )
+) describe_table
response = dynamodb.describe_table(TableName=table_name)