|
| 1 | +# |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | +# contributor license agreements. See the NOTICE file distributed with |
| 4 | +# this work for additional information regarding copyright ownership. |
| 5 | +# The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | +# (the "License"); you may not use this file except in compliance with |
| 7 | +# the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +# |
| 17 | + |
| 18 | +import argparse |
| 19 | +import decimal |
| 20 | +import logging |
| 21 | + |
| 22 | +import boto3 |
| 23 | +from boto3.dynamodb.types import TypeDeserializer |
| 24 | + |
| 25 | +import apache_beam as beam |
| 26 | +from apache_beam.transforms.util import BatchElements |
| 27 | +from apache_beam.options.pipeline_options import PipelineOptions |
| 28 | +from apache_beam.options.pipeline_options import SetupOptions |
| 29 | + |
| 30 | +from dynamodb_pyio.io import WriteToDynamoDB |
| 31 | + |
| 32 | +TABLE_NAME = "dynamodb-pyio-test" |
| 33 | + |
| 34 | + |
| 35 | +def get_table(table_name): |
| 36 | + resource = boto3.resource("dynamodb") |
| 37 | + return resource.Table(table_name) |
| 38 | + |
| 39 | + |
| 40 | +def create_table(table_name): |
| 41 | + client = boto3.client("dynamodb") |
| 42 | + try: |
| 43 | + client.describe_table(TableName=table_name) |
| 44 | + table_exists = True |
| 45 | + except Exception: |
| 46 | + table_exists = False |
| 47 | + if not table_exists: |
| 48 | + print(">> create table...") |
| 49 | + params = { |
| 50 | + "TableName": table_name, |
| 51 | + "KeySchema": [ |
| 52 | + {"AttributeName": "pk", "KeyType": "HASH"}, |
| 53 | + {"AttributeName": "sk", "KeyType": "RANGE"}, |
| 54 | + ], |
| 55 | + "AttributeDefinitions": [ |
| 56 | + {"AttributeName": "pk", "AttributeType": "S"}, |
| 57 | + {"AttributeName": "sk", "AttributeType": "N"}, |
| 58 | + ], |
| 59 | + "BillingMode": "PAY_PER_REQUEST", |
| 60 | + } |
| 61 | + client.create_table(**params) |
| 62 | + get_table(table_name).wait_until_exists() |
| 63 | + |
| 64 | + |
| 65 | +def to_int_if_decimal(v): |
| 66 | + try: |
| 67 | + if isinstance(v, decimal.Decimal): |
| 68 | + return int(v) |
| 69 | + else: |
| 70 | + return v |
| 71 | + except Exception: |
| 72 | + return v |
| 73 | + |
| 74 | + |
| 75 | +def scan_table(**kwargs): |
| 76 | + client = boto3.client("dynamodb") |
| 77 | + paginator = client.get_paginator("scan") |
| 78 | + page_iterator = paginator.paginate(**kwargs) |
| 79 | + items = [] |
| 80 | + for page in page_iterator: |
| 81 | + for document in page["Items"]: |
| 82 | + items.append( |
| 83 | + { |
| 84 | + k: to_int_if_decimal(TypeDeserializer().deserialize(v)) |
| 85 | + for k, v in document.items() |
| 86 | + } |
| 87 | + ) |
| 88 | + return sorted(items, key=lambda d: d["sk"]) |
| 89 | + |
| 90 | + |
| 91 | +def truncate_table(table_name): |
| 92 | + records = scan_table(TableName=TABLE_NAME) |
| 93 | + table = get_table(table_name) |
| 94 | + with table.batch_writer() as batch: |
| 95 | + for record in records: |
| 96 | + batch.delete_item(Key=record) |
| 97 | + |
| 98 | + |
| 99 | +def mask_secrets(d: dict): |
| 100 | + return {k: (v if k.find("aws") < 0 else "x" * len(v)) for k, v in d.items()} |
| 101 | + |
| 102 | + |
| 103 | +def run(argv=None, save_main_session=True): |
| 104 | + parser = argparse.ArgumentParser(description="Beam pipeline arguments") |
| 105 | + parser.add_argument( |
| 106 | + "--table_name", default=TABLE_NAME, type=str, help="DynamoDB table name" |
| 107 | + ) |
| 108 | + parser.add_argument( |
| 109 | + "--num_records", default="500", type=int, help="Number of records" |
| 110 | + ) |
| 111 | + known_args, pipeline_args = parser.parse_known_args(argv) |
| 112 | + |
| 113 | + pipeline_options = PipelineOptions(pipeline_args) |
| 114 | + pipeline_options.view_as(SetupOptions).save_main_session = save_main_session |
| 115 | + print(f"known_args - {known_args}") |
| 116 | + print(f"pipeline options - {mask_secrets(pipeline_options.display_data())}") |
| 117 | + |
| 118 | + with beam.Pipeline(options=pipeline_options) as p: |
| 119 | + ( |
| 120 | + p |
| 121 | + | "CreateElements" |
| 122 | + >> beam.Create( |
| 123 | + [ |
| 124 | + { |
| 125 | + "pk": str(int(1 if i >= known_args.num_records / 2 else i)), |
| 126 | + "sk": int(1 if i >= known_args.num_records / 2 else i), |
| 127 | + } |
| 128 | + for i in range(known_args.num_records) |
| 129 | + ] |
| 130 | + ) |
| 131 | + | "BatchElements" >> BatchElements(min_batch_size=100, max_batch_size=200) |
| 132 | + | "WriteToDynamoDB" |
| 133 | + >> WriteToDynamoDB( |
| 134 | + table_name=known_args.table_name, dedup_pkeys=["pk", "sk"] |
| 135 | + ) |
| 136 | + ) |
| 137 | + |
| 138 | + logging.getLogger().setLevel(logging.INFO) |
| 139 | + logging.info("Building pipeline ...") |
| 140 | + |
| 141 | + |
| 142 | +if __name__ == "__main__": |
| 143 | + create_table(TABLE_NAME) |
| 144 | + print(">> start pipeline...") |
| 145 | + run() |
| 146 | + print(">> check number of records...") |
| 147 | + print(len(scan_table(TableName=TABLE_NAME))) |
| 148 | + print(">> truncate table...") |
| 149 | + truncate_table(TABLE_NAME) |
0 commit comments