

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# Verwenden von Time to Live (TTL) in DynamoDB
<a name="TTL"></a>

Time To Live (TTL) für DynamoDB ist eine kosteneffiziente Methode zum Löschen von Elementen, die nicht mehr relevant sind. TTL ermöglicht es Ihnen, einen Ablaufzeitstempel pro Element zu definieren, um festzulegen, wann ein Element nicht mehr benötigt wird. DynamoDB löscht abgelaufene Elemente automatisch innerhalb weniger Tage nach ihrem Ablauftermin, ohne dass dafür Schreibdurchsatz verbraucht wird. 

Um TTL zu verwenden, aktivieren Sie es zunächst in einer Tabelle. Definieren Sie dann ein bestimmtes Attribut zum Speichern des TTL-Ablaufzeitstempels. Der Zeitstempel muss als Datentyp [Zahl](HowItWorks.NamingRulesDataTypes.md#HowItWorks.DataTypes) im [Unix-Epochenzeitformat](https://en.wikipedia.org/wiki/Unix_time) mit der Granularität Sekunden gespeichert werden. Elemente mit einem TTL-Attribut, das kein Zahlentyp ist, werden vom TTL-Prozess ignoriert. Immer, wenn ein Element erstellt oder aktualisiert wird, können Sie die Ablaufzeit berechnen und sie im TTL-Attribut speichern.

Elemente mit gültigen, abgelaufenen TTL-Attributen können vom System jederzeit gelöscht werden. In der Regel geschieht das innerhalb weniger Tage nach ihrem Ablauf. Sie können die abgelaufenen Elemente, deren Löschung noch aussteht, weiterhin aktualisieren. Dazu gehören auch das Ändern oder Entfernen ihrer TTL-Attribute. Wenn Sie ein abgelaufenes Element aktualisieren, empfiehlt es sich, einen Bedingungsausdruck zu verwenden, um sicherzustellen, dass das Element anschließend nicht gelöscht wurde. Verwenden Sie Filterausdrücke, um abgelaufene Elemente aus [Scan](Scan.md#Scan.FilterExpression)- und [Abfrageergebnissen](Query.FilterExpression.md) zu entfernen.

Gelöschte Elemente funktionieren ähnlich wie Objekte, die bei typischen Löschvorgängen gelöscht wurden. Nach dem Löschen fließen Elemente als Servicelöschungen statt als Benutzerlöschungen in DynamoDB Streams ein und werden wie andere Löschvorgänge aus lokalen und globalen sekundären Indizes entfernt. 

Wenn Sie [Version 2019.11.21 der globalen Tabellen (aktuell)](GlobalTables.md) und außerdem die TTL-Funktion verwenden, repliziert DynamoDB TTL-Löschungen in alle Replikattabellen. Die anfängliche TTL-Löschung verbraucht keine Schreibkapazitätseinheiten (WCU) in der Region, in der die TTL abläuft. Die in die Replikattabellen replizierte TTL-Löschung verbraucht jedoch in jeder Region mit einem Replikat bei Verwendung bereitgestellter Kapazität eine Einheit für replizierte Schreibkapazität bzw. bei Verwendung von On-Demand-Kapazität eine replizierte Schreibeinheit. Dafür werden die entsprechenden Gebühren berechnet.

Weitere Informationen zu TTL finden Sie in den folgenden Themen:

**Topics**
+ [Aktivieren von Time to Live (TTL) in DynamoDB](time-to-live-ttl-how-to.md)
+ [Berechnen der Time to Live (TTL) in DynamoDB](time-to-live-ttl-before-you-start.md)
+ [Arbeiten mit abgelaufenen Elementen und Time to Live (TTL)](ttl-expired-items.md)

# Aktivieren von Time to Live (TTL) in DynamoDB
<a name="time-to-live-ttl-how-to"></a>

**Anmerkung**  
Um das Debugging und die Verifizierung des ordnungsgemäßen Betriebs der TTL-Funktion zu erleichtern, werden die Werte für die Element-TTL in DynamoDB-Diagnoseprotokollen in Klartext angegeben.

Sie können TTL in der Amazon DynamoDB DynamoDB-Konsole, der AWS Command Line Interface (AWS CLI), oder mithilfe der [Amazon DynamoDB DynamoDB-API-Referenz](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/) mit einer der angegebenen Optionen aktivieren. AWS SDKs Es dauert ungefähr eine Stunde, um TTL auf allen Partitionen zu aktivieren.

## DynamoDB TTL über die Konsole aktivieren AWS
<a name="time-to-live-ttl-how-to-enable-console"></a>

1. Melden Sie sich bei der an AWS-Managementkonsole und öffnen Sie die DynamoDB-Konsole unter. [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/)

1. Wählen Sie **Tabellen** und anschließend die Tabelle aus, die Sie ändern möchten.

1. Wählen Sie auf der Registerkarte **Zusätzliche Einstellungen** im Abschnitt **Time to Live (TTL)** die Option **Einschalten** aus, um TTL zu aktivieren.

1. Wenn Sie TTL für eine Tabelle aktivieren, müssen Sie bei DynamoDB einen bestimmten Attributnamen angeben, nach dem der Service sucht, wenn bestimmt wird, ob der Ablauf eines Elements veranlasst werden soll. Beim Namen des TTL-Attributs (siehe unten) wird zwischen Groß- und Kleinschreibung unterschieden. Außerdem muss er mit dem in Ihren Lese- und Schreibvorgängen definierten Attribut übereinstimmen. Andernfalls werden abgelaufene Elemente nicht gelöscht. Um das TTL-Attribut umzubenennen, müssen Sie TTL zunächst deaktivieren und dann mit dem neuen Attribut aktivieren. TTL verarbeitet Löschungen etwa 30 Minuten lang weiter, nachdem es deaktiviert wurde. Bei wiederhergestellten Tabellen muss TTL neu konfiguriert werden.  
![\[TTL-Attributname mit Berücksichtigung von Groß- und Kleinschreibung, anhand dessen DynamoDB bestimmt, ob ein Element abläuft.\]](http://docs.aws.amazon.com/de_de/amazondynamodb/latest/developerguide/images/EnableTTL-Settings.png)

1. (Optional) Sie können einen Test durchführen, indem Sie Datum und Uhrzeit des Ablaufs simulieren und einige Elemente abgleichen. Dadurch erhalten Sie eine Beispielliste mit Elementen, die bestätigt, dass es Elemente mit dem angegebenen TTL-Attributnamen und der Ablaufzeit gibt.

Nachdem TTL aktiviert wurde, wird das TTL-Attribut mit **TTL** gekennzeichnet, wenn Sie Elemente in der DynamoDB-Konsole ansehen. Sie können den Termin anzeigen, an dem ein Element abläuft, indem Sie mit dem Mauszeiger über das Attribut fahren. 

## Aktivieren von DynamoDB TTL mithilfe der API
<a name="time-to-live-ttl-how-to-enable-api"></a>

------
#### [ Python ]

Sie können TTL mithilfe des Vorgangs mit Code aktivieren. [UpdateTimeToLive](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/update_time_to_live.html)

```
import boto3


def enable_ttl(table_name, ttl_attribute_name):
    """
    Enables TTL on DynamoDB table for a given attribute name
        on success, returns a status code of 200
        on error, throws an exception

    :param table_name: Name of the DynamoDB table
    :param ttl_attribute_name: The name of the TTL attribute being provided to the table.
    """
    try:
        dynamodb = boto3.client('dynamodb')

        # Enable TTL on an existing DynamoDB table
        response = dynamodb.update_time_to_live(
            TableName=table_name,
            TimeToLiveSpecification={
                'Enabled': True,
                'AttributeName': ttl_attribute_name
            }
        )

        # In the returned response, check for a successful status code.
        if response['ResponseMetadata']['HTTPStatusCode'] == 200:
            print("TTL has been enabled successfully.")
        else:
            print(f"Failed to enable TTL, status code {response['ResponseMetadata']['HTTPStatusCode']}")
    except Exception as ex:
        print("Couldn't enable TTL in table %s. Here's why: %s" % (table_name, ex))
        raise


# your values
enable_ttl('your-table-name', 'expirationDate')
```

Sie können überprüfen, ob TTL aktiviert ist, indem Sie den [DescribeTimeToLive](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/describe_time_to_live.html)Vorgang verwenden, der den TTL-Status in einer Tabelle beschreibt. Der `TimeToLive`-Status ist entweder `ENABLED` oder `DISABLED`.

```
# create a DynamoDB client
dynamodb = boto3.client('dynamodb')

# set the table name
table_name = 'YourTable'

# describe TTL
response = dynamodb.describe_time_to_live(TableName=table_name)
```

------
#### [ JavaScript ]

Sie können TTL mithilfe des Vorgangs mit Code aktivieren. [UpdateTimeToLiveCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-dynamodb/Class/UpdateTimeToLiveCommand/)

```
import { DynamoDBClient, UpdateTimeToLiveCommand } from "@aws-sdk/client-dynamodb";

const enableTTL = async (tableName, ttlAttribute) => {

    const client = new DynamoDBClient({});

    const params = {
        TableName: tableName,
        TimeToLiveSpecification: {
            Enabled: true,
            AttributeName: ttlAttribute
        }
    };

    try {
        const response = await client.send(new UpdateTimeToLiveCommand(params));
        if (response.$metadata.httpStatusCode === 200) {
            console.log(`TTL enabled successfully for table ${tableName}, using attribute name ${ttlAttribute}.`);
        } else {
            console.log(`Failed to enable TTL for table ${tableName}, response object: ${response}`);
        }
        return response;
    } catch (e) {
        console.error(`Error enabling TTL: ${e}`);
        throw e;
    }
};

// call with your own values
enableTTL('ExampleTable', 'exampleTtlAttribute');
```

------

## Aktivieren Sie Time to Live mit dem AWS CLI
<a name="time-to-live-ttl-how-to-enable-cli-sdk"></a>

1. Aktivieren Sie TTL in der `TTLExample`-Tabelle.

   ```
   aws dynamodb update-time-to-live --table-name TTLExample --time-to-live-specification "Enabled=true, AttributeName=ttl"
   ```

1. Beschreiben Sie TTL in der `TTLExample`-Tabelle.

   ```
   aws dynamodb describe-time-to-live --table-name TTLExample
   {
       "TimeToLiveDescription": {
           "AttributeName": "ttl",
           "TimeToLiveStatus": "ENABLED"
       }
   }
   ```

1. Fügen Sie der `TTLExample`-Tabelle mit dem Time-to-Live-Attributsatz ein Element mit der BASH-Shell und AWS CLI hinzu: 

   ```
   EXP=`date -d '+5 days' +%s`
   aws dynamodb put-item --table-name "TTLExample" --item '{"id": {"N": "1"}, "ttl": {"N": "'$EXP'"}}'
   ```

In diesem Beispiel wurde mit dem aktuellen Datum begonnen und es wurden 5 Tage hinzugefügt, um ein Ablaufdatum zu erstellen. Anschließend wird das Ablaufdatum in ein Epoch-Zeitformat umgewandelt, um der Tabelle "`TTLExample`" ein Element hinzuzufügen. 

**Anmerkung**  
 Eine Möglichkeit, Ablaufwerte für Time to Live festzulegen, besteht darin, die Anzahl von Sekunden zu berechnen, die dem Ablaufdatum hinzugefügt werden. Beispielsweise sind 5 Tage 432.000 Sekunden. Es ist jedoch häufig besser, mit einem Datum zu beginnen und dieses als Ausgangspunkt zu nehmen.

Es ist relativ einfach, die aktuelle Zeit im Epoch-Zeitformat zu erhalten, wie in folgenden Beispielen veranschaulicht.
+ Linux-Terminal: `date +%s`
+ Python: `import time; int(time.time())`
+ Java: `System.currentTimeMillis() / 1000L`
+ JavaScript: `Math.floor(Date.now() / 1000)`

## Aktivieren Sie DynamoDB TTL mit CloudFormation
<a name="time-to-live-ttl-how-to-enable-cf"></a>

```
AWSTemplateFormatVersion: "2010-09-09"
Resources:
  TTLExampleTable:
    Type: AWS::DynamoDB::Table
    Description: "A DynamoDB table with TTL Specification enabled"
    Properties:
      AttributeDefinitions:
        - AttributeName: "Album"
          AttributeType: "S"
        - AttributeName: "Artist"
          AttributeType: "S"
      KeySchema:
        - AttributeName: "Album"
          KeyType: "HASH"
        - AttributeName: "Artist"
          KeyType: "RANGE"
      ProvisionedThroughput:
        ReadCapacityUnits: "5"
        WriteCapacityUnits: "5"
      TimeToLiveSpecification:
        AttributeName: "TTLExampleAttribute"
        Enabled: true
```

[Weitere Informationen zur Verwendung von TTL in Ihren CloudFormation Vorlagen finden Sie hier.](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-table-timetolivespecification.html)

# Berechnen der Time to Live (TTL) in DynamoDB
<a name="time-to-live-ttl-before-you-start"></a>

Eine gängige Methode zur Implementierung von TTL besteht darin, eine Ablaufzeit für Elemente festzulegen, die auf dem Erstellungs- oder letzten Aktualisierungsdatum basiert. Dies kann durch Hinzufügen von Zeit zu den Zeitstempeln `createdAt` und `updatedAt` erreicht werden. Beispielsweise kann die TTL für neu erstellte Elemente auf `createdAt` \$1 90 Tage festgelegt werden. Wenn das Element aktualisiert wird, kann die TTL mit `updatedAt` \$1 90 Tage neu berechnet werden.

Die berechnete Ablaufzeit muss im Unix-Format in Sekunden angegeben werden. Damit Elemente für Ablauf und Löschung infrage kommen, darf die TTL nicht länger als fünf Jahre zurückliegen. Wenn Sie ein anderes Format verwenden, ignorieren die TTL-Prozesse das Element. Wenn Sie die Ablaufzeit auf einen Zeitpunkt in der future festlegen, an dem der Artikel ablaufen soll, läuft der Artikel nach dieser Zeit ab. Angenommen, Sie haben die Ablaufzeit auf 1724241326 festgelegt (das ist Montag, 21. August 2024 11:55:26 (UTC)). Der Artikel läuft nach der angegebenen Zeit ab. Es gibt keine TTL-Mindestdauer. Sie können die Ablaufzeit auf einen beliebigen Zeitpunkt in der future festlegen, z. B. auf 5 Minuten ab der aktuellen Uhrzeit. DynamoDB löscht abgelaufene Elemente jedoch in der Regel innerhalb von 48 Stunden nach deren Ablauf, nicht sofort, wenn der Artikel abläuft.

**Topics**
+ [Erstellen eines Elements und Festlegen der Time to Live](#time-to-live-ttl-before-you-start-create)
+ [Aktualisieren eines Elements und der Time to Live](#time-to-live-ttl-before-you-start-update)

## Erstellen eines Elements und Festlegen der Time to Live
<a name="time-to-live-ttl-before-you-start-create"></a>

Das folgende Beispiel zeigt, wie die Ablaufzeit berechnet wird, wenn ein neues Element erstellt wird. Dabei wird `expireAt` als TTL-Attributname verwendet. Eine Zuweisungsanweisung ruft die aktuelle Uhrzeit als Variable ab. In diesem Beispiel wird die Ablaufzeit als 90 Tage ab der aktuellen Uhrzeit berechnet. Die Zeit wird dann in das Unix-Format umgewandelt und als Ganzzahl-Datentyp im TTL-Attribut gespeichert.

Die folgenden Codebeispiele veranschaulichen, wie Sie ein Element mit TTL erstellen.

------
#### [ Java ]

**SDK für Java 2.x**  

```
package com.amazon.samplelib.ttl;

import com.amazon.samplelib.CodeSampleUtils;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Creates an item in a DynamoDB table with TTL attributes.
 * This class demonstrates how to add TTL expiration timestamps to DynamoDB items.
 */
public class CreateTTL {

    private static final String USAGE =
        """
            Usage:
                <tableName> <primaryKey> <sortKey> <region>
            Where:
                tableName - The Amazon DynamoDB table being queried.
                primaryKey - The name of the primary key. Also known as the hash or partition key.
                sortKey - The name of the sort key. Also known as the range attribute.
                region (optional) - The AWS region that the Amazon DynamoDB table is located in. (Default: us-east-1)
            """;
    private static final int DAYS_TO_EXPIRE = 90;
    private static final int SECONDS_PER_DAY = 24 * 60 * 60;
    private static final String PRIMARY_KEY_ATTR = "primaryKey";
    private static final String SORT_KEY_ATTR = "sortKey";
    private static final String CREATION_DATE_ATTR = "creationDate";
    private static final String EXPIRE_AT_ATTR = "expireAt";
    private static final String SUCCESS_MESSAGE = "%s PutItem operation with TTL successful.";
    private static final String TABLE_NOT_FOUND_ERROR = "Error: The Amazon DynamoDB table \"%s\" can't be found.";

    private final DynamoDbClient dynamoDbClient;

    /**
     * Constructs a CreateTTL instance with the specified DynamoDB client.
     *
     * @param dynamoDbClient The DynamoDB client to use
     */
    public CreateTTL(final DynamoDbClient dynamoDbClient) {
        this.dynamoDbClient = dynamoDbClient;
    }

    /**
     * Constructs a CreateTTL with a default DynamoDB client.
     */
    public CreateTTL() {
        this.dynamoDbClient = null;
    }

    /**
     * Main method to demonstrate creating an item with TTL.
     *
     * @param args Command line arguments
     */
    public static void main(final String[] args) {
        try {
            int result = new CreateTTL().processArgs(args);
            System.exit(result);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    /**
     * Process command line arguments and create an item with TTL.
     *
     * @param args Command line arguments
     * @return 0 if successful, non-zero otherwise
     * @throws ResourceNotFoundException If the table doesn't exist
     * @throws DynamoDbException If an error occurs during the operation
     * @throws IllegalArgumentException If arguments are invalid
     */
    public int processArgs(final String[] args) {
        // Argument validation (remove or replace this line when reusing this code)
        CodeSampleUtils.validateArgs(args, new int[] {3, 4}, USAGE);

        final String tableName = args[0];
        final String primaryKey = args[1];
        final String sortKey = args[2];
        final Region region = Optional.ofNullable(args.length > 3 ? args[3] : null)
            .map(Region::of)
            .orElse(Region.US_EAST_1);

        try (DynamoDbClient ddb = dynamoDbClient != null
            ? dynamoDbClient
            : DynamoDbClient.builder().region(region).build()) {
            final CreateTTL createTTL = new CreateTTL(ddb);
            createTTL.createItemWithTTL(tableName, primaryKey, sortKey);
            return 0;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * Creates an item in the specified table with TTL attributes.
     *
     * @param tableName The name of the table
     * @param primaryKeyValue The value for the primary key
     * @param sortKeyValue The value for the sort key
     * @return The response from the PutItem operation
     * @throws ResourceNotFoundException If the table doesn't exist
     * @throws DynamoDbException If an error occurs during the operation
     */
    public PutItemResponse createItemWithTTL(
        final String tableName, final String primaryKeyValue, final String sortKeyValue) {
        // Get current time in epoch second format
        final long createDate = System.currentTimeMillis() / 1000;

        // Calculate expiration time 90 days from now in epoch second format
        final long expireDate = createDate + (DAYS_TO_EXPIRE * SECONDS_PER_DAY);

        final Map<String, AttributeValue> itemMap = new HashMap<>();
        itemMap.put(
            PRIMARY_KEY_ATTR, AttributeValue.builder().s(primaryKeyValue).build());
        itemMap.put(SORT_KEY_ATTR, AttributeValue.builder().s(sortKeyValue).build());
        itemMap.put(
            CREATION_DATE_ATTR,
            AttributeValue.builder().n(String.valueOf(createDate)).build());
        itemMap.put(
            EXPIRE_AT_ATTR,
            AttributeValue.builder().n(String.valueOf(expireDate)).build());

        final PutItemRequest request =
            PutItemRequest.builder().tableName(tableName).item(itemMap).build();

        try {
            final PutItemResponse response = dynamoDbClient.putItem(request);
            System.out.println(String.format(SUCCESS_MESSAGE, tableName));
            return response;
        } catch (ResourceNotFoundException e) {
            System.err.format(TABLE_NOT_FOUND_ERROR, tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            throw e;
        }
    }
}
```
+  *Einzelheiten zur API finden Sie unter [PutItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/PutItem)API-Referenz.AWS SDK for Java 2.x * 

------
#### [ JavaScript ]

**SDK für JavaScript (v3)**  

```
import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb";

export function createDynamoDBItem(table_name, region, partition_key, sort_key) {
    const client = new DynamoDBClient({
        region: region,
        endpoint: `https://dynamodb.${region}.amazonaws.com`
    });

    // Get the current time in epoch second format
    const current_time = Math.floor(new Date().getTime() / 1000);

    // Calculate the expireAt time (90 days from now) in epoch second format
    const expire_at = Math.floor((new Date().getTime() + 90 * 24 * 60 * 60 * 1000) / 1000);

    // Create DynamoDB item
    const item = {
        'partitionKey': {'S': partition_key},
        'sortKey': {'S': sort_key},
        'createdAt': {'N': current_time.toString()},
        'expireAt': {'N': expire_at.toString()}
    };

    const putItemCommand = new PutItemCommand({
        TableName: table_name,
        Item: item,
        ProvisionedThroughput: {
            ReadCapacityUnits: 1,
            WriteCapacityUnits: 1,
        },
    });

    client.send(putItemCommand, function(err, data) {
        if (err) {
            console.log("Exception encountered when creating item %s, here's what happened: ", data, err);
            throw err;
        } else {
            console.log("Item created successfully: %s.", data);
            return data;
        }
    });
}

// Example usage (commented out for testing)
// createDynamoDBItem('your-table-name', 'us-east-1', 'your-partition-key-value', 'your-sort-key-value');
```
+  Einzelheiten zur API finden Sie [PutItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/PutItemCommand)in der *AWS SDK für JavaScript API-Referenz*. 

------
#### [ Python ]

**SDK für Python (Boto3)**  

```
from datetime import datetime, timedelta

import boto3


def create_dynamodb_item(table_name, region, primary_key, sort_key):
    """
    Creates a DynamoDB item with an attached expiry attribute.

    :param table_name: Table name for the boto3 resource to target when creating an item
    :param region: string representing the AWS region. Example: `us-east-1`
    :param primary_key: one attribute known as the partition key.
    :param sort_key: Also known as a range attribute.
    :return: Void (nothing)
    """
    try:
        dynamodb = boto3.resource("dynamodb", region_name=region)
        table = dynamodb.Table(table_name)

        # Get the current time in epoch second format
        current_time = int(datetime.now().timestamp())

        # Calculate the expiration time (90 days from now) in epoch second format
        expiration_time = int((datetime.now() + timedelta(days=90)).timestamp())

        item = {
            "primaryKey": primary_key,
            "sortKey": sort_key,
            "creationDate": current_time,
            "expireAt": expiration_time,
        }
        response = table.put_item(Item=item)

        print("Item created successfully.")
        return response
    except Exception as e:
        print(f"Error creating item: {e}")
        raise e


# Use your own values
create_dynamodb_item(
    "your-table-name", "us-west-2", "your-partition-key-value", "your-sort-key-value"
)
```
+  Einzelheiten zur API finden Sie [PutItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/PutItem)in *AWS SDK for Python (Boto3) API* Reference. 

------

## Aktualisieren eines Elements und der Time to Live
<a name="time-to-live-ttl-before-you-start-update"></a>

Dies ist eine Fortsetzung des Beispiels aus dem [vorherigen Abschnitt](#time-to-live-ttl-before-you-start-create). Die Ablaufzeit kann neu berechnet werden, wenn das Element aktualisiert wird. Im folgenden Beispiel wird der Zeitstempel `expireAt` neu berechnet, sodass er 90 Tage nach der aktuellen Uhrzeit liegt.

Die folgenden Codebeispiele veranschaulichen, wie Sie die TTL eines Elements aktualisieren.

------
#### [ Java ]

**SDK für Java 2.x**  
Aktualisieren Sie die TTL für ein vorhandenes DynamoDB-Element in einer Tabelle.  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

    public UpdateItemResponse updateItemWithTTL(
        final String tableName, final String primaryKeyValue, final String sortKeyValue) {
        // Get current time in epoch second format
        final long currentTime = System.currentTimeMillis() / 1000;

        // Calculate expiration time 90 days from now in epoch second format
        final long expireDate = currentTime + (DAYS_TO_EXPIRE * SECONDS_PER_DAY);

        // Create the key map for the item to update
        final Map<String, AttributeValue> keyMap = new HashMap<>();
        keyMap.put(PRIMARY_KEY_ATTR, AttributeValue.builder().s(primaryKeyValue).build());
        keyMap.put(SORT_KEY_ATTR, AttributeValue.builder().s(sortKeyValue).build());

        // Create the expression attribute values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            ":c", AttributeValue.builder().n(String.valueOf(currentTime)).build());
        expressionAttributeValues.put(
            ":e", AttributeValue.builder().n(String.valueOf(expireDate)).build());

        final UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(keyMap)
            .updateExpression(UPDATE_EXPRESSION)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try {
            final UpdateItemResponse response = dynamoDbClient.updateItem(request);
            System.out.println(String.format(SUCCESS_MESSAGE, tableName));
            return response;
        } catch (ResourceNotFoundException e) {
            System.err.format(TABLE_NOT_FOUND_ERROR, tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            throw e;
        }
    }
```
+  Einzelheiten zur API finden Sie unter [UpdateItem AWS SDK for Java 2.x](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)*API-Referenz*. 

------
#### [ JavaScript ]

**SDK für JavaScript (v3)**  

```
import { DynamoDBClient, UpdateItemCommand } from "@aws-sdk/client-dynamodb";
import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";

export const updateItem = async (tableName, partitionKey, sortKey, region = 'us-east-1') => {
    const client = new DynamoDBClient({
        region: region,
        endpoint: `https://dynamodb.${region}.amazonaws.com`
    });

    const currentTime = Math.floor(Date.now() / 1000);
    const expireAt = Math.floor((Date.now() + 90 * 24 * 60 * 60 * 1000) / 1000);

    const params = {
        TableName: tableName,
        Key: marshall({
            partitionKey: partitionKey,
            sortKey: sortKey
        }),
        UpdateExpression: "SET updatedAt = :c, expireAt = :e",
        ExpressionAttributeValues: marshall({
            ":c": currentTime,
            ":e": expireAt
        }),
    };

    try {
        const data = await client.send(new UpdateItemCommand(params));
        const responseData = unmarshall(data.Attributes);
        console.log("Item updated successfully: %s", responseData);
        return responseData;
    } catch (err) {
        console.error("Error updating item:", err);
        throw err;
    }
}

