Запросы по вторичным индексам: GSI и LSI
Узнайте, как глобальные и локальные вторичные индексы позволяют выполнять запросы к DynamoDB по атрибутам, отличным от первичного ключа, и как выбирать между ними.
«Запросы по вторичным индексам: GSI и LSI» — бесплатный урок Serverless Backend with AWS Lambda & API Gateway на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Serverless Backend with AWS Lambda & API Gateway, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Serverless Backend with AWS Lambda & API Gateway содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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.
Часто задаваемые вопросы
Урок «Запросы по вторичным индексам: GSI и LSI» бесплатный?
Да — полный текст урока «Запросы по вторичным индексам: GSI и LSI» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Serverless Backend with AWS Lambda & API Gateway, подпишись на CoddyKit PRO. Курс Serverless Backend with AWS Lambda & API Gateway содержит 4 уроков всего.
Чему я научусь в уроке «Запросы по вторичным индексам: GSI и LSI»?
Узнайте, как глобальные и локальные вторичные индексы позволяют выполнять запросы к DynamoDB по атрибутам, отличным от первичного ключа, и как выбирать между ними. Ты практикуешь Serverless Backend with AWS Lambda & API Gateway с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Serverless Backend with AWS Lambda & API Gateway?
Предыдущий опыт не требуется. Serverless Backend with AWS Lambda & API Gateway на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Запросы по вторичным индексам: GSI и LSI»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Serverless Backend with AWS Lambda & API Gateway?
Да. Каждый урок Serverless Backend with AWS Lambda & API Gateway включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Введение в DynamoDB
- Проектирование таблиц DynamoDB
- Интеграция Lambda и DynamoDB
- Запросы по вторичным индексам: GSI и LSI