Consultas con índices secundarios: GSI y LSI
Aprenda cómo los índices secundarios globales y locales permiten consultar DynamoDB por atributos distintos de la clave principal, y cómo elegir entre ellos.
Consultas con índices secundarios: GSI y LSI es una lección gratuita de Serverless Backend with AWS Lambda & API Gateway en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Serverless Backend with AWS Lambda & API Gateway, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Serverless Backend with AWS Lambda & API Gateway incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
The Primary Key Limitation
DynamoDB queries efficiently only by the primary key (partition key, optionally plus sort key). To query by other attributes you need a secondary index.
- Scanning the whole table is slow and costly
- Indexes give you efficient alternate access paths
What Is a Secondary Index?
A secondary index is an alternate view of your table data, organized by a different key. DynamoDB keeps it in sync automatically as you write to the base table.
Global Secondary Index (GSI)
A GSI can use any attributes as its partition and sort key, different from the table key. It has its own throughput and can be created anytime.
- Query by a completely different attribute
- Spans all partitions of the table
- Eventually consistent reads only
Local Secondary Index (LSI)
An LSI shares the table partition key but uses a different sort key. It must be created at table creation time and supports strongly consistent reads.
GSI vs LSI at a Glance
Choosing between them:
- GSI: different partition key, created anytime, eventually consistent
- LSI: same partition key, created with the table, strongly consistent
Defining a GSI
You specify the index name and its key schema. Reads and writes against the index are billed separately from the base table.
aws dynamodb update-table --table-name Orders \
--attribute-definitions AttributeName=status,AttributeType=S \
--global-secondary-index-updates "[{...}]"Querying an Index
To query a GSI you pass its name and the index key condition. The query returns items matching that alternate key.
aws dynamodb query --table-name Orders \
--index-name status-index \
--key-condition-expression "status = :s" \
--expression-attribute-values '{":s":{"S":"PAID"}}'Projection: Which Attributes Are Copied
An index projection controls which attributes are copied into it: keys only, a selected set, or all. Projecting fewer attributes saves storage but may force a base-table fetch.
- KEYS_ONLY: smallest, just keys
- INCLUDE: keys plus chosen attributes
- ALL: full copy, biggest
Index Throughput and Cost
GSIs consume their own read and write capacity. Every base-table write that affects an indexed attribute also writes to the GSI, so over-indexing increases cost.
Sparse Indexes
If an item lacks the index key attribute, it is not written to the index. This creates a sparse index, an efficient way to query only items that have a certain attribute set.
Designing Access Patterns First
In DynamoDB you design indexes around your access patterns, not the other way around. List the queries your app needs, then create the minimal set of indexes that serve them.
Quick Check
Test your index knowledge.
Recap
You learned how secondary indexes enable querying DynamoDB by non-primary-key attributes. You compared GSIs (flexible keys, created anytime, eventually consistent) with LSIs (shared partition key, created with the table, strongly consistent), and covered projections, throughput, sparse indexes, and access-pattern-first design.
Preguntas frecuentes
¿La lección «Consultas con índices secundarios: GSI y LSI» es gratis?
Sí — el texto completo de «Consultas con índices secundarios: GSI y LSI» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Serverless Backend with AWS Lambda & API Gateway, actualiza a CoddyKit PRO. El curso de Serverless Backend with AWS Lambda & API Gateway incluye 4 lecciones en total.
¿Qué aprenderé en «Consultas con índices secundarios: GSI y LSI»?
Aprenda cómo los índices secundarios globales y locales permiten consultar DynamoDB por atributos distintos de la clave principal, y cómo elegir entre ellos. Practicas Serverless Backend with AWS Lambda & API Gateway con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Serverless Backend with AWS Lambda & API Gateway?
No se requiere experiencia previa. Serverless Backend with AWS Lambda & API Gateway en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Consultas con índices secundarios: GSI y LSI»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Serverless Backend with AWS Lambda & API Gateway?
Sí. Cada lección de Serverless Backend with AWS Lambda & API Gateway incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Introducción a DynamoDB
- Diseño de tablas de DynamoDB
- Integración de Lambda y DynamoDB
- Consultas con índices secundarios: GSI y LSI