<?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 Yusuf Alptuğ Aydın on Medium]]></title>
        <description><![CDATA[Stories by Yusuf Alptuğ Aydın on Medium]]></description>
        <link>https://medium.com/@aydinya?source=rss-e4b79b6cef21------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*WzcHWS8L2lJniojM</url>
            <title>Stories by Yusuf Alptuğ Aydın on Medium</title>
            <link>https://medium.com/@aydinya?source=rss-e4b79b6cef21------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:10:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aydinya/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[DynamoDB: Deleting Records Without Partition and Sort Keys with Pagination]]></title>
            <link>https://medium.com/@aydinya/dynamodb-deleting-records-without-partition-and-sort-keys-8ecdd19b8f8f?source=rss-e4b79b6cef21------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ecdd19b8f8f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[nosql]]></category>
            <dc:creator><![CDATA[Yusuf Alptuğ Aydın]]></dc:creator>
            <pubDate>Thu, 07 Sep 2023 13:09:33 GMT</pubDate>
            <atom:updated>2023-09-07T13:10:44.584Z</atom:updated>
            <content:encoded><![CDATA[<p>.</p><h3>Partition Key and Sort Key</h3><p>Each DynamoDB table must have a partition key and as the name indicates Partition Key is used to distribute data across multiple storage partitions.</p><p>Sort Key is optional key that is used to sort records in the partition. Together they are composing the <em>Composite Primary Key</em>.</p><h3>When to use Scan, Query or GetItem?</h3><p>There is a great schema that I attached in my post <a href="https://medium.com/@yusufalptuaydn/dynamodb-deleting-records-with-unknown-sort-keys-4b533c9ea2f5"><strong>DynamoDB: Deleting Records Without Sort Keys</strong></a> too which summarizes the answer to the question in this blog:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*HDk3CkLiBYnAQ5j4.png" /></figure><p>Since the Delete command requires Composite Primary Key (Partition Key + Sort Key) and the desire is to delete all the records <strong>without using a key but other attribute/s</strong>, it’s necessary to use<strong> Scan with FilterExpressions.</strong></p><p>Note that <strong><em>Scan </em></strong><em>command has a maximum of 1 MB data retrieval limit </em><strong><em>even the Limit parameter is defined.</em></strong></p><blockquote><em>- PrimaryKey: unknown</em></blockquote><blockquote><em>- SortKey: unknown</em></blockquote><blockquote><em>Use </em><strong><em>Scan </em></strong><em>to collect keys (has 1 MB limit)</em></blockquote><blockquote><em>Delete records with composite primary key (primitiveKey + sortKey)</em></blockquote><p>I have created a table named “ExampleTable” in local with partition and sort keys as a primary key. Additionally, there are two different attributes where the type of “attributeOne” is a String and “attributeTwo” is a Number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*02lD9at1vKBl-fL_PwhhLA.png" /><figcaption>Metadata</figcaption></figure><p>Next, populate the table to with 9 records and 3 different partition keys, each having a varying number of records distinguished by different sortKey values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*v-NorvaY-ObqEwPmqEY_ww.png" /><figcaption>Initial state of the table</figcaption></figure><p>Here is the code to delete records when <strong>both Partition Key and Sort Keys are unknown</strong>:</p><pre>const { DynamoDBClient, ScanCommand, DeleteItemCommand } = require(&#39;@aws-sdk/client-dynamodb&#39;);<br>const logger = require(&#39;./logger&#39;)<br><br>const client = new DynamoDBClient({<br>  region: process.env.REGION,<br>  credentials: {<br>    accessKeyId: process.env.ACCESS_KEY_ID,<br>    secretAccessKey: process.env.SECRET_ACCESS_KEY<br>  },<br>  endpoint: &#39;http://localhost:8001&#39; // for local<br>});<br><br>const tableName = process.env.TABLE_NAME<br>const partitionKeyName = process.env.PARTITION_KEY_NAME;<br>const sortKeyName = process.env.SORT_KEY_NAME;<br><br>async function deleteRecordsForTarget(targetAttributeName, targetValue) {<br>  let counter = 0;<br>  let ExclusiveStartKey = null;<br>  let shouldContinue = true;<br><br>  const valueType = Number.isFinite(targetValue) ? { N: targetValue } : { S: targetValue }; // defined according to target type<br><br>  while (shouldContinue) {<br>    const params = {<br>      TableName: tableName,<br>      ExclusiveStartKey,<br>      ConsistentRead: true,<br>      FilterExpression: `${targetAttributeName} = :value`,<br>      ExpressionAttributeValues: {<br>        &#39;:value&#39;: valueType<br>      },<br>    };<br><br>    const command = new ScanCommand(params);<br>    const response = await client.send(command);<br>    const { Items, LastEvaluatedKey } = response;<br><br>    logger.info(`${tableName}-dynamodb -- Deleting records with ${targetAttributeName}: ${targetValue}`);<br>    counter += await deleteItems(Items);<br><br>    if (LastEvaluatedKey) {<br>      ExclusiveStartKey = LastEvaluatedKey;<br>    } else {<br>      shouldContinue = false;<br>    }<br>  }<br><br>  return counter;<br>}<br><br>async function deleteItems(items) {<br>  let counter = 0;<br><br>  for (const item of items) {<br>    const partitionKeyValue = item[partitionKeyName].S;<br>    const sortKeyValue = item[sortKeyName].S;<br><br>    if (!partitionKeyValue || !sortKeyValue) {<br>      continue;<br>    }<br><br>    const deleteParams = {<br>      TableName: tableName,<br>      Key: {<br>        [partitionKeyName]: { S: partitionKeyValue },<br>        [sortKeyName]: { S: sortKeyValue }<br>      }<br>    };<br>    const deleteCommand = new DeleteItemCommand(deleteParams);<br>    await client.send(deleteCommand);<br>    logger.info(`${tableName}-dynamodb -- Deleted records with ${partitionKeyName}: ${partitionKeyValue} ${sortKeyName}: ${sortKeyValue}`);<br><br>    counter++;<br>  }<br><br>  return counter;<br>}<br><br><br>async function executeDynamoDBDeletionWithTargetList(targetList) {<br>  <br>  let totalRecordsDeleted = 0;<br><br>  for (const [targetAttributeName, targetValues] of Object.entries(targetList)) {<br>    for (const targetValue of targetValues) {<br>      totalRecordsDeleted += await deleteRecordsForTarget(targetAttributeName, targetValue);<br>    }<br>  }<br><br>  logger.info(`${tableName}-dynamodb -- Total deleted records: ${totalRecordsDeleted}`);<br><br>  return [{<br>    table: tableName,<br>    deletedRecords: totalRecordsDeleted<br>  }];<br>}<br><br>module.exports = executeDynamoDBDeletionWithTargetList;</pre><p><strong>ExclusiveStartKey</strong>: This is used for paginating through the results since the <strong>Scan </strong>has a limit of 1 MB<strong> </strong>even the Limit parameter is defined. It begins as null but may be updated with the LastEvaluatedKey from the previous scan.</p><p><strong>ConsistentRead</strong>: This is used to ensure that the scan operation returns the most up-to-date results.</p><p><strong>FilterExpression</strong>: This paramter is used to specifie the filter condition for the Scan, in this case, filtering records where the value of <strong>targetAttributeName </strong>matches <strong>:value</strong>.</p><p><strong>ExpressionAttributeValues: </strong>this parameter is used to replace the defined placeholder with the values of the attribute want them to be compared at runtime. In another words, it maps the “<strong>:value</strong>” placeholder to the value stored in the <strong>valueType </strong>variable.</p><p>The line below sets the <strong>valueType </strong>according to the type of the target value:</p><pre>const valueType = Number.isFinite(targetValue) ? { N: targetValue } : { S: targetValue }; // defined according to target type</pre><p>In the master code the <strong>deleteRecordsWithUnknownSortKey </strong>method is called by providing an object that contains two keys with a list of elements on each according to attribute type.</p><pre>const deleteRecordsWithUnknownPartitionAndSortKey = require(&#39;./delete-ExampleTable-without-key-dynamodb&#39;);<br><br>const targetValuesToBeDeleted = {&quot;attributeOne&quot;: [&#39;2&#39;, &#39;21&#39;, &#39;22&#39;], &quot;attributeTwo&quot;: [3, 31, 32]}<br>deleteRecordsWithUnknownPartitionAndSortKey(targetValuesToBeDeleted);</pre><p>These are the logs that shows for each attribute given, the code Scans the table <strong>with pagination</strong> to collect Partition Key and Sort Keys from the Scanned records then using those to delete records one by one.</p><pre>PS C:\Users\yusuf.aydin\Dev\YUSUF\dynamodb&gt; node main.js<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting records with attributeTwo: 2&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted records with partitionKey: partitionKey2 sortKey: sortKey2&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting records with attributeTwo: 21&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted records with partitionKey: partitionKey2 sortKey: sortKey21&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting records with attributeTwo: 22&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted records with partitionKey: partitionKey2 sortKey: sortKey22&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting records with attributeOne: 3&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted records with partitionKey: partitionKey3 sortKey: sortKey3&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting records with attributeOne: 31&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted records with partitionKey: partitionKey3 sortKey: sortKey31&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting records with attributeOne: 32&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted records with partitionKey: partitionKey3 sortKey: sortKey32&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Total deleted records: 6&quot;}</pre><p>The table after the deletion looks like the image below. For the provided “attributeOne” String values all records under “partitionKey2” and for the provided “attributeTwo” Number values all records under “partitionKey3” are deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*LpUve7CNFH9brdwHOQe6sg.png" /><figcaption>Status of the table after deletion</figcaption></figure><h3>Dependencies and logger configuration:</h3><p>The dependencies are:</p><ul><li><strong>@aws-sdk/client-dynamodb</strong>: AWS SDK</li><li><strong>dotenv</strong>: to read env variables</li><li><strong>winston</strong>: for the logger</li></ul><pre>&quot;dependencies&quot;: {<br>    &quot;@aws-sdk/client-dynamodb&quot;: &quot;^3.405.0&quot;,<br>    &quot;dotenv&quot;: &quot;^16.3.1&quot;,<br>    &quot;winston&quot;: &quot;^3.10.0&quot;<br>  }</pre><p><strong>.env:</strong></p><pre>REGION=<br>ACCESS_KEY_ID=<br>SECRET_ACCESS_KEY=<br>TABLE_NAME=&quot;ExampleTable&quot;<br>PARTITION_KEY_NAME=&quot;partitionKey&quot;<br>SORT_KEY_NAME=&quot;sortKey&quot;</pre><p>The logger saves the entire log into a file with a timestamp.</p><p><strong>logger.js:</strong></p><pre>const { createLogger, format, transports } = require(&#39;winston&#39;);</pre><pre>const timestamp = new Date().toISOString();<br>const logFilename = `logfile_${timestamp.replaceAll(&#39;:&#39;, &#39;-&#39;,)}.txt`;</pre><pre>module.exports  = createLogger({<br>    level: &#39;info&#39;,<br>    <br>    format: format.json(<br>      format.timestamp(),<br>      format.printf(({ level, message, timestamp }) =&gt; {<br>        return `[${timestamp}] [${level.toUpperCase()}] - ${message}`;<br>      })<br>    ),<br>    transports: [new transports.Console(), <br>      new transports.File({<br>        filename: logFilename,<br>        format: format.combine(<br>          format.timestamp({<br>            format: &quot;YYYY-MM-DD HH:mm:ss&quot;,<br>          }),<br>          format.json()<br>        ),<br>      }),]<br>  });</pre><h3>Resources:</h3><ul><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html?source=post_page-----4b533c9ea2f5--------------------------------">Scan</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html">Read consistency</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html#DDB-Query-request-ExclusiveStartKey">Query</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html#DDB-Scan-request-FilterExpression">Scan</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeValues.html?source=post_page-----4b533c9ea2f5--------------------------------">Expression attribute values</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ecdd19b8f8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DynamoDB: Deleting Records Without Sort Keys]]></title>
            <link>https://medium.com/@aydinya/dynamodb-deleting-records-with-unknown-sort-keys-4b533c9ea2f5?source=rss-e4b79b6cef21------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b533c9ea2f5</guid>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[sort-key]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Yusuf Alptuğ Aydın]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 12:47:04 GMT</pubDate>
            <atom:updated>2023-10-15T19:08:12.296Z</atom:updated>
            <content:encoded><![CDATA[<p>.</p><h4>Partition Key and Sort Key</h4><p>Each DynamoDB table must have a partition key and as the name indicates Partition Key is used to distribute data across multiple storage partitions.</p><p>Sort Key is optional key that is used to sort records in the partition. Together they are composing the <em>Composite Primary Key</em>.</p><h4><strong>When to use Scan, Query or GetItem?</strong></h4><p>There is a great schema that summarizes the answer in this blog: <a href="https://dynobase.dev/dynamodb-scan-vs-query/">https://dynobase.dev/dynamodb-scan-vs-query/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*bXJgSRbt5sQluH090-V8_w.png" /></figure><p>Since the Delete command requires Composite Primary Key (Partition Key + Sort Key) and the desire is to delete all the records <strong>with a Partition Key</strong> it’s necessary to first collect the Sort Key values using a <strong>Query </strong>command.</p><blockquote>- PrimaryKey: known</blockquote><blockquote>- SortKey: unknown</blockquote><blockquote>Use <strong>Query</strong> to collect sortKeys</blockquote><blockquote>Delete records with composite primary key (primitiveKey + sortKey)</blockquote><p>I have created a table named ExampleTable in local with partition and sort keys as a primary key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*AOj0Gkk3d30qgZ3q1mK8dg.png" /><figcaption>Metadata</figcaption></figure><p>Next, populate the table with 10 records and three different partition keys, each having a varying number of records distinguished by different sortKey values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*IQsKtzRSIAVqnSKyxSyanQ.png" /><figcaption>Initial state of the table</figcaption></figure><p>Here is the code to delete records when only Partition Key is known and Sort Keys are unknown:</p><pre>const { DynamoDBClient, QueryCommand, DeleteItemCommand } = require(&#39;@aws-sdk/client-dynamodb&#39;);<br>const logger = require(&#39;./logger&#39;)<br>require(&#39;dotenv&#39;).config();<br><br>const client = new DynamoDBClient({<br>  region: process.env.REGION,<br>  credentials: {<br>    accessKeyId: process.env.ACCESS_KEY_ID,<br>    secretAccessKey: process.env.SECRET_ACCESS_KEY<br>  },<br>  endpoint: &#39;http://localhost:8001&#39; // for local<br>});<br><br>const tableName = process.env.TABLE_NAME<br>const partitionKeyName = process.env.PARTITION_KEY_NAME;<br>const sortKeyName = process.env.SORT_KEY_NAME;<br><br>async function getSortKeyValues(partitionKeyValue) {<br>  logger.info(`${tableName}-dynamodb -- Retrieving sortKeys with partitionKey: ${partitionKeyValue}`);<br>  const params = {<br>    TableName: tableName,<br>    ProjectionExpression: sortKeyName,<br>    KeyConditionExpression: `${partitionKeyName} = :value`,<br>    ExpressionAttributeValues: {<br>      &#39;:value&#39;: { S: partitionKeyValue }<br>    },<br>  };<br><br>  const command = new QueryCommand(params);<br>  const response = await client.send(command);<br><br>  const sortKeyValues = response.Items.map((item) =&gt; item[sortKeyName].S);<br><br>  return sortKeyValues;<br>}<br><br>async function deleteRecords(partitionKeyValues) {<br>  let totalDeletedRecords = 0;<br><br>  for (let i = 0; i &lt; partitionKeyValues.length; i++) {<br>    const partitionKeyValue = partitionKeyValues[i];<br><br>    const sortKeyValues = await getSortKeyValues(partitionKeyValue);<br><br>    for (const sortKeyValue of sortKeyValues) {<br>      logger.info(`${tableName}-dynamodb -- Deleting record with partitionKey: ${partitionKeyValue}, sortKey: ${sortKeyValue}`);<br><br>      const params = {<br>        TableName: tableName,<br>        Key: {<br>          [partitionKeyName]: { S: partitionKeyValue },<br>          [sortKeyName]: { S: sortKeyValue }<br>        },<br>      };<br><br>      const command = new DeleteItemCommand(params);<br>      await client.send(command);<br><br>      totalDeletedRecords++;<br>      logger.info(`${tableName}-dynamodb -- Deleted record with partitionKey: ${partitionKeyValue}, sortKey: ${sortKeyValue}`);<br>    }<br>  }<br><br>  logger.info(`${tableName}-dynamodb -- Total deleted records: ${totalDeletedRecords}`);<br>  return totalDeletedRecords;<br>}<br><br>async function executeDynamoDBDeletionWithPartitionList(partitionKeyList) {<br>  let totalDeletedRecords = 0;<br>  try {<br>    totalDeletedRecords = await deleteRecords(partitionKeyList);<br>  } catch (error) {<br>    logger.error(tableName + &#39;-dynamodb -- An error occurred: &#39; + error);<br>  }<br><br>  return [{<br>    table: tableName,<br>    deletedRecords: totalDeletedRecords<br>  }];<br>}<br><br>module.exports = executeDynamoDBDeletionWithPartitionList;</pre><p><strong>ProjectionExpression: </strong>this parameter is used to define the fields we want the Query command to retrieve. The Query command will retrieve all attributes of the record by default, if not specified.</p><p><strong>KeyConditionExpression:</strong> this parameter is used to specify the key value of the records which the Query command will retrieve.</p><p><strong>ExpressionAttributeValues: </strong>this parameter is used to replace the defined placeholder with the values of the attribute want them to be compared at runtime. In another words, it maps the “<strong>:value</strong>” placeholder to the value stored in the <strong>partitionKeyValue </strong>variable.</p><p>In the master code the <strong>deleteRecordsWithUnknownSortKey </strong>method is called by providing a list of Partition Keys to be deleted.</p><pre>const deleteRecordsWithUnknownSortKey = require(&#39;./delete-ExampleTable-dynamodb&#39;);<br>const partitionKeyValuesToBeDeleted = [&#39;partitionKey2&#39;, &#39;partitionKey3&#39;];<br>deleteRecordsWithUnknownSortKey(partitionKeyValuesToBeDeleted);</pre><p>These logs show that the code collects Sort Keys for each Partition Key and then uses both the provided Partition Key and the queried Sort Keys as a primary key to delete records one by one.</p><pre>PS C:\Users\yusuf.aydin\Dev\dynamodb&gt; node main.js<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Retrieving sortKeys with partitionKey: partitionKey2&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting record with partitionKey: partitionKey2, sortKey: sortKey2&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted record with partitionKey: partitionKey2, sortKey: sortKey2&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting record with partitionKey: partitionKey2, sortKey: sortKey21&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted record with partitionKey: partitionKey2, sortKey: sortKey21&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting record with partitionKey: partitionKey2, sortKey: sortKey22&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted record with partitionKey: partitionKey2, sortKey: sortKey22&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting record with partitionKey: partitionKey2, sortKey: sortKey23&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted record with partitionKey: partitionKey2, sortKey: sortKey23&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Retrieving sortKeys with partitionKey: partitionKey3&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting record with partitionKey: partitionKey3, sortKey: sortKey3&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted record with partitionKey: partitionKey3, sortKey: sortKey3&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting record with partitionKey: partitionKey3, sortKey: sortKey31&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted record with partitionKey: partitionKey3, sortKey: sortKey31&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting record with partitionKey: partitionKey3, sortKey: sortKey32&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted record with partitionKey: partitionKey3, sortKey: sortKey32&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleting record with partitionKey: partitionKey3, sortKey: sortKey33&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Deleted record with partitionKey: partitionKey3, sortKey: sortKey33&quot;}<br>{&quot;level&quot;:&quot;info&quot;,&quot;message&quot;:&quot;ExampleTable-dynamodb -- Total deleted records: 8&quot;}</pre><p>The table after the deletion looks like the image below. All records under “partitionKey2” and “partitionKey3” are deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*ZOQ8zJTYFwGfhBBJoAbD8g.png" /><figcaption>Status of the table after deletion</figcaption></figure><h4><strong>Dependencies and logger configuration:</strong></h4><p>The dependencies are:</p><ul><li><strong>@aws-sdk/client-dynamodb</strong>: AWS SDK</li><li><strong>dotenv</strong>: to read env variables</li><li><strong>winston</strong>: for the logger</li></ul><pre>  &quot;dependencies&quot;: {<br>    &quot;@aws-sdk/client-dynamodb&quot;: &quot;^3.405.0&quot;,<br>    &quot;dotenv&quot;: &quot;^16.3.1&quot;,<br>    &quot;winston&quot;: &quot;^3.10.0&quot;<br>  }</pre><p><strong>.env:</strong></p><pre>REGION=<br>ACCESS_KEY_ID=<br>SECRET_ACCESS_KEY=<br>TABLE_NAME=&quot;ExampleTable&quot;<br>PARTITION_KEY_NAME=&quot;partitionKey&quot;<br>SORT_KEY_NAME=&quot;sortKey&quot;</pre><p>The logger saves the entire log into a file with a timestamp.</p><p><strong>logger.js:</strong></p><pre>const { createLogger, format, transports } = require(&#39;winston&#39;);<br><br>const timestamp = new Date().toISOString();<br>const logFilename = `logfile_${timestamp.replaceAll(&#39;:&#39;, &#39;-&#39;,)}.txt`;<br><br>module.exports  = createLogger({<br>    level: &#39;info&#39;,<br>    <br>    format: format.json(<br>      format.timestamp(),<br>      format.printf(({ level, message, timestamp }) =&gt; {<br>        return `[${timestamp}] [${level.toUpperCase()}] - ${message}`;<br>      })<br>    ),<br>    transports: [new transports.Console(), <br>      new transports.File({<br>        filename: logFilename,<br>        format: format.combine(<br>          format.timestamp({<br>            format: &quot;YYYY-MM-DD HH:mm:ss&quot;,<br>          }),<br>          format.json()<br>        ),<br>      }),]<br>  });</pre><h4>Resources:</h4><ul><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html">Query</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html">Scan</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html">Condition expressions</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeValues.html">Expression attribute values</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ProjectionExpressions.html">Projection expressions</a></li><li><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.KeyConditions.html">KeyConditions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b533c9ea2f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algoritmik Yanlılık]]></title>
            <link>https://medium.com/@aydinya/algoritmik-yanl%C4%B1l%C4%B1k-800c9ce4beab?source=rss-e4b79b6cef21------2</link>
            <guid isPermaLink="false">https://medium.com/p/800c9ce4beab</guid>
            <category><![CDATA[algoritma]]></category>
            <category><![CDATA[önyargı]]></category>
            <category><![CDATA[algorithmic-bias]]></category>
            <category><![CDATA[ethnocentrism]]></category>
            <dc:creator><![CDATA[Yusuf Alptuğ Aydın]]></dc:creator>
            <pubDate>Mon, 19 Oct 2020 23:13:43 GMT</pubDate>
            <atom:updated>2020-10-19T23:13:43.031Z</atom:updated>
            <content:encoded><![CDATA[<h3>Algoritmik Yanlılık Nedir? Örnekleri ve Sakıncaları Nelerdir?</h3><p>(“Bias” kelimesi de “prejudice” gibi Türkçe’ye “önyargı” olarak çevirildiği ve tam olarak aynı anlamı karşılamadığı için “bias” yerine “<strong>yanlılık</strong>” kelimesini kullanmayı tercih ettim.)</p><p>Algoritmik yanlılık, tasarımı gereği sistematik ve tekrar eden ayrıcalıklı, dışlayıcı veya adaletsiz sonuçlar üreten algoritmaları tanımlayan bir kavram. Bu taraftarlık, hatalı tasarım sonucu alakasız parametrelere olması gerekenden fazla dayanan sonuçlardan kaynaklanabileceği gibi doğrudan geliştiricinin kendi bakış açısından da kaynaklanabilir. Örnek vermek gerekirse banka kredisi algoritmasında “ailedeki çocuk sayısı” gibi bir kriterin “sabit gelir” kriterine göre daha belirleyici olması istenen kararların hatalı veya adaletsiz alınmasına sebep olabilir.</p><p>Algoritmalar insanlar tarafından üretildiği için doğrudan geliştiricilerinin bulunduğu kültürel, sosyal konumu yansıtabilir. İnsanlar tarafından alınan bir takım kararları bilgisayar programlarına yükleyen yapay zeka uygulamalarında, programların geliştircilerinin etnik merkezci yaklaşımları ve kollektif narsisizm sonucu sahip oldukları kültürel yanlılıklarının (cultural bias) etkin olması, yapay zekanın alacağı kararları aynı bakış açısıyla alması anlamına gelir. Karşılaştığımız algoritmik yanlılık örnekleri, makine öğrenmesi modellerinin eğitildiği veri setlerinin yeterince çeşitliliğe sahip olmamasından kaynaklanır.</p><h3>Algoritmik yanlılığa bazı örnekler</h3><p>● IBM, Microsoft ve Face++ şirketlerinin coğrafi bölgelere göre cinsiyet sınıflandırması yapan bilgisayarlı görülü yapay zeka ürünleri için yapılan testler sonucunda her üç ürün de erkeklerde kadınlara kıyasla 8.1% ile 20.6% arasında değişen oranlarda daha iyi sonuçlar verdi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*mGWqze-bMY0-IPUoPvPMog.png" /></figure><p>Aynı şekilde her üç şirketin ürünü de açık tenli kişilerde koyu tenli kişilere kıyasla 11.8% ile 19.2% arasında değişen oranlarda daha iyi sonuçlar verdi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*Rd-NCn8XeWoFPkohALGc3Q.png" /></figure><p>IBM’in geliştirdiği ürün koyu ten rengine sahip kadınlarla, açık ten rengine sahip erkekler arasındaki hata oranı farkı 34.4%.</p><p><strong>Microsoft ürününün hatalı etiketlediği kişilerin 93.6%’sı koyu tenli olan kişilerden oluşuyor.</strong></p><p><strong>Face++ ürününün hatalı etiketlediği kişilerin 95.6%’sı ise kadınlardan oluşuyor.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0ZQZRqoJ6VinS8bamRPEQ.png" /></figure><p><a href="http://gendershades.org/overview.html">[L]</a></p><p>● 2015 senesinde Google, Google Photos uygulamasının siyahi kişilerin fotoğraflarını goriller isimli albümde kategorilediği için özür dilemişti ve hızlı önlem olarak goril,şempanze,maymun ve benzeri etiketleri bloklayarak çözüm üretmişti.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qfsw1mFiRLjh98XeOJZYNw.png" /></figure><p><a href="https://www.theguardian.com/technology/2018/jan/12/google-racism-ban-gorilla-black-people">[L]</a></p><p>● Google Translate, sahip olduğu önyargılı hata düzeltilmeden önce Türkçe,Fince gibi cinsiyet belirsiz özneli cümleler içeren dillerden yapılan bazı çevirilerde belirli meslekleri cinsiyetlere göre sınıflandırıyordu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*HWjLDClU7QMucS3fUzcVcw.jpeg" /></figure><p><a href="https://www.independent.co.uk/life-style/women/google-translate-sexist-masculine-feminine-he-said-she-said-english-spanish-languages-a8672586.html">[L]</a></p><p>● Amazon işe alım için kullandığı geçmiş özgeçmişlerle beslenen uygulamasının erkek çoğunluklu veri setine dayanarak erkeklerin daha tercih edilesi olduğu kanısına varan ve içeriğinde adayın erkek olduğuna dair kelimeler bulamadığı özgeçmişleri eleyerek cinsiyetçi kararlar aldığı ortaya çıkan uygulamayı sonlandırmıştı.</p><p><a href="https://www.theguardian.com/technology/2018/oct/10/amazon-hiring-ai-gender-bias-recruiting-engine">[L]</a></p><p>● LinkedIn üzerinden Amerika’da kullanılan onlarca yaygın kadın kadın ismiyle yapılan aramalarda LinkedIn öneri algoritmasının aranan ismin fonetik olarak erkek ismi benzerini önerdiğini fakat en yaygın 100 erkek ismi ile yapılan aramalarda bir kadın ismi önererek “aradığınız isim bu mu?” sorusunu sormadığı iddia edildi.</p><p><a href="https://www.seattletimes.com/business/microsoft/how-linkedins-search-engine-may-reflect-a-bias/">[L]</a></p><p>● 2009 yılında, Nikon kameralarına gelen göz kırpma özelliğinin asyalılarda sürekli göz kırpması algılaması algoritmik yanlılığın tartışıldığı ilk örneklerinden biri.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*pTA0YDEWM7aQ61G6_LtxUg.jpeg" /></figure><p><a href="http://content.time.com/time/business/article/0,8599,1954643-1,00.html">[L]</a></p><h3>Önyargıya başka bir örnek</h3><p>ABD’de kullanılan COMPAS isimli bir yazılımın öngörme bileşenlerinden “bir suçlunun mahkumiyetinin ardından 2 yıl içerisinde tekrar suç işleyip işlemeyeceği” özelliğinin performansına dair bir analiz yapıldı. <a href="https://www.theatlantic.com/technology/archive/2018/01/equivant-compas-algorithm/550646/">[L]</a></p><p>Yapılan analizlerde, hem gönüllü insanlara hem de yazılıma yapılan sunulan veriler sonucunda, insanların kararlarındaki yanlış pozitif oranı siyah sanıklarda 37% iken beyaz sanıklarda 27% ve çok yakın bir şekilde COMPAS’dan gelen sonuçlarda ise yanlış pozitif oranı siyah sanıklarda 40% iken beyaz sanıklarda 30% olarak çıkmış.</p><p>Algoritmik yanlılık, geliştirilen ürünlerde bir cinsiyete veya etnik gruba karşı ayrımcılık yapmasının yanında insanların hayatı için de tehlike arz edebilir. ATM’lerde ve kapalı güvenlik kameralarında bilgisayarlı görü, aranan suçluların veya potansiyel suçların tespitinde kullanılmaya başlandı bile. Yüz tanıma ve eşleştirme sistemlerine havalimanları, konser veya miting alanları gibi kitlerleri hedef alan saldırıların olası olduğu yerlerde sistemin örneklerini gördüğümüz hataları yüzünden başarısızlığı insan hayatına mal olabilir.</p><p>Çoğunlukla bilgisayarlı görü kullanan yapay zeka uygulamalarında denk geldiğimiz algoritmik yanlılığın, bu uygulamaların yer aldığı her alanda olabileceği öngörüsüyle gelecekte; otonom araçlarda veya suçlu tespitinde/müdahalesinde oluşabilecek telafisi mümkün olmayan hataların önlenmesi için bu konuda duyarlı olmak geliştiriclerin önemli bir sorumluluğu.</p><h3>İlgili kaynaklar</h3><p><a href="https://en.wikipedia.org/wiki/Algorithmic_bias">https://en.wikipedia.org/wiki/Algorithmic_bias</a></p><p><a href="http://gendershades.org/overview.html">http://gendershades.org/overview.html</a></p><ul><li><a href="https://www.ajl.org/">Algorithmic Justice League - Unmasking AI harms and biases</a></li><li><a href="https://www.theguardian.com/technology/2018/jan/12/google-racism-ban-gorilla-black-people">Google&#39;s solution to accidental algorithmic racism: ban gorillas</a></li><li><a href="https://www.independent.co.uk/life-style/women/google-translate-sexist-masculine-feminine-he-said-she-said-english-spanish-languages-a8672586.html">Google fixes Translate tool after accusations of sexism</a></li><li><a href="https://www.theguardian.com/technology/2018/oct/10/amazon-hiring-ai-gender-bias-recruiting-engine">Amazon ditched AI recruiting tool that favored men for technical jobs</a></li><li><a href="https://www.seattletimes.com/business/microsoft/how-linkedins-search-engine-may-reflect-a-bias/">How LinkedIn&#39;s search engine may reflect a gender bias</a></li><li><a href="http://content.time.com/time/business/article/0,8599,1954643-1,00.html">Breaking News, Analysis, Politics, Blogs, News Photos, Video, Tech Reviews - TIME.com</a></li><li><a href="https://www.theatlantic.com/technology/archive/2018/01/equivant-compas-algorithm/550646/">A Popular Algorithm Is No Better at Predicting Crimes Than Random People</a></li><li><a href="https://tr.euronews.com/2020/03/08/yapay-zekanin-cinsiyetciligi-kadin-elinden-cikan-algoritmalar-kadinlara-kars-ayrimcilik-ya">Yapay zekanın cinsiyetçiliği: Algoritmalar ayrımcılığa yol açıyor mu?</a></li><li><a href="https://sendika63.org/2016/10/bilgisayarlar-insan-dillerini-ogrendiklerinde-insan-onyargilarini-da-ogreniyorlar-christopher-groskopf-379884/">Bilgisayarlar insan dillerini öğrendiklerinde insan önyargılarını da öğreniyorlar - Christopher Groskopf</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FbWOUw8omUVg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DbWOUw8omUVg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FbWOUw8omUVg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa4e7a6e8a0b520fa3ce008f4be28caf/href">https://medium.com/media/aa4e7a6e8a0b520fa3ce008f4be28caf/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUG_X_7g63rY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUG_X_7g63rY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FUG_X_7g63rY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa767e52fb79a00b4765820f1f84f3dd/href">https://medium.com/media/fa767e52fb79a00b4765820f1f84f3dd/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=800c9ce4beab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>