0Pricing
Firebase Auth & Realtime Database Apps · 课时

筛选与排序数据

学习根据特定条件筛选数据,并使用 Firebase 查询高效地排列结果

筛选与排序数据 是 CoddyKit 上的免费 Firebase Auth & Realtime Database Apps 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Firebase Auth & Realtime Database Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Firebase Auth & Realtime Database Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Shape Your Realtime Data

Welcome back! In the Realtime Database, data often needs to be organized or filtered before it's useful. This lesson teaches you how to precisely shape your data.

We'll cover how to sort data using different criteria and filter it to find exactly what you need.

The Need for Precision

Imagine a list of products, users, or messages. Without filtering and ordering, you'd download everything, which is inefficient and slow.

  • Filtering: Narrows down results to specific criteria (e.g., "products in stock").
  • Ordering: Arranges results in a meaningful sequence (e.g., "users by name A-Z").

These operations are crucial for building responsive and data-efficient apps.

Sorting with orderBy()

Firebase Realtime Database allows you to order your data using a single orderBy method. You can order by a child key, the item's key, or its value.

  • orderByChild("keyName"): Sorts by the value of a specified child key.
  • orderByKey(): Sorts by the unique keys of your data items.
  • orderByValue(): Sorts by the values of your data items directly (if they are simple values).

orderByChild() in Action

Let's say you have a list of users, each with a "score". You can order them by their score.

Try running this example to see how the query is structured:

public class OrderByChildDemo {
  public static void main(String[] args) {
    System.out.println("--- Firebase Query for Users by Score ---");
    System.out.println("Imagine a database path: 'users'");
    System.out.println("To order users by their 'score' child:");
    System.out.println("  .orderByChild(\"score\")");
    System.out.println("\nThis query prepares to fetch users ordered by 'score'.");
    System.out.println("Real Firebase query would look like:");
    System.out.println("// Query usersByScore = databaseRef.child(\"users\")");
    System.out.println("//                          .orderByChild(\"score\");");
  }
}

Pinpointing Data Filters

Once ordered, you can filter your data. These methods define the range or exact match:

  • equalTo(value): Finds items where the ordered child/key/value is exactly value.
  • startAt(value): Starts retrieving items from value onwards.
  • endAt(value): Stops retrieving items at value.

These are always used after an orderBy method.

Finding Specific Items

If you want to find all users with a specific status, equalTo() is your go-to. It's often combined with orderByChild().

Here's how you'd query for users with a "status" of "active":

public class EqualToDemo {
  public static void main(String[] args) {
    System.out.println("--- Firebase Query for Active Users ---");
    System.out.println("Imagine a database path: 'users'");
    System.out.println("To find users where 'status' is 'active':");
    System.out.println("  .orderByChild(\"status\")");
    System.out.println("  .equalTo(\"active\")");
    System.out.println("\nThis query would fetch users with 'status' set to 'active'.");
    System.out.println("Real Firebase query would look like:");
    System.out.println("// Query activeUsers = databaseRef.child(\"users\")");
    System.out.println("//                         .orderByChild(\"status\")");
    System.out.println("//                         .equalTo(\"active\");");
  }
}

Data within a Range

Need data between two values? startAt() and endAt() are perfect for this. For example, finding products within a price range.

This example shows how to query for items where the "price" is between 10.0 and 50.0:

public class RangeQueryDemo {
  public static void main(String[] args) {
    System.out.println("--- Firebase Query for Price Range ---");
    System.out.println("Imagine a database path: 'products'");
    System.out.println("To find products with 'price' between 10.0 and 50.0:");
    System.out.println("  .orderByChild(\"price\")");
    System.out.println("  .startAt(10.0)");
    System.out.println("  .endAt(50.0)");
    System.out.println("\nThis query would fetch products with 'price' in the specified range.");
    System.out.println("Real Firebase query would look like:");
    System.out.println("// Query affordableProducts = databaseRef.child(\"products\")");
    System.out.println("//                                .orderByChild(\"price\")");
    System.out.println("//                                .startAt(10.0)");
    System.out.println("//                                .endAt(50.0);");
  }
}

Powerful Combined Queries

The true power comes from combining orderBy() with startAt(), endAt(), or equalTo(). Remember:

  • You can only use one orderBy method per query.
  • Filter methods like startAt() must correspond to the property you're ordering by.

This ensures efficient indexing and retrieval.

Fetching Top Scores

Let's get the top 5 users with scores greater than 100. This combines ordering, a start filter, and a limit (limitToFirst() or limitToLast(), which are related to pagination but also used for filtering 'top N').

We'll order by score, start at 100, and take the first few results.

public class CombinedQueryDemo {
  public static void main(String[] args) {
    System.out.println("--- Firebase Query for Top Scores ---");
    System.out.println("Imagine a database path: 'players'");
    System.out.println("To get players with score > 100, ordered by score, limited to 5:");
    System.out.println("  .orderByChild(\"score\")");
    System.out.println("  .startAt(100)");
    System.out.println("  .limitToFirst(5)");
    System.out.println("\nThis query would fetch the first 5 players with 'score' >= 100.");
    System.out.println("Real Firebase query would look like:");
    System.out.println("// Query topPlayers = databaseRef.child(\"players\")");
    System.out.println("//                          .orderByChild(\"score\")");
    System.out.println("//                          .startAt(100)");
    System.out.println("//                          .limitToFirst(5);");
  }
}

Optimizing with Indexes

For efficient ordering and filtering on child keys, you need to define indexes in your Firebase Realtime Database Security Rules.

Without indexes, Firebase will download all data and filter/order it client-side, which is slow and costly. Add ".indexOn": ["yourKey"] to your rules for frequently queried fields.

Querying Knowledge Check

Which of the following Firebase Realtime Database query methods are used to filter data based on a specific range or exact value?

Filtering & Ordering Summary

Great job! You've learned how to effectively filter and order data in Firebase Realtime Database.

  • Use orderByChild(), orderByKey(), or orderByValue() to sort.
  • Apply equalTo(), startAt(), and endAt() for precise filtering.
  • Combine these methods for powerful, specific queries.
  • Remember to add indexes for performance!

Next, we'll explore techniques for handling large datasets using pagination.

常见问题解答

「筛选与排序数据」课时是免费的吗?

是的 — 「筛选与排序数据」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Firebase Auth & Realtime Database Apps 课程的其余内容,请升级到 CoddyKit PRO。 Firebase Auth & Realtime Database Apps 课程共包含 4 节课。

「筛选与排序数据」这节课中我会学到什么?

学习根据特定条件筛选数据,并使用 Firebase 查询高效地排列结果 你通过在浏览器中直接运行的动手代码来练习 Firebase Auth & Realtime Database Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Firebase Auth & Realtime Database Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Firebase Auth & Realtime Database Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「筛选与排序数据」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Firebase Auth & Realtime Database Apps 课中编写并运行代码吗?

能。每节 Firebase Auth & Realtime Database Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 基本数据查询
  2. 筛选与排序数据
  3. 数据分页技术
  4. 为查询建立索引以提升性能
← 返回 Firebase Auth & Realtime Database Apps