<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Divachavan on Medium]]></title>
        <description><![CDATA[Stories by Divachavan on Medium]]></description>
        <link>https://medium.com/@divachavan974?source=rss-b4da99f0c54------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*lmPfB3FEE0leF4vZ</url>
            <title>Stories by Divachavan on Medium</title>
            <link>https://medium.com/@divachavan974?source=rss-b4da99f0c54------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:34:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@divachavan974/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AWSDynamodb Table converted to pyspark dataframe using Python]]></title>
            <link>https://medium.com/@divachavan974/awsdynamodb-table-converted-to-pyspark-dataframe-using-python-9c98cb0e7461?source=rss-b4da99f0c54------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c98cb0e7461</guid>
            <category><![CDATA[aws-dynamodb]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[boto3-python]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Divachavan]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 14:05:43 GMT</pubDate>
            <atom:updated>2023-12-18T14:18:16.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*GZ7SUJWADkxzOCmiI_1yVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wjcNhgQ55RKg0TgVWkY1UA.png" /></figure><p>Working as a Data- Enthusiast one always has to work with cloud services ,Python and NoSql databases .</p><p>Recently, i also got an opportunity to work on <strong>AWS DynamoDB </strong>and for multiple cases like storing S3-Uri , crawling S3 data using Dynamodb and using Dynamodb as a logging and analysing tool on aws console for one of the best ETL tools i.e. <strong>AWS Glue</strong></p><blockquote>This post will cover one of the way to convert <strong>DynamoDB to Pyspark-Dataframe </strong>, which is very usefull when we include DynamoDB in high level Data-pipelines</blockquote><h4><strong>First Step</strong> = Use below link to understand the format of data in Dynamodb table</h4><p><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/AppendixSampleTables.html">Example tables and data</a></p><h3><strong>Python code-</strong></h3><pre>import boto3<br>from pyspark.sql import DataFrame<br>from pyspark.sql import SparkSession<br><br>spark = SparkSession.builder.appName(&#39;Dynamo to DF&#39;).getOrCreate()<br>aws_access_key_id = &#39;your_aws_access_key_id&#39;<br>aws_secret_access_key = &#39;your_secret_access_key&#39;<br><br># use boto - resource() api , you can also use boto&#39;s client api <br># But then you will need to map the values of table content <br># As it gives out data data for string value - {S:&quot;string&quot;}, num values - {N:1} <br># so i would suggest use resource api :) <br><br>dynamodb_resource =  boto3.resource(service_name = &#39;dynamodb&#39;,region_name = &#39;your-region&#39;,<br>              aws_access_key_id = aws_access_key_id,<br>              aws_secret_access_key = aws_secret_access_key)<br><br>table = dynamodb_resource.Table(&quot;your_table_name&quot;)<br><br># scan() function will take all the rows from the table (your_table_name)<br>data = table.scan()<br><br><br>data = [dict(i) for i in data[&quot;Items&quot;]]<br><br># create dataframe from data <br>df = spark.createDataFrame(data)<br><br>df = df.select(&quot; select the columns which you want in dataframe &quot;)<br><br># can also add additional filtering on the dataframe using where function and etc.<br># to display dataframe content<br>df.show()<br></pre><p><strong>In case you dont wan’t to use resource api , and want to implement it using client() api refer to below code</strong></p><pre>import boto3<br>from pyspark.sql import DataFrame<br>from pyspark.sql import SparkSession<br><br>spark = SparkSession.builder.appName(&#39;Dynamo to DF&#39;).getOrCreate()<br><br># credentials<br>aws_access_key_id = &#39;your_aws_access_key_id&#39;<br>aws_secret_access_key = &#39;your_secret_access_key&#39;<br><br># dynamodb_client instance<br>dynamodb_client =  boto3.client(service_name = &#39;dynamodb&#39;,region_name = &#39;your-region&#39;,<br>      aws_access_key_id = aws_access_key_id,<br>      aws_secret_access_key = aws_secret_access_key)<br><br>#scan table <br>response = dynamodb_client.scan(TableName=&quot;Your_table_name&quot;)<br><br># collecting the data from output response<br>data = response[&#39;Items&#39;]<br><br># Below loop will actually give clear output from the data <br>list_data = []<br>for item in data:<br>    output_dict = {}<br>    for key, value in item.items():<br>        if isinstance(value, dict):<br>            if &#39;S&#39; in value:<br>                output_dict[key] = value[&#39;S&#39;]<br>            elif &#39;N&#39; in value:<br>                output_dict[key] = value[&#39;N&#39;]<br>    list_data.append(output_dict)<br><br><br># create a pyspark dataframe from list of dict data<br>df = spark.createDataFrame(list_data)<br>df = df.select(&quot;column names to filter&quot;).where(&quot;Whatever condition you want to filter&quot;)<br><br># display data <br>df.show()</pre><p>Hoping this might help :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c98cb0e7461" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use DynamoDB to save S3-Events & S3-URI]]></title>
            <link>https://medium.com/@divachavan974/how-to-use-dynamodb-to-save-s3-events-s3-uri-5be27b9d051e?source=rss-b4da99f0c54------2</link>
            <guid isPermaLink="false">https://medium.com/p/5be27b9d051e</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Divachavan]]></dc:creator>
            <pubDate>Thu, 14 Dec 2023 10:42:44 GMT</pubDate>
            <atom:updated>2023-12-14T10:42:44.952Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong><em>AWS-Lambda to store S3-events in DynamoDB (Python 3.0+)</em></strong></h3><blockquote>This blog will cover all the required information to save a s3 events related data in dynamodb</blockquote><p>Step 1- you will need to create a new lambda from AWS console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thYFBnvE6st4dTdntJtTVQ.png" /></figure><p>Step 2 -configure a s3 event trigger to from the Lambda configuration like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yp5uNsk8dzaBYwA9kDPuqA.png" /></figure><blockquote><em>As you can see above, I have set the Suffix of the s3 event trigger as .json : you can set as per your requirement (.csv, .parquet .e.t.c)</em></blockquote><blockquote>Also I have set the trigger event on <strong>All object create events </strong>,i would suggest you select proper option for that otherwise it will be triggered on every copy, uplooad , move ,e.t.c type of events</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcdJOOzNnjBsdY_yCMLevQ.png" /></figure><p>Below is the sample Json we get from the s3 event whenever there is a new file uploaded in s3 ,</p><p>you can also refer to this aws documentation to know more about S3-event and its usecase in Lambda,SNS, SQS</p><p><a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-content-structure.html">Event message structure</a></p><pre>{  <br>   &quot;Records&quot;:[  <br>      {  <br>         &quot;eventVersion&quot;:&quot;2.2&quot;,<br>         &quot;eventSource&quot;:&quot;aws:s3&quot;,<br>         &quot;awsRegion&quot;:&quot;us-west-2&quot;,<br>         &quot;eventTime&quot;:&quot;The time, in ISO-8601 format, for example, 1970-01-01T00:00:00.000Z, when Amazon S3 finished processing the request&quot;,<br>         &quot;eventName&quot;:&quot;event-type&quot;,<br>         &quot;userIdentity&quot;:{  <br>            &quot;principalId&quot;:&quot;Amazon-customer-ID-of-the-user-who-caused-the-event&quot;<br>         },<br>         &quot;requestParameters&quot;:{  <br>            &quot;sourceIPAddress&quot;:&quot;ip-address-where-request-came-from&quot;<br>         },<br>         &quot;responseElements&quot;:{  <br>            &quot;x-amz-request-id&quot;:&quot;Amazon S3 generated request ID&quot;,<br>            &quot;x-amz-id-2&quot;:&quot;Amazon S3 host that processed the request&quot;<br>         },<br>         &quot;s3&quot;:{  <br>            &quot;s3SchemaVersion&quot;:&quot;1.0&quot;,<br>            &quot;configurationId&quot;:&quot;ID found in the bucket notification configuration&quot;,<br>            &quot;bucket&quot;:{  <br>               &quot;name&quot;:&quot;bucket-name&quot;,<br>               &quot;ownerIdentity&quot;:{  <br>                  &quot;principalId&quot;:&quot;Amazon-customer-ID-of-the-bucket-owner&quot;<br>               },<br>               &quot;arn&quot;:&quot;bucket-ARN&quot;<br>            },<br>            &quot;object&quot;:{  <br>               &quot;key&quot;:&quot;object-key&quot;,<br>               &quot;size&quot;:&quot;object-size in bytes&quot;,<br>               &quot;eTag&quot;:&quot;object eTag&quot;,<br>               &quot;versionId&quot;:&quot;object version if bucket is versioning-enabled, otherwise null&quot;,<br>               &quot;sequencer&quot;: &quot;a string representation of a hexadecimal value used to determine event sequence, only used with PUTs and DELETEs&quot;<br>            }<br>         },<br>         &quot;glacierEventData&quot;: {<br>            &quot;restoreEventData&quot;: {<br>               &quot;lifecycleRestorationExpiryTime&quot;: &quot;The time, in ISO-8601 format, for example, 1970-01-01T00:00:00.000Z, of Restore Expiry&quot;,<br>               &quot;lifecycleRestoreStorageClass&quot;: &quot;Source storage class for restore&quot;<br>            }<br>         }<br>      }<br>   ]<br>}</pre><h3>Below is the code which you can change a little bit according to your requirement</h3><blockquote>Note: I have replaced key string “%3D” with “=” as there is inbuilt URL encoding module which changes special characters ,there can be other characters which you might need to handle the same</blockquote><p>**Important** :- Create dynamodb table with your desired name and make sure to understand the concept of partition key and sort key in dynamodb</p><pre>import json<br>import boto3<br><br>def extract_variables(event):<br>    data = {}<br>    for record in event[&quot;Records&quot;]:<br>        data[&quot;date&quot;]       = record[&quot;eventTime&quot;][:10]<br>        data[&quot;time&quot;]       = record[&quot;eventTime&quot;][11:-5]<br>        data[&quot;eventName&quot;]  = record[&quot;eventName&quot;]<br>        key                = (record[&#39;s3&#39;][&#39;object&#39;][&#39;key&#39;]).replace(&quot;%3D&quot;, &quot;=&quot;)<br>        data[&quot;key&quot;]        = record[&quot;s3&quot;][&quot;object&quot;][&quot;key&quot;]<br>        data[&quot;sourceIP&quot;]   = record[&quot;requestParameters&quot;][&quot;sourceIPAddress&quot;]<br>        data[&quot;bucketName&quot;] = record[&quot;s3&quot;][&quot;bucket&quot;][&quot;name&quot;]<br>        data[&quot;s3_uri&quot;]     = f&quot;s3://{data[&#39;bucketName&#39;]}/{key}&quot;<br>        data[&quot;etag&quot;]       = record[&quot;s3&quot;][&quot;object&quot;][&quot;eTag&quot;]<br>        data[&quot;filesize&quot;]   = record[&quot;s3&quot;][&quot;object&quot;][&quot;size&quot;]<br><br>        return data<br><br><br>def insert_into_dynamodb(data):<br>    dynamodb = boto3.resource(&quot;dynamodb&quot;)<br>    table = dynamodb.Table(&quot;Your_table_name&quot;)<br><br>    response = table.put_item(<br>        Item={<br>            &quot;EVENT_DATE&quot; : data[&quot;date&quot;],<br>            &quot;TABLE_NAME&quot; : data[&quot;Table_name&quot;],<br>            &quot;EVENT_TIME&quot; : data[&quot;time&quot;],<br>            &quot;EVENT_NAME&quot; : data[&quot;eventName&quot;],<br>            &quot;BUCKET_NAME&quot;: data[&quot;bucketName&quot;],<br>            &quot;S3_URI&quot;     : data[&quot;s3_uri&quot;],<br>            &quot;FILE_SIZE&quot;  : data[&quot;filesize&quot;],<br>            &quot;ETAG&quot;       : data[&quot;etag&quot;],<br>            &quot;IP&quot;         : data[&quot;sourceIP&quot;]<br>        }<br>    )<br>    return response<br><br><br>def lambda_handler(event, context):<br>    data = extract_variables(event)<br>    response = insert_into_dynamodb(data)<br>    print(response)<br>    return {<br>        &quot;statusCode&quot;: 200,<br>        &quot;body&quot;: json.dumps(<br>            &quot;Hey! we have successfully recorded the data event in dynamodb table&quot;<br>        ),<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5be27b9d051e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>