// Example usage (commented out for testing)
// updateItem('your-table-name', 'your-partition-key-value', 'your-sort-key-value');
```
+  Einzelheiten zur API finden Sie [UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)in der *AWS SDK für JavaScript API-Referenz*. 

------
#### [ Python ]

**SDK für Python (Boto3)**  

```
from datetime import datetime, timedelta

import boto3


def update_dynamodb_item(table_name, region, primary_key, sort_key):
    """
    Update an existing DynamoDB item with a TTL.
    :param table_name: Name of the DynamoDB table
    :param region: AWS Region of the table - example `us-east-1`
    :param primary_key: one attribute known as the partition key.
    :param sort_key: Also known as a range attribute.
    :return: Void (nothing)
    """
    try:
        # Create the DynamoDB resource.
        dynamodb = boto3.resource("dynamodb", region_name=region)
        table = dynamodb.Table(table_name)

        # Get the current time in epoch second format
        current_time = int(datetime.now().timestamp())

        # Calculate the expireAt time (90 days from now) in epoch second format
        expire_at = int((datetime.now() + timedelta(days=90)).timestamp())

        table.update_item(
            Key={"partitionKey": primary_key, "sortKey": sort_key},
            UpdateExpression="set updatedAt=:c, expireAt=:e",
            ExpressionAttributeValues={":c": current_time, ":e": expire_at},
        )

        print("Item updated successfully.")
    except Exception as e:
        print(f"Error updating item: {e}")


