프로젝트의 build.gradle에 의존성 추가
buildscript {
dependencies {
classpath 'com.google.gms:google-services:4.3.14'
}
}
사용할 모듈(app)의 build.gradle에 id 및 의존성 추가
plugins {
.....
id 'com.google.gms.google-services'
}
dependencies {
.......
implementation platform ('com.google.firebase:firebase-bom:31.0.3')
implementation 'com.google.firebase:firebase-firestore-ktx'
}
BoM(Bill of Materials)을 사용하면 BoM에 선언된 개별 라이브러리 버전을 자동으로 매핑해서 가져온다.
만약 Firebase의 여러 라이브러리를 사용해야 하고 각각의 버전을 직접 관리하고 싶다면 BOM 없이 직접 선언하면 된다.
dependencies {
.......
implementation 'com.google.firebase:firebase-firestore-ktx:24.4.0'
}
마지막으로 Firebase에 앱을 등록하면 받을 수 있는 google-services.json
을 사용할 모듈의 최상단에 넣어줘야 한다.
// 초기화 후 사용
val db = Firebase.firestore
// 내부 코드
val Firebase.firestore: FirebaseFirestore
get() = FirebaseFirestore.getInstance()
/* ------------ */
@NonNull
public static FirebaseFirestore getInstance() {
FirebaseApp app = FirebaseApp.getInstance();
if (app == null) {
throw new IllegalStateException("You must call FirebaseApp.initializeApp first.");
}
return getInstance(app, DatabaseId.DEFAULT_DATABASE_ID);
}
val user1 = hashMapOf("first" to "hello", "second" to "world", "세번째" to "데이터")
data class User(val name: String, val team: String)
val user2 = User("김이박", "부스트")
data class Data(val key:String)
val user3 = hashMapOf("first" to "hello!", Data("value!"))
db.collection("users").document("doc")
.set("first" to "hello", "second" to "world")
db.collection("users").document("doc")
.set(mapOf("first" to "value"), SetOptions.merge())
users/doc
에 데이터를 저장한다.doc
이 있으면 데이터를 덮어쓰며 기존 값은 모두 제거된다.SetOptions.merge()
를 사용하면 기존 데이터와 병합한다.db.collection("users").add(user1)
db.collection("users").document().set(user1)
// -------------------------------
fun document(): DocumentReference {
return document(Util.autoId());
}
users
컬렉션에 자동으로 생성된 ID로 문서를 생성한다.users/{무작위 id}
가 된다.db.collection("users").document("doc")
.update(mapOf("first" to "hi!!!!"))
db.collection("users").document("doc")
.update("first", "hi!!!!")
db.collection("users").document("doc")
.update("location", "seoul")
// Atomically add a new region to the "regions" array field.
washingtonRef.update("regions", FieldValue.arrayUnion("greater_virginia"))
// Atomically remove a region from the "regions" array field.
washingtonRef.update("regions", FieldValue.arrayRemove("east_coast"))
// Atomically increment the population of the city by 50.
washingtonRef.update("population", FieldValue.increment(50))
arrayUnion
과 arrayRemove
로 배열에 데이터를 추가하거나 제거할 수 있다.increment
로 값을 증가시킬 수 있다.db.collection("cities").document("SF").get()
.addOnSuccessListener { documentSnapshot->
if (documentSnapshot!= null) {
Log.d(TAG, "DocumentSnapshot data: ${documentSnapshot.data}")
} else {
Log.d(TAG, "No such document")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}
/* --------------------------- */
db.collection("cities")
.get()
.addOnSuccessListener { result ->
for (document in result) {
Log.d(TAG, "${document.id} => ${document.data}")
}
}
collection
이나 document
가 존재하지 않으면 success
이지만 결과가 null
이다.document
를 지정하지 않으면 해당 collection
의 모든 문서를 가져온다.val source = Source.CACHE
docRef.get(source)
DEFAULT
, SERVER
, CACHE
를 지원한다.DEFAULT
: 항상 서버에서 데이터를 가져오며, 오프라인 일 때 캐시에 저장된 데이터를 사용한다.SERVER
: 항상 서버에서 데이터를 가져오며, 오프라인 일 때 오류를 발생시킨다.CACHE
: 캐시된 데이터가 있으면 그 데이터를 사용한다.documentSnapshot.toObject<City>()
documentSnapshot.toObject(City::class.java)
var
을 사용해야 하며 초기값을 지정해야 한다.<
less than<=
less than or equal to==
equal to>
greater than>=
greater than or equal to[!=
not equal to](https://firebase.google.com/docs/firestore/query-data/queries#not_equal)[array-contains](https://firebase.google.com/docs/firestore/query-data/queries#array_membership)
[array-contains-any](https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any)
[in](https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any)
[not-in](https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any)
db.collection("cities")
.whereEqualTo("capital", true)
.get()
db.collection("cities")
.whereArrayContains("regions", "west_coast")
data class User(
@set:PropertyName("name")
@get:PropertyName("name")
var userName: String = "",
var team: String = ""
)
PropertyName("~~~")
을 사용하면 안 된다.is
인 경우 해당 변수에 @field:JvmField
를 추가해야 한다.db.collection("cities")
.add(data)
.addOnSuccessListener { documentReference ->
Log.d(TAG, "DocumentSnapshot written with ID: ${documentReference.id}")
}
.addOnFailureListener { e ->
Log.w(TAG, "Error adding document", e)
}
addOnFailureListener
를 사용하면 실패해도 앱이 종료되지 않는다.Firestore | Firebase
NoSQL이란 무엇인가? 대량데이터 동시처리위한 DBMS 종류와 특징 - SAMSUNG SDS
NoSQL이란? - Amazon