데이터 필터링 및 정렬
특정 기준에 따라 데이터를 필터링하고 Firebase 쿼리를 사용하여 결과를 효율적으로 정렬하는 방법을 학습합니다.
데이터 필터링 및 정렬은(는) CoddyKit의 무료 Firebase Auth & Realtime Database Apps 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 exactlyvalue.startAt(value): Starts retrieving items fromvalueonwards.endAt(value): Stops retrieving items atvalue.
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
orderBymethod 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(), ororderByValue()to sort. - Apply
equalTo(),startAt(), andendAt()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.
자주 묻는 질문
“데이터 필터링 및 정렬” 강의는 무료인가요?
네 — “데이터 필터링 및 정렬” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Firebase Auth & Realtime Database Apps 강의 전체를 잠금 해제할 수 있습니다. Firebase Auth & Realtime Database Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
“데이터 필터링 및 정렬”에서 뭘 배우나요?
특정 기준에 따라 데이터를 필터링하고 Firebase 쿼리를 사용하여 결과를 효율적으로 정렬하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Firebase Auth & Realtime Database Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Firebase Auth & Realtime Database Apps을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Firebase Auth & Realtime Database Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“데이터 필터링 및 정렬” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Firebase Auth & Realtime Database Apps 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Firebase Auth & Realtime Database Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 기본 데이터 쿼리
- 데이터 필터링 및 정렬
- 데이터 페이지 매김 기법
- 성능을 위한 쿼리 인덱싱