# Replace with your own values
update_dynamodb_item(
    "your-table-name", "us-west-2", "your-partition-key-value", "your-sort-key-value"
)
```
+  Einzelheiten zur API finden Sie [UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)in *AWS SDK for Python (Boto3) API* Reference. 

------

Die in dieser Einführung vorgestellten TTL-Beispiele sind ein Weg, um sicherzustellen, dass nur kürzlich aktualisierte Elemente in einer Tabelle gespeichert bleiben. Die Lebensdauer aktualisierter Elemente wird verlängert, wohingegen Elemente, die seit ihrer Erstellung nicht mehr aktualisiert wurden, ablaufen und kostenlos gelöscht werden. So wird Speicherplatz reduziert und die Tabellen werden auf dem neuesten Stand gehalten.

# Arbeiten mit abgelaufenen Elementen und Time to Live (TTL)
<a name="ttl-expired-items"></a>

Abgelaufene Elemente, deren Löschung noch aussteht, können aus Lese- und Schreibvorgängen herausgefiltert werden. Dies ist nützlich in Szenarien, in denen abgelaufene Daten nicht mehr gültig sind und nicht verwendet werden sollten. Wenn sie nicht gefiltert werden, werden sie weiterhin bei Lese- und Schreibvorgängen angezeigt, bis sie vom Hintergrundprozess gelöscht werden.

**Anmerkung**  
Diese Elemente werden weiterhin auf die Speicher- und Lesekosten angerechnet, bis sie gelöscht werden.

TTL-Löschungen können in DynamoDB Streams identifiziert werden, jedoch nur in der Region, in der die Löschung stattgefunden hat. TTL-Löschungen, die in globale Tabellenbereiche repliziert werden, sind in DynamoDB-Streams in den Regionen, in die die Löschung repliziert wurde, nicht identifizierbar.

## Filtern abgelaufener Elemente aus Lesevorgängen
<a name="ttl-expired-items-filter"></a>

Bei Lesevorgängen wie [Scan](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html) und [Abfrage](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html) kann ein Filterausdruck abgelaufene Elemente herausfiltern, deren Löschung noch aussteht. Wie im folgenden Codeausschnitt gezeigt, kann der Filterausdruck Elemente herausfiltern, bei denen die TTL-Zeit gleich oder kleiner als die aktuelle Zeit ist. Der Python-SDK-Code enthält beispielsweise eine Zuweisungsanweisung, die die aktuelle Uhrzeit als Variable (`now`) abruft und sie in `int` für das Unix-Zeitformat konvertiert.

In den folgenden Codebeispielen wird gezeigt, wie TTL-Elemente abgefragt werden.

------
#### [ Java ]

**SDK für Java 2.x**  
Abfragen eines gefilterten Ausdrucks zum Sammeln von TTL-Elementen in einer DynamoDB-Tabelle mithilfe von. AWS SDK for Java 2.x  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.Map;
import java.util.Optional;

        final QueryRequest request = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .filterExpression(FILTER_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try (DynamoDbClient ddb = dynamoDbClient != null
            ? dynamoDbClient
            : DynamoDbClient.builder().region(region).build()) {
            final QueryResponse response = ddb.query(request);
            System.out.println("Query successful. Found " + response.count() + " items that have not expired yet.");

            // Print each item
            response.items().forEach(item -> {
                System.out.println("Item: " + item);
            });

            return 0;
        } catch (ResourceNotFoundException e) {
            System.err.format(TABLE_NOT_FOUND_ERROR, tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            throw e;
        }
```
+  Weitere API-Informationen finden Sie unter [Abfragen](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query) in der *AWS SDK for Java 2.x -API-Referenz*. 

