imhamburger 님의 블로그

DynamoDB: The provided key element does not match the schema 본문

끄적끄적

DynamoDB: The provided key element does not match the schema

imhamburger 2025. 12. 19. 13:12

에러메세지

Error: An error occurred (ValidationException) when calling the BatchWriteItem operation:
The provided key element does not match the schema

 

 

원인

The provided key element does not match the schema
→ 즉, 넣으려는 아이템의 기본 키(primary key) 가 DynamoDB 테이블 스키마의 키 정의와 다르다는 뜻.

나는 PK만 맞추면 될 줄 알았는데 Sort Key가 지정되어있다면 그것도 맞춰줘야 한다고 한다.

DynamoDB 테이블에 Primary Key, Sort Key 두 개 다 명시되어 있었다.

- (1) Partition key만 있음
    → `companyID (Number)`
    
- (2) Partition + Sort key 있음
    → `companyID (Number)` + `registrationDate (String)`
  
Partition key와 Sort key가 있다면 두 개 다 반드시 존재해야 하고 타입도 일치해야 한다.

 

 

해결방법

기존코드)

def batch_delete_dynamodb(table, pk_name, chunk_size=25):
    """
    테이블 전체 삭제
    """
    scan = table.scan()
    items = scan.get('Items', [])

    while 'LastEvaluatedKey' in scan:
        scan = table.scan(ExclusiveStartKey=scan['LastEvaluatedKey'])
        items.extend(scan.get('Items', []))

    print(f"Deleting {len(items)} items from DynamoDB...")

    for i in range(0, len(items), chunk_size):
        chunk = items[i:i+chunk_size]
        with table.batch_writer() as batch:
            for item in chunk:
                if pk_name in item:
                    batch.delete_item(Key={
                    pk_name: str(item[pk_name])
                    })
                else:
                    print("Skipped item without PK:", item)

 

 

수정코드)

def batch_delete_dynamodb(table, pk_name, sk_name, chunk_size=25):
    """
    테이블 전체 삭제
    """
    scan = table.scan()
    items = scan.get('Items', [])

    while 'LastEvaluatedKey' in scan:
        scan = table.scan(ExclusiveStartKey=scan['LastEvaluatedKey'])
        items.extend(scan.get('Items', []))

    print(f"Deleting {len(items)} items from DynamoDB...")

    for i in range(0, len(items), chunk_size):
        chunk = items[i:i+chunk_size]
        with table.batch_writer() as batch:
            for item in chunk:
                if pk_name in item:
                    batch.delete_item(Key={
                    pk_name: str(item[pk_name]),
                    sk_name: str(item[sk_name])
                    })
                else:
                    print("Skipped item without PK:", item)

 

 

다른 해결방법으로는 아예 Key값을 주지 않는 것이다.

 

수정 전)

with table.batch_writer(overwrite_by_pkeys=['companyID', 'registrationDate']) as batch:

 

수정 후)

with table.batch_writer() as batch: