La Guía de referencia de la API de AWS SDK for JavaScript V3 describe en detalle todas las operaciones de la API para la versión 3 (V3) de AWS SDK for JavaScript.
Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.
Ejemplos de DynamoDB que utilizan el SDK JavaScript para (v3)
Los siguientes ejemplos de código muestran cómo realizar acciones e implementar escenarios comunes mediante el uso de AWS SDK for JavaScript (v3) con DynamoDB.
Los conceptos básicos son ejemplos de código que muestran cómo realizar las operaciones esenciales dentro de un servicio.
Las acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Mientras las acciones muestran cómo llamar a las distintas funciones de servicio, es posible ver las acciones en contexto en los escenarios relacionados.
Los escenarios son ejemplos de código que muestran cómo llevar a cabo una tarea específica a través de llamadas a varias funciones dentro del servicio o combinado con otros Servicios de AWS.
En cada ejemplo se incluye un enlace al código de origen completo, con instrucciones de configuración y ejecución del código en el contexto.
Introducción
En los siguientes ejemplos de código, se muestra cómo empezar a utilizar DynamoDB.
- SDK para (v3 JavaScript )
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Para obtener más información sobre cómo trabajar con DynamoDB AWS SDK for JavaScript en, consulte Programar DynamoDB con. JavaScript
import { ListTablesCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new ListTablesCommand({}); const response = await client.send(command); console.log(response.TableNames.join("\n")); return response; };
-
Para obtener más información sobre la API, consulte ListTablesla referencia de la API.AWS SDK for JavaScript
-
Conceptos básicos
En el siguiente ejemplo de código, se muestra cómo:
Creación de una tabla que pueda contener datos de películas.
Colocar, obtener y actualizar una sola película en la tabla.
Escribir los datos de películas en la tabla a partir de un archivo JSON de ejemplo.
Consultar películas que se hayan estrenado en un año determinado.
Buscar películas que se hayan estrenado en un intervalo de años.
Eliminación de una película de la tabla y, a continuación, eliminar la tabla.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. import { readFileSync } from "node:fs"; import { BillingMode, CreateTableCommand, DeleteTableCommand, DynamoDBClient, waitUntilTableExists, } from "@aws-sdk/client-dynamodb"; /** * This module is a convenience library. It abstracts Amazon DynamoDB's data type * descriptors (such as S, N, B, and BOOL) by marshalling JavaScript objects into * AttributeValue shapes. */ import { BatchWriteCommand, DeleteCommand, DynamoDBDocumentClient, GetCommand, PutCommand, UpdateCommand, paginateQuery, paginateScan, } from "@aws-sdk/lib-dynamodb"; // These modules are local to our GitHub repository. We recommend cloning // the project from GitHub if you want to run this example. // For more information, see https://github.com/awsdocs/aws-doc-sdk-examples. import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js"; import { dirnameFromMetaUrl } from "@aws-doc-sdk-examples/lib/utils/util-fs.js"; import { chunkArray } from "@aws-doc-sdk-examples/lib/utils/util-array.js"; const dirname = dirnameFromMetaUrl(import.meta.url); const tableName = getUniqueName("Movies"); const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); const log = (msg) => console.log(`[SCENARIO] ${msg}`); export const main = async () => { /** * Create a table. */ const createTableCommand = new CreateTableCommand({ TableName: tableName, // This example performs a large write to the database. // Set the billing mode to PAY_PER_REQUEST to // avoid throttling the large write. BillingMode: BillingMode.PAY_PER_REQUEST, // Define the attributes that are necessary for the key schema. AttributeDefinitions: [ { AttributeName: "year", // 'N' is a data type descriptor that represents a number type. // For a list of all data type descriptors, see the following link. // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors AttributeType: "N", }, { AttributeName: "title", AttributeType: "S" }, ], // The KeySchema defines the primary key. The primary key can be // a partition key, or a combination of a partition key and a sort key. // Key schema design is important. For more info, see // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html KeySchema: [ // The way your data is accessed determines how you structure your keys. // The movies table will be queried for movies by year. It makes sense // to make year our partition (HASH) key. { AttributeName: "year", KeyType: "HASH" }, { AttributeName: "title", KeyType: "RANGE" }, ], }); log("Creating a table."); const createTableResponse = await client.send(createTableCommand); log(`Table created: ${JSON.stringify(createTableResponse.TableDescription)}`); // This polls with DescribeTableCommand until the requested table is 'ACTIVE'. // You can't write to a table before it's active. log("Waiting for the table to be active."); await waitUntilTableExists({ client }, { TableName: tableName }); log("Table active."); /** * Add a movie to the table. */ log("Adding a single movie to the table."); // PutCommand is the first example usage of 'lib-dynamodb'. const putCommand = new PutCommand({ TableName: tableName, Item: { // In 'client-dynamodb', the AttributeValue would be required (`year: { N: 1981 }`) // 'lib-dynamodb' simplifies the usage ( `year: 1981` ) year: 1981, // The preceding KeySchema defines 'title' as our sort (RANGE) key, so 'title' // is required. title: "The Evil Dead", // Every other attribute is optional. info: { genres: ["Horror"], }, }, }); await docClient.send(putCommand); log("The movie was added."); /** * Get a movie from the table. */ log("Getting a single movie from the table."); const getCommand = new GetCommand({ TableName: tableName, // Requires the complete primary key. For the movies table, the primary key // is only the id (partition key). Key: { year: 1981, title: "The Evil Dead", }, // Set this to make sure that recent writes are reflected. // For more information, see https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html. ConsistentRead: true, }); const getResponse = await docClient.send(getCommand); log(`Got the movie: ${JSON.stringify(getResponse.Item)}`); /** * Update a movie in the table. */ log("Updating a single movie in the table."); const updateCommand = new UpdateCommand({ TableName: tableName, Key: { year: 1981, title: "The Evil Dead" }, // This update expression appends "Comedy" to the list of genres. // For more information on update expressions, see // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html UpdateExpression: "set #i.#g = list_append(#i.#g, :vals)", ExpressionAttributeNames: { "#i": "info", "#g": "genres" }, ExpressionAttributeValues: { ":vals": ["Comedy"], }, ReturnValues: "ALL_NEW", }); const updateResponse = await docClient.send(updateCommand); log(`Movie updated: ${JSON.stringify(updateResponse.Attributes)}`); /** * Delete a movie from the table. */ log("Deleting a single movie from the table."); const deleteCommand = new DeleteCommand({ TableName: tableName, Key: { year: 1981, title: "The Evil Dead" }, }); await client.send(deleteCommand); log("Movie deleted."); /** * Upload a batch of movies. */ log("Adding movies from local JSON file."); const file = readFileSync( `${dirname}../../../../resources/sample_files/movies.json`, ); const movies = JSON.parse(file.toString()); // chunkArray is a local convenience function. It takes an array and returns // a generator function. The generator function yields every N items. const movieChunks = chunkArray(movies, 25); // For every chunk of 25 movies, make one BatchWrite request. for (const chunk of movieChunks) { const putRequests = chunk.map((movie) => ({ PutRequest: { Item: movie, }, })); const command = new BatchWriteCommand({ RequestItems: { [tableName]: putRequests, }, }); await docClient.send(command); } log("Movies added."); /** * Query for movies by year. */ log("Querying for all movies from 1981."); const paginatedQuery = paginateQuery( { client: docClient }, { TableName: tableName, //For more information about query expressions, see // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html#Query.KeyConditionExpressions KeyConditionExpression: "#y = :y", // 'year' is a reserved word in DynamoDB. Indicate that it's an attribute // name by using an expression attribute name. ExpressionAttributeNames: { "#y": "year" }, ExpressionAttributeValues: { ":y": 1981 }, ConsistentRead: true, }, ); /** * @type { Record<string, any>[] }; */ const movies1981 = []; for await (const page of paginatedQuery) { movies1981.push(...page.Items); } log(`Movies: ${movies1981.map((m) => m.title).join(", ")}`); /** * Scan the table for movies between 1980 and 1990. */ log("Scan for movies released between 1980 and 1990"); // A 'Scan' operation always reads every item in the table. If your design requires // the use of 'Scan', consider indexing your table or changing your design. // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-query-scan.html const paginatedScan = paginateScan( { client: docClient }, { TableName: tableName, // Scan uses a filter expression instead of a key condition expression. Scan will // read the entire table and then apply the filter. FilterExpression: "#y between :y1 and :y2", ExpressionAttributeNames: { "#y": "year" }, ExpressionAttributeValues: { ":y1": 1980, ":y2": 1990 }, ConsistentRead: true, }, ); /** * @type { Record<string, any>[] }; */ const movies1980to1990 = []; for await (const page of paginatedScan) { movies1980to1990.push(...page.Items); } log( `Movies: ${movies1980to1990 .map((m) => `${m.title} (${m.year})`) .join(", ")}`, ); /** * Delete the table. */ const deleteTableCommand = new DeleteTableCommand({ TableName: tableName }); log(`Deleting table ${tableName}.`); await client.send(deleteTableCommand); log("Table deleted."); };
-
Para obtener información sobre la API, consulte los siguientes temas en la referencia de la API de AWS SDK for JavaScript .
-
Acciones
En el siguiente ejemplo de código, se muestra cómo utilizar BatchExecuteStatement
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Crear un lote de elementos con PartiQL.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, BatchExecuteStatementCommand, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const breakfastFoods = ["Eggs", "Bacon", "Sausage"]; const command = new BatchExecuteStatementCommand({ Statements: breakfastFoods.map((food) => ({ Statement: `INSERT INTO BreakfastFoods value {'Name':?}`, Parameters: [food], })), }); const response = await docClient.send(command); console.log(response); return response; };
Obtener un lote de elementos con PartiQL.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, BatchExecuteStatementCommand, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new BatchExecuteStatementCommand({ Statements: [ { Statement: "SELECT * FROM PepperMeasurements WHERE Unit=?", Parameters: ["Teaspoons"], ConsistentRead: true, }, { Statement: "SELECT * FROM PepperMeasurements WHERE Unit=?", Parameters: ["Grams"], ConsistentRead: true, }, ], }); const response = await docClient.send(command); console.log(response); return response; };
Actualizar un lote de elementos con PartiQL.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, BatchExecuteStatementCommand, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const eggUpdates = [ ["duck", "fried"], ["chicken", "omelette"], ]; const command = new BatchExecuteStatementCommand({ Statements: eggUpdates.map((change) => ({ Statement: "UPDATE Eggs SET Style=? where Variety=?", Parameters: [change[1], change[0]], })), }); const response = await docClient.send(command); console.log(response); return response; };
Eliminar un lote de elementos con PartiQL.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, BatchExecuteStatementCommand, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new BatchExecuteStatementCommand({ Statements: [ { Statement: "DELETE FROM Flavors where Name=?", Parameters: ["Grape"], }, { Statement: "DELETE FROM Flavors where Name=?", Parameters: ["Strawberry"], }, ], }); const response = await docClient.send(command); console.log(response); return response; };
-
Para obtener más información sobre la API, consulta BatchExecuteStatementla Referencia AWS SDK for JavaScript de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar BatchGetItem
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Este ejemplo utiliza el cliente de documentos para simplificar el trabajo con elementos en DynamoDB. Para obtener detalles sobre la API, consulte BatchGet.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { BatchGetCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new BatchGetCommand({ // Each key in this object is the name of a table. This example refers // to a Books table. RequestItems: { Books: { // Each entry in Keys is an object that specifies a primary key. Keys: [ { Title: "How to AWS", }, { Title: "DynamoDB for DBAs", }, ], // Only return the "Title" and "PageCount" attributes. ProjectionExpression: "Title, PageCount", }, }, }); const response = await docClient.send(command); console.log(response.Responses.Books); return response; };
-
Para obtener información, consulte la Guía para desarrolladores de AWS SDK for JavaScript.
-
Para obtener más información sobre la API, consulte BatchGetItemla Referencia AWS SDK for JavaScript de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar BatchWriteItem
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Este ejemplo utiliza el cliente de documentos para simplificar el trabajo con elementos en DynamoDB. Para obtener detalles sobre la API, consulte BatchWrite.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { BatchWriteCommand, DynamoDBDocumentClient, } from "@aws-sdk/lib-dynamodb"; import { readFileSync } from "node:fs"; // These modules are local to our GitHub repository. We recommend cloning // the project from GitHub if you want to run this example. // For more information, see https://github.com/awsdocs/aws-doc-sdk-examples. import { dirnameFromMetaUrl } from "@aws-doc-sdk-examples/lib/utils/util-fs.js"; import { chunkArray } from "@aws-doc-sdk-examples/lib/utils/util-array.js"; const dirname = dirnameFromMetaUrl(import.meta.url); const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const file = readFileSync( `${dirname}../../../../../resources/sample_files/movies.json`, ); const movies = JSON.parse(file.toString()); // chunkArray is a local convenience function. It takes an array and returns // a generator function. The generator function yields every N items. const movieChunks = chunkArray(movies, 25); // For every chunk of 25 movies, make one BatchWrite request. for (const chunk of movieChunks) { const putRequests = chunk.map((movie) => ({ PutRequest: { Item: movie, }, })); const command = new BatchWriteCommand({ RequestItems: { // An existing table is required. A composite key of 'title' and 'year' is recommended // to account for duplicate titles. BatchWriteMoviesTable: putRequests, }, }); await docClient.send(command); } };
-
Para obtener más información sobre la API, consulte BatchWriteItemla Referencia AWS SDK for JavaScript de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar CreateTable
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. import { CreateTableCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new CreateTableCommand({ TableName: "EspressoDrinks", // For more information about data types, // see https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes and // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors AttributeDefinitions: [ { AttributeName: "DrinkName", AttributeType: "S", }, ], KeySchema: [ { AttributeName: "DrinkName", KeyType: "HASH", }, ], ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, }); const response = await client.send(command); console.log(response); return response; };
-
Para obtener información, consulte la Guía para desarrolladores de AWS SDK for JavaScript.
-
Para obtener más información sobre la API, consulta CreateTablela Referencia AWS SDK for JavaScript de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar DeleteItem
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Este ejemplo utiliza el cliente de documentos para simplificar el trabajo con elementos en DynamoDB. Para obtener detalles sobre la API, consulte DeleteCommand.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, DeleteCommand } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new DeleteCommand({ TableName: "Sodas", Key: { Flavor: "Cola", }, }); const response = await docClient.send(command); console.log(response); return response; };
-
Para obtener información, consulte la Guía para desarrolladores de AWS SDK for JavaScript.
-
Para obtener más información sobre la API, consulte DeleteItemla Referencia AWS SDK for JavaScript de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar DeleteTable
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. import { DeleteTableCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new DeleteTableCommand({ TableName: "DecafCoffees", }); const response = await client.send(command); console.log(response); return response; };
-
Para obtener más información sobre la API, consulta DeleteTablela Referencia AWS SDK for JavaScript de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar DescribeTable
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. import { DescribeTableCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new DescribeTableCommand({ TableName: "Pastries", }); const response = await client.send(command); console.log(`TABLE NAME: ${response.Table.TableName}`); console.log(`TABLE ITEM COUNT: ${response.Table.ItemCount}`); return response; };
-
Para obtener información, consulte la Guía para desarrolladores de AWS SDK for JavaScript.
-
Para obtener más información sobre la API, consulta DescribeTablela Referencia AWS SDK for JavaScript de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar DescribeTimeToLive
.
- SDK para JavaScript (v3)
-
import { DynamoDBClient, DescribeTimeToLiveCommand } from "@aws-sdk/client-dynamodb"; const describeTableTTL = async (tableName, region) => { const client = new DynamoDBClient({ region: region, endpoint: `https://dynamodb.${region}.amazonaws.com` }); try { const ttlDescription = await client.send(new DescribeTimeToLiveCommand({ TableName: tableName })); if (ttlDescription.TimeToLiveDescription.TimeToLiveStatus === 'ENABLED') { console.log("TTL is enabled for table %s.", tableName); } else { console.log("TTL is not enabled for table %s.", tableName); } return ttlDescription; } catch (e) { console.error(`Error describing table: ${e}`); throw e; } } // enter table name and change region if desired. describeTableTTL('your-table-name', 'us-east-1');
-
Para obtener más información sobre la API, consulte DescribeTimeToLivela Referencia de AWS SDK for JavaScript la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar ExecuteStatement
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Crear un elemento con PartiQL.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { ExecuteStatementCommand, DynamoDBDocumentClient, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new ExecuteStatementCommand({ Statement: `INSERT INTO Flowers value {'Name':?}`, Parameters: ["Rose"], }); const response = await docClient.send(command); console.log(response); return response; };
Obtener un elemento con PartiQL.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { ExecuteStatementCommand, DynamoDBDocumentClient, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new ExecuteStatementCommand({ Statement: "SELECT * FROM CloudTypes WHERE IsStorm=?", Parameters: [false], ConsistentRead: true, }); const response = await docClient.send(command); console.log(response); return response; };
Actualizar un elemento con PartiQL.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { ExecuteStatementCommand, DynamoDBDocumentClient, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new ExecuteStatementCommand({ Statement: "UPDATE EyeColors SET IsRecessive=? where Color=?", Parameters: [true, "blue"], }); const response = await docClient.send(command); console.log(response); return response; };
Eliminar un elemento con PartiQL.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { ExecuteStatementCommand, DynamoDBDocumentClient, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new ExecuteStatementCommand({ Statement: "DELETE FROM PaintColors where Name=?", Parameters: ["Purple"], }); const response = await docClient.send(command); console.log(response); return response; };
-
Para obtener más información sobre la API, consulta ExecuteStatementla Referencia AWS SDK for JavaScript de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar GetItem
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Este ejemplo utiliza el cliente de documentos para simplificar el trabajo con elementos en DynamoDB. Para obtener detalles sobre la API, consulte GetCommand.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, GetCommand } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new GetCommand({ TableName: "AngryAnimals", Key: { CommonName: "Shoebill", }, }); const response = await docClient.send(command); console.log(response); return response; };
-
Para obtener más información sobre la API, consulte GetItemla Referencia AWS SDK for JavaScript de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar ListTables
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. import { ListTablesCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new ListTablesCommand({}); const response = await client.send(command); console.log(response); return response; };
-
Para obtener información, consulte la Guía para desarrolladores de AWS SDK for JavaScript.
-
Para obtener más información sobre la API, consulta ListTablesla Referencia AWS SDK for JavaScript de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar PutItem
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Este ejemplo utiliza el cliente de documentos para simplificar el trabajo con elementos en DynamoDB. Para obtener detalles sobre la API, consulte PutCommand.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { PutCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new PutCommand({ TableName: "HappyAnimals", Item: { CommonName: "Shiba Inu", }, }); const response = await docClient.send(command); console.log(response); return response; };
-
Para obtener más información sobre la API, consulte PutItemla Referencia AWS SDK for JavaScript de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar Query
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Este ejemplo utiliza el cliente de documentos para simplificar el trabajo con elementos en DynamoDB. Para obtener detalles sobre la API, consulte QueryCommand.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { QueryCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new QueryCommand({ TableName: "CoffeeCrop", KeyConditionExpression: "OriginCountry = :originCountry AND RoastDate > :roastDate", ExpressionAttributeValues: { ":originCountry": "Ethiopia", ":roastDate": "2023-05-01", }, ConsistentRead: true, }); const response = await docClient.send(command); console.log(response); return response; };
-
Para obtener información, consulte la Guía para desarrolladores de AWS SDK for JavaScript.
-
Para obtener información sobre la API, consulte Query en la referencia de la API de AWS SDK for JavaScript .
-
En el siguiente ejemplo de código, se muestra cómo utilizar Scan
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Este ejemplo utiliza el cliente de documentos para simplificar el trabajo con elementos en DynamoDB. Para obtener detalles sobre la API, consulte ScanCommand.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, ScanCommand } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new ScanCommand({ ProjectionExpression: "#Name, Color, AvgLifeSpan", ExpressionAttributeNames: { "#Name": "Name" }, TableName: "Birds", }); const response = await docClient.send(command); for (const bird of response.Items) { console.log(`${bird.Name} - (${bird.Color}, ${bird.AvgLifeSpan})`); } return response; };
-
Para obtener información sobre la API, consulte Scan en la referencia de la API de AWS SDK for JavaScript .
-
En el siguiente ejemplo de código, se muestra cómo utilizar UpdateItem
.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Este ejemplo utiliza el cliente de documentos para simplificar el trabajo con elementos en DynamoDB. Para obtener detalles sobre la API, consulte UpdateCommand.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, UpdateCommand } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new UpdateCommand({ TableName: "Dogs", Key: { Breed: "Labrador", }, UpdateExpression: "set Color = :color", ExpressionAttributeValues: { ":color": "black", }, ReturnValues: "ALL_NEW", }); const response = await docClient.send(command); console.log(response); return response; };
-
Para obtener más información sobre la API, consulte UpdateItemla Referencia AWS SDK for JavaScript de la API.
-
En el siguiente ejemplo de código, se muestra cómo utilizar UpdateTimeToLive
.
- SDK para JavaScript (v3)
-
Habilite TTL en una tabla de DynamoDB existente.
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');
Deshabilite TTL en una tabla de DynamoDB existente.
import { DynamoDBClient, UpdateTimeToLiveCommand } from "@aws-sdk/client-dynamodb"; const disableTTL = async (tableName, ttlAttribute) => { const client = new DynamoDBClient({}); const params = { TableName: tableName, TimeToLiveSpecification: { Enabled: false, AttributeName: ttlAttribute } }; try { const response = await client.send(new UpdateTimeToLiveCommand(params)); if (response.$metadata.httpStatusCode === 200) { console.log(`TTL disabled successfully for table ${tableName}, using attribute name ${ttlAttribute}.`); } else { console.log(`Failed to disable TTL for table ${tableName}, response object: ${response}`); } return response; } catch (e) { console.error(`Error disabling TTL: ${e}`); throw e; } }; // call with your own values disableTTL('ExampleTable', 'exampleTtlAttribute');
-
Para obtener más información sobre la API, consulte UpdateTimeToLivela Referencia de AWS SDK for JavaScript la API.
-
Escenarios
El siguiente ejemplo de código muestra cómo crear una aplicación que envíe datos a una tabla de Amazon DynamoDB y le notifique cuando un usuario actualice la tabla.
- SDK para (v3) JavaScript
-
Este ejemplo indica cómo crear una aplicación que permita a los usuarios enviar datos a una tabla de Amazon DynamoDB y un mensaje de texto al administrador mediante Amazon Simple Notification Service (Amazon SNS).
Para ver el código fuente completo y las instrucciones sobre cómo configurarlo y ejecutarlo, consulta el ejemplo completo en GitHub
. Este ejemplo también está disponible en la Guía para desarrolladores de AWS SDK for JavaScript v3.
Servicios utilizados en este ejemplo
DynamoDB
Amazon SNS
El siguiente ejemplo de código muestra cómo actualizar de forma condicional el TTL de un elemento.
- SDK para JavaScript (v3)
-
Actualice el TTL en un elemento de DynamoDB existente en una tabla con una condición.
import { DynamoDBClient, UpdateItemCommand } from "@aws-sdk/client-dynamodb"; import { marshall, unmarshall } from "@aws-sdk/util-dynamodb"; 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');
-
Para obtener más información sobre la API, consulte UpdateItemla Referencia de AWS SDK for JavaScript la API.
-
En el siguiente ejemplo de código se muestra cómo crear una aplicación sin servidor que permita a los usuarios administrar fotos mediante etiquetas.
- SDK para JavaScript (v3)
-
Muestra cómo desarrollar una aplicación de administración de activos fotográficos que detecte las etiquetas de las imágenes mediante Amazon Rekognition y las almacene para su posterior recuperación.
Para ver el código fuente completo y las instrucciones sobre cómo configurarlo y ejecutarlo, consulta el ejemplo completo en GitHub
. Para profundizar en el origen de este ejemplo, consulte la publicación en Comunidad de AWS
. Servicios utilizados en este ejemplo
API Gateway
DynamoDB
Lambda
Amazon Rekognition
Amazon S3
Amazon SNS
El siguiente ejemplo de código muestra cómo crear una tabla con el rendimiento dinámico activado.
- SDK para JavaScript (v3)
-
import { DynamoDBClient, CreateTableCommand } from "@aws-sdk/client-dynamodb"; async function createDynamoDBTableWithWarmThroughput( tableName, partitionKey, sortKey, miscKeyAttr, nonKeyAttr, tableProvisionedReadUnits, tableProvisionedWriteUnits, tableWarmReads, tableWarmWrites, indexName, indexProvisionedReadUnits, indexProvisionedWriteUnits, indexWarmReads, indexWarmWrites, region = "us-east-1" ) { try { const ddbClient = new DynamoDBClient({ region: region }); const command = new CreateTableCommand({ TableName: tableName, AttributeDefinitions: [ { AttributeName: partitionKey, AttributeType: "S" }, { AttributeName: sortKey, AttributeType: "S" }, { AttributeName: miscKeyAttr, AttributeType: "N" }, ], KeySchema: [ { AttributeName: partitionKey, KeyType: "HASH" }, { AttributeName: sortKey, KeyType: "RANGE" }, ], ProvisionedThroughput: { ReadCapacityUnits: tableProvisionedReadUnits, WriteCapacityUnits: tableProvisionedWriteUnits, }, WarmThroughput: { ReadUnitsPerSecond: tableWarmReads, WriteUnitsPerSecond: tableWarmWrites, }, GlobalSecondaryIndexes: [ { IndexName: indexName, KeySchema: [ { AttributeName: sortKey, KeyType: "HASH" }, { AttributeName: miscKeyAttr, KeyType: "RANGE" }, ], Projection: { ProjectionType: "INCLUDE", NonKeyAttributes: [nonKeyAttr], }, ProvisionedThroughput: { ReadCapacityUnits: indexProvisionedReadUnits, WriteCapacityUnits: indexProvisionedWriteUnits, }, WarmThroughput: { ReadUnitsPerSecond: indexWarmReads, WriteUnitsPerSecond: indexWarmWrites, }, }, ], }); const response = await ddbClient.send(command); console.log(response); } catch (error) { console.error(`Error creating table: ${error}`); throw error; } }
-
Para obtener más información sobre la API, consulte CreateTablela Referencia de AWS SDK for JavaScript la API.
-
El siguiente ejemplo de código muestra cómo crear un elemento con TTL.
- SDK para JavaScript (v3)
-
import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb"; 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, ex); throw err; } else { console.log("Item created successfully: %s.", data); return data; } }); } // use your own values createDynamoDBItem('your-table-name', 'us-east-1', 'your-partition-key-value', 'your-sort-key-value');
-
Para obtener más información sobre la API, consulte PutItemla Referencia de AWS SDK for JavaScript la API.
-
El siguiente ejemplo de código muestra cómo invocar una AWS Lambda función desde un navegador.
- SDK para JavaScript (v3)
-
Puede crear una aplicación basada en un navegador que utilice una AWS Lambda función para actualizar una tabla de Amazon DynamoDB con las selecciones de los usuarios. Esta aplicación utiliza la versión 3. AWS SDK for JavaScript
Para obtener el código fuente completo y las instrucciones sobre cómo configurarlo y ejecutarlo, consulte el ejemplo completo en GitHub
. Servicios utilizados en este ejemplo
DynamoDB
Lambda
En el siguiente ejemplo de código, se muestra cómo:
Obtención de un lote de elementos mediante la ejecución de varias instrucciones SELECT.
Agregar un lote de elementos mediante la ejecución de varias instrucciones INSERT.
Actualizar un lote de elementos con la ejecución de varias instrucciones UPDATE.
Eliminación de un lote de elementos con la ejecución de varias instrucciones DELETE.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Ejecutar instrucciones PartiQL por lotes.
import { BillingMode, CreateTableCommand, DeleteTableCommand, DescribeTableCommand, DynamoDBClient, waitUntilTableExists, } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, BatchExecuteStatementCommand, } from "@aws-sdk/lib-dynamodb"; import { ScenarioInput } from "@aws-doc-sdk-examples/lib/scenario"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); const log = (msg) => console.log(`[SCENARIO] ${msg}`); const tableName = "Cities"; export const main = async (confirmAll = false) => { /** * Delete table if it exists. */ try { await client.send(new DescribeTableCommand({ TableName: tableName })); // If no error was thrown, the table exists. const input = new ScenarioInput( "deleteTable", `A table named ${tableName} already exists. If you choose not to delete this table, the scenario cannot continue. Delete it?`, { type: "confirm", confirmAll }, ); const deleteTable = await input.handle({}, { confirmAll }); if (deleteTable) { await client.send(new DeleteTableCommand({ tableName })); } else { console.warn( "Scenario could not run. Either delete ${tableName} or provide a unique table name.", ); return; } } catch (caught) { if ( caught instanceof Error && caught.name === "ResourceNotFoundException" ) { // Do nothing. This means the table is not there. } else { throw caught; } } /** * Create a table. */ log("Creating a table."); const createTableCommand = new CreateTableCommand({ TableName: tableName, // This example performs a large write to the database. // Set the billing mode to PAY_PER_REQUEST to // avoid throttling the large write. BillingMode: BillingMode.PAY_PER_REQUEST, // Define the attributes that are necessary for the key schema. AttributeDefinitions: [ { AttributeName: "name", // 'S' is a data type descriptor that represents a number type. // For a list of all data type descriptors, see the following link. // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors AttributeType: "S", }, ], // The KeySchema defines the primary key. The primary key can be // a partition key, or a combination of a partition key and a sort key. // Key schema design is important. For more info, see // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html KeySchema: [{ AttributeName: "name", KeyType: "HASH" }], }); await client.send(createTableCommand); log(`Table created: ${tableName}.`); /** * Wait until the table is active. */ // This polls with DescribeTableCommand until the requested table is 'ACTIVE'. // You can't write to a table before it's active. log("Waiting for the table to be active."); await waitUntilTableExists({ client }, { TableName: tableName }); log("Table active."); /** * Insert items. */ log("Inserting cities into the table."); const addItemsStatementCommand = new BatchExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.insert.html Statements: [ { Statement: `INSERT INTO ${tableName} value {'name':?, 'population':?}`, Parameters: ["Alachua", 10712], }, { Statement: `INSERT INTO ${tableName} value {'name':?, 'population':?}`, Parameters: ["High Springs", 6415], }, ], }); await docClient.send(addItemsStatementCommand); log("Cities inserted."); /** * Select items. */ log("Selecting cities from the table."); const selectItemsStatementCommand = new BatchExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.select.html Statements: [ { Statement: `SELECT * FROM ${tableName} WHERE name=?`, Parameters: ["Alachua"], }, { Statement: `SELECT * FROM ${tableName} WHERE name=?`, Parameters: ["High Springs"], }, ], }); const selectItemResponse = await docClient.send(selectItemsStatementCommand); log( `Got cities: ${selectItemResponse.Responses.map( (r) => `${r.Item.name} (${r.Item.population})`, ).join(", ")}`, ); /** * Update items. */ log("Modifying the populations."); const updateItemStatementCommand = new BatchExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.update.html Statements: [ { Statement: `UPDATE ${tableName} SET population=? WHERE name=?`, Parameters: [10, "Alachua"], }, { Statement: `UPDATE ${tableName} SET population=? WHERE name=?`, Parameters: [5, "High Springs"], }, ], }); await docClient.send(updateItemStatementCommand); log("Updated cities."); /** * Delete the items. */ log("Deleting the cities."); const deleteItemStatementCommand = new BatchExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.delete.html Statements: [ { Statement: `DELETE FROM ${tableName} WHERE name=?`, Parameters: ["Alachua"], }, { Statement: `DELETE FROM ${tableName} WHERE name=?`, Parameters: ["High Springs"], }, ], }); await docClient.send(deleteItemStatementCommand); log("Cities deleted."); /** * Delete the table. */ log("Deleting the table."); const deleteTableCommand = new DeleteTableCommand({ TableName: tableName }); await client.send(deleteTableCommand); log("Table deleted."); };
-
Para obtener más información sobre la API, consulta BatchExecuteStatementla Referencia AWS SDK for JavaScript de la API.
-
En el siguiente ejemplo de código, se muestra cómo:
Obtención de un artículo mediante una instrucción SELECT.
Agregar un elemento mediante una instrucción INSERT.
Actualizar un elemento mediante una instrucción UPDATE.
Eliminación de un elemento mediante una instrucción DELETE.
- SDK para JavaScript (v3)
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS
. Ejecutar instrucciones PartiQL individuales.
import { BillingMode, CreateTableCommand, DeleteTableCommand, DescribeTableCommand, DynamoDBClient, waitUntilTableExists, } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, ExecuteStatementCommand, } from "@aws-sdk/lib-dynamodb"; import { ScenarioInput } from "@aws-doc-sdk-examples/lib/scenario"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); const log = (msg) => console.log(`[SCENARIO] ${msg}`); const tableName = "SingleOriginCoffees"; export const main = async (confirmAll = false) => { /** * Delete table if it exists. */ try { await client.send(new DescribeTableCommand({ TableName: tableName })); // If no error was thrown, the table exists. const input = new ScenarioInput( "deleteTable", `A table named ${tableName} already exists. If you choose not to delete this table, the scenario cannot continue. Delete it?`, { type: "confirm", confirmAll }, ); const deleteTable = await input.handle({}); if (deleteTable) { await client.send(new DeleteTableCommand({ tableName })); } else { console.warn( "Scenario could not run. Either delete ${tableName} or provide a unique table name.", ); return; } } catch (caught) { if ( caught instanceof Error && caught.name === "ResourceNotFoundException" ) { // Do nothing. This means the table is not there. } else { throw caught; } } /** * Create a table. */ log("Creating a table."); const createTableCommand = new CreateTableCommand({ TableName: tableName, // This example performs a large write to the database. // Set the billing mode to PAY_PER_REQUEST to // avoid throttling the large write. BillingMode: BillingMode.PAY_PER_REQUEST, // Define the attributes that are necessary for the key schema. AttributeDefinitions: [ { AttributeName: "varietal", // 'S' is a data type descriptor that represents a number type. // For a list of all data type descriptors, see the following link. // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors AttributeType: "S", }, ], // The KeySchema defines the primary key. The primary key can be // a partition key, or a combination of a partition key and a sort key. // Key schema design is important. For more info, see // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html KeySchema: [{ AttributeName: "varietal", KeyType: "HASH" }], }); await client.send(createTableCommand); log(`Table created: ${tableName}.`); /** * Wait until the table is active. */ // This polls with DescribeTableCommand until the requested table is 'ACTIVE'. // You can't write to a table before it's active. log("Waiting for the table to be active."); await waitUntilTableExists({ client }, { TableName: tableName }); log("Table active."); /** * Insert an item. */ log("Inserting a coffee into the table."); const addItemStatementCommand = new ExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.insert.html Statement: `INSERT INTO ${tableName} value {'varietal':?, 'profile':?}`, Parameters: ["arabica", ["chocolate", "floral"]], }); await client.send(addItemStatementCommand); log("Coffee inserted."); /** * Select an item. */ log("Selecting the coffee from the table."); const selectItemStatementCommand = new ExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.select.html Statement: `SELECT * FROM ${tableName} WHERE varietal=?`, Parameters: ["arabica"], }); const selectItemResponse = await docClient.send(selectItemStatementCommand); log(`Got coffee: ${JSON.stringify(selectItemResponse.Items[0])}`); /** * Update the item. */ log("Add a flavor profile to the coffee."); const updateItemStatementCommand = new ExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.update.html Statement: `UPDATE ${tableName} SET profile=list_append(profile, ?) WHERE varietal=?`, Parameters: [["fruity"], "arabica"], }); await client.send(updateItemStatementCommand); log("Updated coffee"); /** * Delete the item. */ log("Deleting the coffee."); const deleteItemStatementCommand = new ExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.delete.html Statement: `DELETE FROM ${tableName} WHERE varietal=?`, Parameters: ["arabica"], }); await docClient.send(deleteItemStatementCommand); log("Coffee deleted."); /** * Delete the table. */ log("Deleting the table."); const deleteTableCommand = new DeleteTableCommand({ TableName: tableName }); await client.send(deleteTableCommand); log("Table deleted."); };
-
Para obtener más información sobre la API, consulta ExecuteStatementla Referencia AWS SDK for JavaScript de la API.
-
El siguiente ejemplo de código muestra cómo consultar elementos TTL.
- SDK para JavaScript (v3)
-
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');
-
Para obtener información sobre la API, consulte Query en la referencia de la API de AWS SDK for JavaScript .
-
El siguiente ejemplo de código muestra cómo actualizar la configuración de rendimiento en caliente de una tabla.
- SDK para JavaScript (v3)
-
import { DynamoDBClient, UpdateTableCommand } from "@aws-sdk/client-dynamodb"; async function updateDynamoDBTableWarmThroughput( tableName, tableReadUnits, tableWriteUnits, gsiName, gsiReadUnits, gsiWriteUnits, region = "us-east-1" ) { try { const ddbClient = new DynamoDBClient({ region: region }); // Construct the update table request const updateTableRequest = { TableName: tableName, GlobalSecondaryIndexUpdates: [ { Update: { IndexName: gsiName, WarmThroughput: { ReadUnitsPerSecond: gsiReadUnits, WriteUnitsPerSecond: gsiWriteUnits, }, }, }, ], WarmThroughput: { ReadUnitsPerSecond: tableReadUnits, WriteUnitsPerSecond: tableWriteUnits, }, }; const command = new UpdateTableCommand(updateTableRequest); const response = await ddbClient.send(command); console.log(`Table updated successfully! Response: ${response}`); } catch (error) { console.error(`Error updating table: ${error}`); throw error; } }
-
Para obtener más información sobre la API, consulte UpdateTablela Referencia de AWS SDK for JavaScript la API.
-
El siguiente ejemplo de código muestra cómo actualizar el TTL de un elemento.
- SDK para JavaScript (v3)
-
import { DynamoDBClient, UpdateItemCommand } from "@aws-sdk/client-dynamodb"; import { marshall, unmarshall } from "@aws-sdk/util-dynamodb"; async function updateDynamoDBItem(tableName, region, partitionKey, sortKey) { 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; } } //enter your values here updateDynamoDBItem('your-table-name', 'us-east-1', 'your-partition-key-value', 'your-sort-key-value');
-
Para obtener más información sobre la API, consulte UpdateItemla Referencia de AWS SDK for JavaScript la API.
-
Ejemplos de tecnología sin servidor
En el siguiente ejemplo de código se muestra cómo implementar una función de Lambda que recibe un evento que se desencadena al recibir registros de una transmisión de DynamoDB. La función recupera la carga útil de DynamoDB y registra el contenido del registro.
- SDK para (v3 JavaScript )
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el repositorio de ejemplos de tecnología sin servidor
. Consumir un evento de DynamoDB con Lambda mediante. JavaScript
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 exports.handler = async (event, context) => { console.log(JSON.stringify(event, null, 2)); event.Records.forEach(record => { logDynamoDBRecord(record); }); }; const logDynamoDBRecord = (record) => { console.log(record.eventID); console.log(record.eventName); console.log(`DynamoDB Record: ${JSON.stringify(record.dynamodb)}`); };
Consumir un evento de DynamoDB con Lambda mediante. TypeScript
export const handler = async (event, context) => { console.log(JSON.stringify(event, null, 2)); event.Records.forEach(record => { logDynamoDBRecord(record); }); } const logDynamoDBRecord = (record) => { console.log(record.eventID); console.log(record.eventName); console.log(`DynamoDB Record: ${JSON.stringify(record.dynamodb)}`); };
El siguiente ejemplo de código muestra cómo implementar una respuesta por lotes parcial para las funciones de Lambda que reciben eventos de una transmisión de DynamoDB. La función informa los errores de los elementos del lote en la respuesta y le indica a Lambda que vuelva a intentar esos mensajes más adelante.
- SDK para (v3 JavaScript )
-
nota
Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el repositorio de ejemplos de tecnología sin servidor
. Cómo informar de errores en los elementos de lote de DynamoDB con Lambda mediante. JavaScript
export const handler = async (event) => { const records = event.Records; let curRecordSequenceNumber = ""; for (const record of records) { try { // Process your record curRecordSequenceNumber = record.dynamodb.SequenceNumber; } catch (e) { // Return failed record's sequence number return { batchItemFailures: [{ itemIdentifier: curRecordSequenceNumber }] }; } } return { batchItemFailures: [] }; };
Cómo informar de errores en los elementos de lote de DynamoDB con Lambda mediante. TypeScript
import { DynamoDBBatchResponse, DynamoDBBatchItemFailure, DynamoDBStreamEvent, } from "aws-lambda"; export const handler = async ( event: DynamoDBStreamEvent ): Promise<DynamoDBBatchResponse> => { const batchItemFailures: DynamoDBBatchItemFailure[] = []; let curRecordSequenceNumber; for (const record of event.Records) { curRecordSequenceNumber = record.dynamodb?.SequenceNumber; if (curRecordSequenceNumber) { batchItemFailures.push({ itemIdentifier: curRecordSequenceNumber, }); } } return { batchItemFailures: batchItemFailures }; };