Индексация запросов для повышения производительности
Ускоряйте запросы Realtime Database и обеспечивайте их соответствие правилам: объявляйте индексы с помощью .indexOn, понимайте их значение и избегайте предупреждений о запросах без индексов.
«Индексация запросов для повышения производительности» — бесплатный урок Firebase Auth & Realtime Database Apps на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Firebase Auth & Realtime Database Apps, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Firebase Auth & Realtime Database Apps содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Indexing Matters
Querying with orderByChild works on small data, but as nodes grow, unindexed queries force the client to download and sort everything. That is slow and expensive.
Indexes tell Firebase to pre-sort data on the server for a given field.
The Unindexed Warning
Run an orderByChild query on a field with no index and Firebase logs a warning: it had to perform the sort on the client. In large datasets this is a real performance problem.
Declaring an Index
Indexes are declared in your Security Rules using the .indexOn directive at the parent of the records you query.
{
"rules": {
"users": {
".indexOn": ["age"]
}
}
}Matching the Query to the Index
The indexed field must match the field you order by. This query benefits from the age index above.
import { ref, query, orderByChild } from 'firebase/database';
const q = query(ref(db, 'users'), orderByChild('age'));Indexing Multiple Fields
You can index several fields under the same node by listing them. Each supports a different orderByChild query.
{
"rules": {
"products": {
".indexOn": ["price", "rating", "createdAt"]
}
}
}Indexing on $key and $value
For queries using orderByKey or orderByValue, use the special tokens .key and .value in the index list.
{
"rules": {
"leaderboard": {
".indexOn": ".value"
}
}
}Indexing Under Dynamic Paths
When records sit under a dynamic parent (like per-user lists), put .indexOn inside a wildcard segment so it applies to every child group.
{
"rules": {
"posts": {
"$uid": {
".indexOn": ["timestamp"]
}
}
}
}Indexes Are Free to Maintain
Unlike some databases, Realtime Database indexes add no extra storage cost and are maintained automatically. The trade-off is simply that you must declare them in rules ahead of time.
Index vs Data Structure
Indexing speeds queries, but it does not replace good data modeling. If you constantly query by a field, consider also restructuring data so the common access pattern is a direct lookup.
Limitations to Remember
Keep these constraints in mind:
- You can order by only one field per query
- The index field must exist on the child for it to appear in results
- Deeply nested data is harder to index efficiently
Verifying Your Index
After deploying rules, re-run the query and confirm the unindexed warning is gone from the logs. That confirms the server is now doing the sort.
Quick Check
Test your understanding of query indexing.
Recap
Your queries are now ready to scale.
- Unindexed
orderByChildsorts on the client and warns - Declare indexes with
.indexOnin Security Rules - Match the indexed field to your query field
- Use
.key/.valuefor key and value ordering - Index inside wildcards for dynamic parents
Изучай Firebase Auth & Realtime Database Apps с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 11
- Уроки
- 44
Часто задаваемые вопросы
Урок «Индексация запросов для повышения производительности» бесплатный?
Да — полный текст урока «Индексация запросов для повышения производительности» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Firebase Auth & Realtime Database Apps, подпишись на CoddyKit PRO. Курс Firebase Auth & Realtime Database Apps содержит 4 уроков всего.
Чему я научусь в уроке «Индексация запросов для повышения производительности»?
Ускоряйте запросы Realtime Database и обеспечивайте их соответствие правилам: объявляйте индексы с помощью .indexOn, понимайте их значение и избегайте предупреждений о запросах без индексов. Ты практикуешь Firebase Auth & Realtime Database Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Firebase Auth & Realtime Database Apps?
Предыдущий опыт не требуется. Firebase Auth & Realtime Database Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Индексация запросов для повышения производительности»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Firebase Auth & Realtime Database Apps?
Да. Каждый урок Firebase Auth & Realtime Database Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Базовые запросы к данным
- Фильтрация и сортировка данных
- Методы разбиения данных на страницы
- Индексация запросов для повышения производительности