DynamoDB

Base de datos NoSQL clave-valor gestionada AWS - serverless, latencia milisegundos, auto-scaling

TL;DR

Qué: Una base de datos NoSQL clave-valor totalmente administrada por AWS.

Por qué: Serverless, latencia de milisegundos de un dígito, auto-scaling, pago por uso.

Quick Start

Desarrollo local con Docker:

docker run -p 8000:8000 amazon/dynamodb-local

Instalar AWS CLI:

pip install awscli
aws configure  # Usar valores ficticios para local

Crear tabla:

aws dynamodb create-table \
  --table-name Users \
  --attribute-definitions AttributeName=userId,AttributeType=S \
  --key-schema AttributeName=userId,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST \
  --endpoint-url http://localhost:8000

O usar AWS SDK:

import { DynamoDBClient, CreateTableCommand } from "@aws-sdk/client-dynamodb";
const client = new DynamoDBClient({ region: "us-east-1" });

Cheatsheet

OperaciónAWS CLI
Listar tablasaws dynamodb list-tables
Describir tablaaws dynamodb describe-table --table-name Name
Insertar itemaws dynamodb put-item --table-name Name --item '{}'
Obtener itemaws dynamodb get-item --table-name Name --key '{}'
Queryaws dynamodb query --table-name Name ...
Scanaws dynamodb scan --table-name Name
Eliminar itemaws dynamodb delete-item --table-name Name --key '{}'

Gotchas

CRUD with SDK (JavaScript)

import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand, GetCommand, QueryCommand, DeleteCommand } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

// Insertar item
await docClient.send(new PutCommand({
  TableName: "Users",
  Item: { userId: "123", name: "John", email: "[email protected]" }
}));

// Obtener item
const { Item } = await docClient.send(new GetCommand({
  TableName: "Users",
  Key: { userId: "123" }
}));

// Query (requiere partition key)
const { Items } = await docClient.send(new QueryCommand({
  TableName: "Orders",
  KeyConditionExpression: "userId = :uid",
  ExpressionAttributeValues: { ":uid": "123" }
}));

// Eliminar
await docClient.send(new DeleteCommand({
  TableName: "Users",
  Key: { userId: "123" }
}));

Key design

// Clave primaria simple (solo partition key)
{ userId: "HASH" }

// Clave primaria compuesta
{ userId: "HASH", orderId: "RANGE" }

// Global Secondary Index (GSI)
// Permite consultar por diferentes atributos

Conditional writes

await docClient.send(new PutCommand({
  TableName: "Users",
  Item: { userId: "123", name: "John" },
  ConditionExpression: "attribute_not_exists(userId)"
}));

Next Steps