상세 컨텐츠

본문 제목

클라우드 파이어스토어를 활용한 고급 데이터 관리 기법

공부/Flutter

by micalcomanie 2025. 1. 1. 17:42

본문

728x90
반응형
SMALL

Firebase의 클라우드 파이어스토어(Firestore)는 실시간 동기화 및 확장성을 제공하는 NoSQL 데이터베이스입니다.
이 글에서는 Firestore의 고급 기능과 이를 활용하여 효율적으로 데이터를 관리하는 방법을 다룹니다.


1. Firestore의 주요 개념

1.1 데이터 구조

  • 컬렉션(Collection): 문서(Document)를 포함하는 상위 레벨의 컨테이너.
  • 문서(Document): 키-값 쌍으로 구성된 데이터 단위.
  • 서브컬렉션(Subcollection): 문서 내부에 추가로 중첩된 컬렉션.

1.2 읽기 및 쓰기 동작

  • 읽기 및 쓰기는 각각의 문서 단위로 처리되어 효율적이고 비용 효과적입니다.

1.3 쿼리 기능

Firestore는 강력한 쿼리 기능을 제공합니다:

  • 필터링 (e.g., where)
  • 정렬 (e.g., orderBy)
  • 페이징 (e.g., startAfter, limit)

2. Firestore 설정

Firestore를 사용하려면 cloud_firestore 패키지를 설치합니다:

# pubspec.yaml
dependencies:
  cloud_firestore: ^latest_version

터미널에서 다음 명령어를 실행합니다:

flutter pub get

3. Firestore CRUD 작업

3.1 데이터 읽기

Firestore에서 문서를 읽는 방법:

import 'package:cloud_firestore/cloud_firestore.dart';

class FirestoreService {
  final FirebaseFirestore _db = FirebaseFirestore.instance;

  // 단일 문서 읽기
  Future<DocumentSnapshot> getDocument(String collection, String docId) async {
    return await _db.collection(collection).doc(docId).get();
  }

  // 컬렉션 읽기
  Future<QuerySnapshot> getCollection(String collection) async {
    return await _db.collection(collection).get();
  }
}

3.2 데이터 쓰기

Firestore에 데이터를 추가하는 방법:

Future<void> addDocument(String collection, Map<String, dynamic> data) async {
  await FirebaseFirestore.instance.collection(collection).add(data);
}

3.3 데이터 업데이트

기존 문서를 업데이트하는 방법:

Future<void> updateDocument(String collection, String docId, Map<String, dynamic> data) async {
  await FirebaseFirestore.instance.collection(collection).doc(docId).update(data);
}

3.4 데이터 삭제

문서 또는 컬렉션을 삭제하는 방법:

Future<void> deleteDocument(String collection, String docId) async {
  await FirebaseFirestore.instance.collection(collection).doc(docId).delete();
}

4. 고급 기능

4.1 트랜잭션

여러 작업을 원자적으로 실행하여 데이터 일관성을 유지합니다.

Future<void> runTransactionExample() async {
  await FirebaseFirestore.instance.runTransaction((transaction) async {
    DocumentReference ref = FirebaseFirestore.instance.collection('users').doc('user1');

    DocumentSnapshot snapshot = await transaction.get(ref);

    if (snapshot.exists) {
      int currentBalance = snapshot['balance'];
      transaction.update(ref, {'balance': currentBalance + 100});
    }
  });
}

4.2 배치 작업

여러 문서를 동시에 처리할 때 사용합니다.

Future<void> batchWriteExample() async {
  WriteBatch batch = FirebaseFirestore.instance.batch();

  DocumentReference ref1 = FirebaseFirestore.instance.collection('users').doc('user1');
  DocumentReference ref2 = FirebaseFirestore.instance.collection('users').doc('user2');

  batch.update(ref1, {'active': true});
  batch.set(ref2, {'name': 'New User', 'active': false});

  await batch.commit();
}

4.3 실시간 데이터 동기화

실시간 업데이트를 처리하려면 snapshots 메서드를 사용합니다:

StreamBuilder<QuerySnapshot>(
  stream: FirebaseFirestore.instance.collection('messages').snapshots(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return CircularProgressIndicator();
    }
    List<DocumentSnapshot> docs = snapshot.data!.docs;
    return ListView.builder(
      itemCount: docs.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(docs[index]['text']),
        );
      },
    );
  },
)

5. 성능 최적화

5.1 인덱싱

Firestore는 기본적으로 모든 필드에 인덱스를 생성합니다. 복잡한 쿼리를 위해 수동으로 인덱스를 추가해야 할 수도 있습니다. Firestore 인덱스 관리를 참고하세요.

5.2 캐싱

Firestore는 오프라인에서도 데이터를 사용할 수 있도록 캐싱을 지원합니다.

FirebaseFirestore.instance.settings = Settings(persistenceEnabled: true);

5.3 페이징

대량 데이터를 효율적으로 처리하려면 페이징을 구현합니다:

Query query = FirebaseFirestore.instance.collection('users').orderBy('name').limit(10);

DocumentSnapshot lastVisible;

Future<QuerySnapshot> loadMoreData() async {
  if (lastVisible != null) {
    query = query.startAfterDocument(lastVisible);
  }

  QuerySnapshot snapshot = await query.get();
  if (snapshot.docs.isNotEmpty) {
    lastVisible = snapshot.docs.last;
  }
  return snapshot;
}

6. 결론

Firestore는 간단한 데이터베이스 작업부터 고급 데이터 관리까지 다양한 기능을 제공합니다. 트랜잭션, 배치 작업, 실시간 동기화와 같은 고급 기능을 활용하여 강력하고 효율적인 앱을 개발해보세요. 다음 글에서는 Firestore와 클라우드 함수(Firebase Cloud Functions)를 결합하여 더욱 정교한 백엔드 로직을 구현하는 방법을 다룰 예정입니다.


참고 자료

728x90
반응형
LIST

관련글 더보기