------
#### [ JavaScript ]

**SDK für JavaScript (v3)**  
Abfragen eines gefilterten Ausdrucks zum Sammeln von TTL-Elementen in einer DynamoDB-Tabelle mithilfe von. AWS SDK für JavaScript  

```
import { DynamoDBClient, QueryCommand } from "@aws-sdk/client-dynamodb";
import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";

export const queryFiltered = async (tableName, primaryKey, region = 'us-east-1') => {
    const client = new DynamoDBClient({
        region: region,
        endpoint: `https://dynamodb.${region}.amazonaws.com`
    });

    const currentTime = Math.floor(Date.now() / 1000);

    const params = {
        TableName: tableName,
        KeyConditionExpression: "#pk = :pk",
        FilterExpression: "#ea > :ea",
        ExpressionAttributeNames: {
            "#pk": "primaryKey",
            "#ea": "expireAt"
        },
        ExpressionAttributeValues: marshall({
            ":pk": primaryKey,
            ":ea": currentTime
        })
    };

    try {
        const { Items } = await client.send(new QueryCommand(params));
        Items.forEach(item => {
            console.log(unmarshall(item))
        });
        return Items;
    } catch (err) {
        console.error(`Error querying items: ${err}`);
        throw err;
    }
}

// Example usage (commented out for testing)
// queryFiltered('your-table-name', 'your-partition-key-value');
```
+  Weitere API-Informationen finden Sie unter [Abfragen](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand) in der *AWS SDK für JavaScript -API-Referenz*. 

------
#### [ Python ]

**SDK für Python (Boto3)**  
Abfragen eines gefilterten Ausdrucks zum Sammeln von TTL-Elementen in einer DynamoDB-Tabelle mithilfe von. AWS SDK für Python (Boto3)  

```
from datetime import datetime

