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.
Arbeiten mit abgelaufenen Elementen
Abgelaufene Elemente, deren Löschung aussteht, können aus Lese- und Schreibvorgängen gefiltert werden. Dies ist in Szenarien nützlich, in denen abgelaufene Daten nicht mehr gültig sind und nicht verwendet werden sollten. Wenn sie nicht gefiltert werden, werden sie weiterhin in Lese- und Schreibvorgängen angezeigt, bis sie durch den Hintergrundprozess gelöscht werden.
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 der Löschvorgang stattgefunden hat. TTL-Löschungen, die in globale Tabellenregionen repliziert werden, sind in DynamoDB-Streams in den Regionen, in die der Löschvorgang repliziert wird, nicht identifizierbar.
Filtern abgelaufener Elemente aus Lesevorgängen
Bei Lesevorgängen wie Scan und Abfrage kann ein Filterausdruck abgelaufene Elemente herausfiltern, deren Löschung aussteht. Wie im folgenden Codeausschnitt gezeigt, kann der Filterausdruck Elemente herausfiltern, bei denen die TTL-Zeit gleich oder kleiner als die aktuelle Zeit ist. Dies erfolgt mit einer Zuweisungsanweisung, die die aktuelle Zeit als Variable (now
) erhält, die int
für das Epochenzeitformat in konvertiert wird.
- Python
-
import boto3
from datetime import datetime
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')
Die Ausgabe des Aktualisierungsvorgangs zeigt, dass, während die createdAt
Zeit unverändert ist, die expireAt
Zeiten updatedAt
und aktualisiert wurden. Die expireAt
Zeit ist jetzt auf 90 Tage ab dem Zeitpunkt der letzten Aktualisierung eingestellt, der am Donnerstag, 19. Oktober 2023, um 13:27:15 Uhr liegt.
partition_key |
createdAt |
updatedAt |
expireAt |
Attribut_1 |
Attribut_2 |
some_value
|
2023-07-17 14:11:05.322323 |
2023-07-19 13:27:15.213423 |
1697722035 |
new_value |
some_value |
- Javascript
-
import { DynamoDBClient, QueryCommand } from "@aws-sdk/client-dynamodb";
import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";
async function queryDynamoDBItems(tableName, region, primaryKey) {
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;
}
}
//enter your own values here
queryDynamoDBItems('your-table-name', 'your-partition-key-value');
Bedingtes Schreiben in abgelaufene Elemente
Ein Bedingungsausdruck kann verwendet werden, um Schreibvorgänge für abgelaufene Elemente zu vermeiden. Der folgende Codeausschnitt ist eine bedingte Aktualisierung, die prüft, ob die Ablaufzeit länger als die aktuelle Zeit ist. Wenn „true“, wird der Schreibvorgang fortgesetzt.
- Python
-
import boto3
from datetime import datetime, timedelta
from botocore.exceptions import ClientError
def update_dynamodb_item(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 'ttlExpirationDate' is not expired
condition_expression = "ttlExpirationDate > :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 'ttlExpirationDate' 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('your-table-name', 'us-east-1', 'your-partition-key-value', 'your-sort-key-value',
'your-ttl-attribute-value')
Die Ausgabe des Aktualisierungsvorgangs zeigt, dass, während die createdAt
Zeit unverändert ist, die expireAt
Zeiten updatedAt
und aktualisiert wurden. Die expireAt
Zeit ist jetzt auf 90 Tage ab dem Zeitpunkt der letzten Aktualisierung eingestellt, der am Donnerstag, 19. Oktober 2023, um 13:27:15 Uhr liegt.
partition_key |
createdAt |
updatedAt |
expireAt |
Attribut_1 |
Attribut_2 |
some_value
|
2023-07-17 14:11:05.322323 |
2023-07-19 13:27:15.213423 |
1697722035 |
new_value |
some_value |
- Javascript
-
import { DynamoDBClient, UpdateItemCommand } from "@aws-sdk/client-dynamodb";
import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";
// Example function to update an item in a DynamoDB table.
// The function should take the table name, region, partition key, sort key, and new attribute as arguments.
// The function should use the DynamoDB client to update the item.
// The function should return the updated item.
// The function should handle errors and exceptions.
const updateDynamoDBItem = async (tableName, region, partitionKey, sortKey, newAttribute) => {
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;
}
};
// Enter your values here
updateDynamoDBItem('your-table-name', "us-east-1",'your-partition-key-value', 'your-sort-key-value', 'your-new-attribute-value');
Identifizieren gelöschter Elemente in DynamoDB Streams
Der Stream-Datensatz enthält ein Benutzeridentitätsfeld Records[<index>].userIdentity
. Elemente, die durch den TTL-Prozess gelöscht werden, haben die folgenden Felder:
Records[<index>].userIdentity.type
"Service"
Records[<index>].userIdentity.principalId
"dynamodb.amazonaws.com"
Das folgende JSON zeigt den relevanten Teil eines Datensatzes für einzelne Streams:
"Records": [
{
...
"userIdentity": {
"type": "Service",
"principalId": "dynamodb.amazonaws.com"
}
...
}
]