이 빠른 시작에서는 C#, Go, 자바, Node.js, PHP, Python 또는 Ruby 서버 클라이언트 라이브러리를 사용하여 Firestore를 설정하고, 데이터를 추가하고, 데이터를 읽는 방법을 설명합니다.
시작하기 전에
-
Google 계정으로
로그인합니다.
아직 계정이 없으면 새 계정을 등록하세요.
-
Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.
기본 모드 데이터베이스에서 Firestore 만들기
새 프로젝트인 경우 Firestore 데이터베이스 인스턴스를 만들어야 합니다.
데이터베이스 서비스 선택 화면에서 기본 모드의 Firestore를 선택합니다.
Firestore 위치를 선택합니다.
이 위치 설정이 프로젝트의 기본 Google Cloud Platform(GCP) 리소스 위치입니다. 이 위치는 특히 기본 Cloud Storage 버킷 및 App Engine 앱(Cloud Scheduler 사용 시 필요)과 같이 위치 설정이 필요한 프로젝트의 GCP 서비스에 사용됩니다.
데이터베이스 만들기를 클릭합니다.
Firestore 프로젝트를 만들면 Cloud API Manager에서도 API가 사용 설정됩니다.
인증 설정
클라이언트 라이브러리를 실행하려면 먼저 서비스 계정을 만들고 환경 변수를 설정하여 인증을 설정해야 합니다.
Cloud Console
-
Cloud Console에서 서비스 계정 키 만들기 페이지로 이동합니다.
서비스 계정 키 만들기 페이지로 이동 - 서비스 계정 목록에서 새 서비스 계정을 선택합니다.
- 서비스 계정 이름 필드에 이름을 입력합니다.
역할 목록에서 프로젝트 > 소유자.
- 만들기를 클릭합니다. 키가 포함된 JSON 파일이 컴퓨터에 다운로드됩니다.
명령줄
로컬 머신 또는 Cloud Shell에서 Cloud SDK를 사용하여 다음 명령어를 실행할 수 있습니다.
-
서비스 계정을 만듭니다. NAME을 서비스 계정 이름으로 바꿉니다.
gcloud iam service-accounts create NAME
-
서비스 계정에 권한을 부여합니다. PROJECT_ID를 프로젝트 ID로 바꿉니다.
gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:NAME@PROJECT_ID.iam.gserviceaccount.com" --role="roles/owner"
-
키 파일을 생성합니다. FILE_NAME을 키 파일 이름으로 바꿉니다.
gcloud iam service-accounts keys create FILE_NAME.json --iam-account=NAME@PROJECT_ID.iam.gserviceaccount.com
GOOGLE_APPLICATION_CREDENTIALS
환경 변수를 설정하여 애플리케이션 코드에 사용자 인증 정보를 제공합니다.
[PATH]를 서비스 계정 키가 포함된 JSON 파일의 파일 경로로 바꿉니다. 이 변수는 현재 셸 세션에만 적용되므로 새 세션을 연 경우 변수를 다시 설정합니다.
Linux 또는 macOS
export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
예를 들면 다음과 같습니다.
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"
Windows
PowerShell:
$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
예를 들면 다음과 같습니다.
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\my-key.json"
명령어 프롬프트:
set GOOGLE_APPLICATION_CREDENTIALS=[PATH]
앱에 서버 클라이언트 라이브러리 추가
필요한 종속 항목과 클라이언트 라이브러리를 앱에 추가합니다.
자바
앱에 Firestore 자바 라이브러리를 추가합니다.
-
Gradle 사용:
compile 'com.google.cloud:google-cloud-firestore:1.32.0'
-
Maven 사용:
<dependencyManagement> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>libraries-bom</artifactId> <version>18.0.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-firestore</artifactId> </dependency>
-
IDE 사용:
IntelliJ 또는 Eclipse를 사용하는 경우 다음과 같은 IDE 플러그인을 사용하여 클라이언트 라이브러리를 프로젝트에 추가할 수 있습니다.
이 플러그인은 서비스 계정의 키 관리와 같은 추가 기능을 제공합니다. 자세한 내용은 각 플러그인의 문서를 참조하세요.
Python
앱에 Firestore Python 라이브러리를 추가합니다.
pip install --upgrade google-cloud-firestore
Node.js
앱에 Firestore Node.js 라이브러리를 추가합니다.
npm install --save @google-cloud/firestore
Go
Firestore Go 라이브러리를 설치합니다.
go get cloud.google.com/go/firestore
앱에 Firestore Go 라이브러리를 추가합니다.
import "cloud.google.com/go/firestore"
PHP
- 클라이언트 라이브러리를 사용하는 데 필요한 PHP용 gRPC 확장 프로그램을 설치하고 사용 설정합니다.
-
앱에 Firestore PHP 라이브러리를 추가합니다.
composer require google/cloud-firestore
C#
-
.csproj
파일의 앱에 Firestore C# 라이브러리를 추가합니다.<ItemGroup> <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" /> </ItemGroup>
-
Program.cs
파일에 다음을 추가합니다.using Google.Cloud.Firestore;
Ruby
-
Gemfile
의 앱에 Firestore Ruby 라이브러리를 추가합니다.gem "google-cloud-firestore"
-
다음을 사용하여
Gemfile
의 종속 항목을 설치합니다.bundle install
Firestore 초기화
Firestore의 인스턴스를 초기화합니다.
자바
import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.FirestoreOptions; FirestoreOptions firestoreOptions = FirestoreOptions.getDefaultInstance().toBuilder() .setProjectId(projectId) .setCredentials(GoogleCredentials.getApplicationDefault()) .build(); Firestore db = firestoreOptions.getService();
Python
from google.cloud import firestore # Project ID is determined by the GCLOUD_PROJECT environment variable db = firestore.Client()
Node.js
const Firestore = require('@google-cloud/firestore'); const db = new Firestore({ projectId: 'YOUR_PROJECT_ID', keyFilename: '/path/to/keyfile.json', });
Go
import ( "context" "fmt" "log" "google.golang.org/api/iterator" "cloud.google.com/go/firestore" ) func createClient(ctx context.Context) *firestore.Client { // Sets your Google Cloud Platform project ID. projectID := "YOUR_PROJECT_ID" client, err := firestore.NewClient(ctx, projectID) if err != nil { log.Fatalf("Failed to create client: %v", err) } // Close client when done with // defer client.Close() return client }
PHP
use Google\Cloud\Firestore\FirestoreClient; /** * Initialize Cloud Firestore with default project ID. * ``` * initialize(); * ``` */ function initialize() { // Create the Cloud Firestore client $db = new FirestoreClient(); printf('Created Cloud Firestore client with default project ID.' . PHP_EOL); }
C#
FirestoreDb db = FirestoreDb.Create(project); Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
Ruby
require "google/cloud/firestore" firestore = Google::Cloud::Firestore.new project_id: project_id puts "Created Cloud Firestore client with given project ID."
데이터 추가
Firestore는 컬렉션에 저장되는 문서에 데이터를 저장합니다. 문서에 데이터를 처음 추가할 때 Firestore는 암시적으로 컬렉션과 문서를 만듭니다. 컬렉션이나 문서를 명시적으로 만들 필요가 없습니다.
다음 예시 코드를 사용하여 새 컬렉션과 문서를 만듭니다.
자바
DocumentReference docRef = db.collection("users").document("alovelace"); // Add document data with id "alovelace" using a hashmap Map<String, Object> data = new HashMap<>(); data.put("first", "Ada"); data.put("last", "Lovelace"); data.put("born", 1815); //asynchronously write data ApiFuture<WriteResult> result = docRef.set(data); // ... // result.get() blocks on response System.out.println("Update time : " + result.get().getUpdateTime());
Python
doc_ref = db.collection(u'users').document(u'alovelace') doc_ref.set({ u'first': u'Ada', u'last': u'Lovelace', u'born': 1815 })
Node.js
const docRef = db.collection('users').doc('alovelace'); await docRef.set({ first: 'Ada', last: 'Lovelace', born: 1815 });
Go
_, _, err := client.Collection("users").Add(ctx, map[string]interface{}{ "first": "Ada", "last": "Lovelace", "born": 1815, }) if err != nil { log.Fatalf("Failed adding alovelace: %v", err) }
PHP
$docRef = $db->collection('users')->document('lovelace'); $docRef->set([ 'first' => 'Ada', 'last' => 'Lovelace', 'born' => 1815 ]); printf('Added data to the lovelace document in the users collection.' . PHP_EOL);
C#
DocumentReference docRef = db.Collection("users").Document("alovelace"); Dictionary<string, object> user = new Dictionary<string, object> { { "First", "Ada" }, { "Last", "Lovelace" }, { "Born", 1815 } }; await docRef.SetAsync(user);
Ruby
doc_ref = firestore.doc "#{collection_path}/alovelace" doc_ref.set( first: "Ada", last: "Lovelace", born: 1815 ) puts "Added data to the alovelace document in the users collection."
이제 users
컬렉션에 다른 문서를 추가합니다. 첫 번째 문서에는 나타나지 않는 키-값 쌍(중간 이름)이 문서에 포함된다는 점에 유의하세요. 컬렉션의 문서에는 다른 정보 집합이 포함될 수 있습니다.
자바
DocumentReference docRef = db.collection("users").document("aturing"); // Add document data with an additional field ("middle") Map<String, Object> data = new HashMap<>(); data.put("first", "Alan"); data.put("middle", "Mathison"); data.put("last", "Turing"); data.put("born", 1912); ApiFuture<WriteResult> result = docRef.set(data); System.out.println("Update time : " + result.get().getUpdateTime());
Python
doc_ref = db.collection(u'users').document(u'aturing') doc_ref.set({ u'first': u'Alan', u'middle': u'Mathison', u'last': u'Turing', u'born': 1912 })
Node.js
const aTuringRef = db.collection('users').doc('aturing'); await aTuringRef.set({ 'first': 'Alan', 'middle': 'Mathison', 'last': 'Turing', 'born': 1912 });
Go
_, _, err = client.Collection("users").Add(ctx, map[string]interface{}{ "first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912, }) if err != nil { log.Fatalf("Failed adding aturing: %v", err) }
PHP
$docRef = $db->collection('users')->document('aturing'); $docRef->set([ 'first' => 'Alan', 'middle' => 'Mathison', 'last' => 'Turing', 'born' => 1912 ]); printf('Added data to the aturing document in the users collection.' . PHP_EOL);
C#
DocumentReference docRef = db.Collection("users").Document("aturing"); Dictionary<string, object> user = new Dictionary<string, object> { { "First", "Alan" }, { "Middle", "Mathison" }, { "Last", "Turing" }, { "Born", 1912 } }; await docRef.SetAsync(user);
Ruby
doc_ref = firestore.doc "#{collection_path}/aturing" doc_ref.set( first: "Alan", middle: "Mathison", last: "Turing", born: 1912 ) puts "Added data to the aturing document in the users collection."
데이터 읽기
Firestore에 추가한 데이터를 빠르게 확인하려면 Firebase Console의 데이터 뷰어를 사용합니다.
get
메서드를 사용하여 전체 컬렉션을 검색할 수도 있습니다.
자바
// asynchronously retrieve all users ApiFuture<QuerySnapshot> query = db.collection("users").get(); // ... // query.get() blocks on response QuerySnapshot querySnapshot = query.get(); List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments(); for (QueryDocumentSnapshot document : documents) { System.out.println("User: " + document.getId()); System.out.println("First: " + document.getString("first")); if (document.contains("middle")) { System.out.println("Middle: " + document.getString("middle")); } System.out.println("Last: " + document.getString("last")); System.out.println("Born: " + document.getLong("born")); }
Python
users_ref = db.collection(u'users') docs = users_ref.stream() for doc in docs: print(f'{doc.id} => {doc.to_dict()}')
Node.js
const snapshot = await db.collection('users').get(); snapshot.forEach((doc) => { console.log(doc.id, '=>', doc.data()); });
Go
iter := client.Collection("users").Documents(ctx) for { doc, err := iter.Next() if err == iterator.Done { break } if err != nil { log.Fatalf("Failed to iterate: %v", err) } fmt.Println(doc.Data()) }
PHP
$usersRef = $db->collection('users'); $snapshot = $usersRef->documents(); foreach ($snapshot as $user) { printf('User: %s' . PHP_EOL, $user->id()); printf('First: %s' . PHP_EOL, $user['first']); if (!empty($user['middle'])) { printf('Middle: %s' . PHP_EOL, $user['middle']); } printf('Last: %s' . PHP_EOL, $user['last']); printf('Born: %d' . PHP_EOL, $user['born']); printf(PHP_EOL); } printf('Retrieved and printed out all documents from the users collection.' . PHP_EOL);
C#
CollectionReference usersRef = db.Collection("users"); QuerySnapshot snapshot = await usersRef.GetSnapshotAsync(); foreach (DocumentSnapshot document in snapshot.Documents) { Console.WriteLine("User: {0}", document.Id); Dictionary<string, object> documentDictionary = document.ToDictionary(); Console.WriteLine("First: {0}", documentDictionary["First"]); if (documentDictionary.ContainsKey("Middle")) { Console.WriteLine("Middle: {0}", documentDictionary["Middle"]); } Console.WriteLine("Last: {0}", documentDictionary["Last"]); Console.WriteLine("Born: {0}", documentDictionary["Born"]); Console.WriteLine(); }
Ruby
users_ref = firestore.col collection_path users_ref.get do |user| puts "#{user.document_id} data: #{user.data}." end
다음 단계
다음 주제를 자세히 알아보세요.
- 데이터 모델 - 계층적 데이터와 하위 컬렉션을 비롯한 Firestore에서 데이터가 구조화되는 방식을 자세히 알아보세요.
- 데이터 추가 - Firestore에서 데이터를 만들고 업데이트하는 방법을 자세히 알아보세요.
- 데이터 가져오기 - 데이터를 검색하는 방법을 자세히 알아보세요.
- 단순 쿼리 및 복합 쿼리 실행 - 단순 쿼리 및 복합 쿼리 실행 방법을 알아보세요.
- 쿼리 순서 지정 및 제한 - 쿼리에서 반환된 데이터의 순서를 지정하고 제한하는 방법을 알아보세요.