import boto3


def query_dynamodb_items(table_name, partition_key):
    """

    :param table_name: Name of the DynamoDB table
    :param partition_key:
    :return:
    """
    try:
        # Initialize a DynamoDB resource
        dynamodb = boto3.resource("dynamodb", region_name="us-east-1")

        # Specify your table
        table = dynamodb.Table(table_name)

        # Get the current time in epoch format
        current_time = int(datetime.now().timestamp())

        # Perform the query operation with a filter expression to exclude expired items
        # response = table.query(
        #    KeyConditionExpression=boto3.dynamodb.conditions.Key('partitionKey').eq(partition_key),
        #    FilterExpression=boto3.dynamodb.conditions.Attr('expireAt').gt(current_time)
        # )
        response = table.query(
            KeyConditionExpression=dynamodb.conditions.Key("partitionKey").eq(partition_key),
            FilterExpression=dynamodb.conditions.Attr("expireAt").gt(current_time),
        )

        # Print the items that are not expired
        for item in response["Items"]:
            print(item)

    except Exception as e:
        print(f"Error querying items: {e}")


# Call the function with your values
query_dynamodb_items("Music", "your-partition-key-value")
```
+  Weitere API-Informationen finden Sie unter [Abfragen](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query) in der *API-Referenz zum AWS  SDK für Python (Boto3)*. 

------

## Bedingtes Schreiben in abgelaufene Elemente
<a name="ttl-expired-items-conditional-write"></a>

Ein Bedingungsausdruck kann verwendet werden, um Schreibvorgänge auf abgelaufene Elemente zu verhindern. Der folgende Codeausschnitt ist eine bedingte Aktualisierung, die prüft, ob die Ablaufzeit nach der aktuellen Zeit liegt. Falls ja, wird der Schreibvorgang fortgesetzt.

In den folgenden Codebeispielen wird gezeigt, wie die TTL eines Elements bedingungsabhängig aktualisiert wird.

------
#### [ Java ]

**SDK für Java 2.x**  
Aktualisieren Sie die TTL für ein vorhandenes DynamoDB-Element in einer Tabelle mit einer Bedingung.  

```
package com.amazon.samplelib.ttl;

import com.amazon.samplelib.CodeSampleUtils;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;

import java.util.Map;
import java.util.Optional;

/**
 * Updates an item in a DynamoDB table with TTL attributes using a conditional expression.
 * This class demonstrates how to conditionally update TTL expiration timestamps.
 */
public class UpdateTTLConditional {

    private static final String USAGE =
        """
            Usage:
                <tableName> <primaryKey> <sortKey> <region>
            Where:
                tableName - The Amazon DynamoDB table being queried.
                primaryKey - The name of the primary key. Also known as the hash or partition key.
                sortKey - The name of the sort key. Also known as the range attribute.
                region (optional) - The AWS region that the Amazon DynamoDB table is located in. (Default: us-east-1)
            """;
    private static final int DAYS_TO_EXPIRE = 90;
    private static final int SECONDS_PER_DAY = 24 * 60 * 60;
    private static final String PRIMARY_KEY_ATTR = "primaryKey";
    private static final String SORT_KEY_ATTR = "sortKey";
    private static final String UPDATED_AT_ATTR = "updatedAt";
    private static final String EXPIRE_AT_ATTR = "expireAt";
    private static final String UPDATE_EXPRESSION = "SET " + UPDATED_AT_ATTR + "=:c, " + EXPIRE_AT_ATTR + "=:e";
    private static final String CONDITION_EXPRESSION = "attribute_exists(" + PRIMARY_KEY_ATTR + ")";
    private static final String SUCCESS_MESSAGE = "%s UpdateItem operation with TTL successful.";
    private static final String CONDITION_FAILED_MESSAGE = "Condition check failed. Item does not exist.";
    private static final String TABLE_NOT_FOUND_ERROR = "Error: The Amazon DynamoDB table \"%s\" can't be found.";

    private final DynamoDbClient dynamoDbClient;

    /**
     * Constructs an UpdateTTLConditional with a default DynamoDB client.
     */
    public UpdateTTLConditional() {
        this.dynamoDbClient = null;
    }

    /**
     * Constructs an UpdateTTLConditional with the specified DynamoDB client.
     *
     * @param dynamoDbClient The DynamoDB client to use
     */
    public UpdateTTLConditional(final DynamoDbClient dynamoDbClient) {
        this.dynamoDbClient = dynamoDbClient;
    }

    /**
     * Main method to demonstrate conditionally updating an item with TTL.
     *
     * @param args Command line arguments
     */
    public static void main(final String[] args) {
        try {
            int result = new UpdateTTLConditional().processArgs(args);
            System.exit(result);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    /**
     * Process command line arguments and conditionally update an item with TTL.
     *
     * @param args Command line arguments
     * @return 0 if successful, non-zero otherwise
     * @throws ResourceNotFoundException If the table doesn't exist
     * @throws DynamoDbException If an error occurs during the operation
     * @throws IllegalArgumentException If arguments are invalid
     */
    public int processArgs(final String[] args) {
        // Argument validation (remove or replace this line when reusing this code)
        CodeSampleUtils.validateArgs(args, new int[] {3, 4}, USAGE);

        final String tableName = args[0];
        final String primaryKey = args[1];
        final String sortKey = args[2];
        final Region region = Optional.ofNullable(args.length > 3 ? args[3] : null)
            .map(Region::of)
            .orElse(Region.US_EAST_1);

        // Get current time in epoch second format
        final long currentTime = System.currentTimeMillis() / 1000;

        // Calculate expiration time 90 days from now in epoch second format
        final long expireDate = currentTime + (DAYS_TO_EXPIRE * SECONDS_PER_DAY);

        // Create the key map for the item to update
        final Map<String, AttributeValue> keyMap = Map.of(
            PRIMARY_KEY_ATTR, AttributeValue.builder().s(primaryKey).build(),
            SORT_KEY_ATTR, AttributeValue.builder().s(sortKey).build());

        // Create the expression attribute values
        final Map<String, AttributeValue> expressionAttributeValues = Map.of(
            ":c", AttributeValue.builder().n(String.valueOf(currentTime)).build(),
            ":e", AttributeValue.builder().n(String.valueOf(expireDate)).build());

        final UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(keyMap)
            .updateExpression(UPDATE_EXPRESSION)
            .conditionExpression(CONDITION_EXPRESSION)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try (DynamoDbClient ddb = dynamoDbClient != null
            ? dynamoDbClient
            : DynamoDbClient.builder().region(region).build()) {
            final UpdateItemResponse response = ddb.updateItem(request);
            System.out.println(String.format(SUCCESS_MESSAGE, tableName));
            return 0;
        } catch (ConditionalCheckFailedException e) {
            System.err.println(CONDITION_FAILED_MESSAGE);
            throw e;
        } catch (ResourceNotFoundException e) {
            System.err.format(TABLE_NOT_FOUND_ERROR, tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            throw e;
        }
    }
}
```
+  *Einzelheiten zur API finden Sie unter [UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)API-Referenz.AWS SDK for Java 2.x * 

------
#### [ JavaScript ]

**SDK für JavaScript (v3)**  
Aktualisieren Sie die TTL für ein vorhandenes DynamoDB-Element in einer Tabelle mit einer Bedingung.  

```
import { DynamoDBClient, UpdateItemCommand } from "@aws-sdk/client-dynamodb";
import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";

export const updateItemConditional = async (tableName, partitionKey, sortKey, region = 'us-east-1', newAttribute = 'default-value') => {
    const client = new DynamoDBClient({
        region: region,
        endpoint: `https://dynamodb.${region}.amazonaws.com`
    });

    const currentTime = Math.floor(Date.now() / 1000);

    const params = {
        TableName: tableName,
        Key: marshall({
            artist: partitionKey,
            album: sortKey
        }),
        UpdateExpression: "SET newAttribute = :newAttribute",
        ConditionExpression: "expireAt > :expiration",
        ExpressionAttributeValues: marshall({
            ':newAttribute': newAttribute,
            ':expiration': currentTime
        }),
        ReturnValues: "ALL_NEW"
    };

    try {
        const response = await client.send(new UpdateItemCommand(params));
        const responseData = unmarshall(response.Attributes);
        console.log("Item updated successfully: ", responseData);
        return responseData;
    } catch (error) {
        if (error.name === "ConditionalCheckFailedException") {
            console.log("Condition check failed: Item's 'expireAt' is expired.");
        } else {
            console.error("Error updating item: ", error);
        }
        throw error;
    }
};

// Example usage (commented out for testing)
// updateItemConditional('your-table-name', 'your-partition-key-value', 'your-sort-key-value');
```
+  Einzelheiten zur API finden Sie [UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)in der *AWS SDK für JavaScript API-Referenz*. 

------
#### [ Python ]

**SDK für Python (Boto3)**  
Aktualisieren Sie die TTL für ein vorhandenes DynamoDB-Element in einer Tabelle mit einer Bedingung.  

```
from datetime import datetime, timedelta

import boto3
from botocore.exceptions import ClientError


def update_dynamodb_item_ttl(table_name, region, primary_key, sort_key, ttl_attribute):
    """
    Updates an existing record in a DynamoDB table with a new or updated TTL attribute.

    :param table_name: Name of the DynamoDB table
    :param region: AWS Region of the table - example `us-east-1`
    :param primary_key: one attribute known as the partition key.
    :param sort_key: Also known as a range attribute.
    :param ttl_attribute: name of the TTL attribute in the target DynamoDB table
    :return:
    """
    try:
        dynamodb = boto3.resource("dynamodb", region_name=region)
        table = dynamodb.Table(table_name)

        # Generate updated TTL in epoch second format
        updated_expiration_time = int((datetime.now() + timedelta(days=90)).timestamp())

        # Define the update expression for adding/updating a new attribute
        update_expression = "SET newAttribute = :val1"

        # Define the condition expression for checking if 'expireAt' is not expired
        condition_expression = "expireAt > :val2"

        # Define the expression attribute values
        expression_attribute_values = {":val1": ttl_attribute, ":val2": updated_expiration_time}

        response = table.update_item(
            Key={"primaryKey": primary_key, "sortKey": sort_key},
            UpdateExpression=update_expression,
            ConditionExpression=condition_expression,
            ExpressionAttributeValues=expression_attribute_values,
        )

        print("Item updated successfully.")
        return response["ResponseMetadata"]["HTTPStatusCode"]  # Ideally a 200 OK
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            print("Condition check failed: Item's 'expireAt' is expired.")
        else:
            print(f"Error updating item: {e}")
    except Exception as e:
        print(f"Error updating item: {e}")


# replace with your values
update_dynamodb_item_ttl(
    "your-table-name",
    "us-east-1",
    "your-partition-key-value",
    "your-sort-key-value",
    "your-ttl-attribute-value",
)
```
+  Einzelheiten zur API finden Sie [UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)in *AWS SDK for Python (Boto3) API* Reference. 

------

## Identifizieren gelöschter Elemente in DynamoDB Streams
<a name="ttl-expired-items-identifying"></a>

Der Stream-Datensatz enthält ein Benutzeridentitätsfeld `Records[<index>].userIdentity`. Elemente, die durch den TTL-Prozess gelöscht wurden, haben die folgenden Felder:

```
Records[<index>].userIdentity.type
"Service"

Records[<index>].userIdentity.principalId
"dynamodb.amazonaws.com"
```

Der folgende JSON-Ausdruck zeigt den relevanten Teil eines einzelnen Stream-Datensatzes:

```
"Records": [ 
  { 
	... 
		"userIdentity": {
		"type": "Service", 
      	"principalId": "dynamodb.amazonaws.com" 
   	} 
   ... 
	} 
]
```