Skip to content

Commit 4a15b36

Browse files
authored
Adding firestore samples (#877)
1 parent fe135c7 commit 4a15b36

File tree

13 files changed

+2048
-0
lines changed

13 files changed

+2048
-0
lines changed

firestore/README.md

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Getting started with Google Cloud Firestore
2+
[Google Cloud Firestore](https://cloud.google.com/firestore/docs/) is a hosted NoSQL database built
3+
for automatic scaling, high performance, and ease of application development.
4+
5+
These code samples demonstrate how to access the Google Cloud Firestore API
6+
using the Beta version of the Firestore Client Libraries.
7+
8+
Note: You cannot use both Cloud Firestore and Cloud Datastore in the
9+
same project, which might affect apps using App Engine. Try using Cloud Firestore with a different
10+
project.
11+
12+
## Setup
13+
- Install [Maven](http://maven.apache.org/).
14+
- Open the [Firebase Console](https://console.firebase.com) and click **Add project**.
15+
- Select the option to **Enable Cloud Firestore Beta** for this project.
16+
- Click **Create Project**.
17+
When you create a Cloud Firestore project, it also enables the API in the
18+
[Cloud API Manager](https://console.cloud.google.com/projectselector/apis/api/firestore.googleapis.com/overview).
19+
- [Create a service account](https://cloud.google.com/docs/authentication/)
20+
and set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to point to the
21+
credentials JSON file.
22+
23+
## Build
24+
Build your project:
25+
26+
mvn clean package
27+
28+
29+
## Quickstart
30+
[Quickstart.java](src/main/java/com/example/java/com/example/firestore/Quicstart.java)
31+
demonstrates adding and querying documents in a collection in Firestore.
32+
You can run the quickstart with:
33+
34+
mvn exec:java -Dexec.mainClass=com.example.firestore.Quickstart -Dexec.args="your-firestore-project-id"
35+
36+
Note: the default project-id will be used if no argument is provided.
37+
38+
## Snippets
39+
These [code samples](src/main/java/com/example/firestore/snippets) support
40+
the Firestore [documentation](https://cloud.google.com/firestore/docs).
41+
42+
## Tests
43+
Run all tests:
44+
```
45+
mvn clean verify
46+
```
47+

firestore/pom.xml

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<!--
2+
Copyright 2017 Google Inc.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
You may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
-->
16+
17+
<project>
18+
<modelVersion>4.0.0</modelVersion>
19+
<groupId>com.example.firestore</groupId>
20+
<artifactId>firestore-samples</artifactId>
21+
<version>1.0.0</version>
22+
<packaging>jar</packaging>
23+
<name>Google Cloud Firestore Samples</name>
24+
<description>
25+
Quick start and code snippets supporting Firestore documentation
26+
</description>
27+
28+
<parent>
29+
<artifactId>doc-samples</artifactId>
30+
<groupId>com.google.cloud</groupId>
31+
<version>1.0.0</version>
32+
<relativePath>..</relativePath>
33+
</parent>
34+
35+
<properties>
36+
<maven.compiler.target>1.7</maven.compiler.target>
37+
<maven.compiler.source>1.7</maven.compiler.source>
38+
</properties>
39+
40+
<dependencies>
41+
<!-- Firestore -->
42+
<!-- [START fs-maven] -->
43+
<dependency>
44+
<groupId>com.google.cloud</groupId>
45+
<artifactId>google-cloud-firestore</artifactId>
46+
<version>0.25.0-beta</version>
47+
</dependency>
48+
<!-- [END fs-maven] -->
49+
50+
<!-- Test dependencies -->
51+
<dependency>
52+
<groupId>junit</groupId>
53+
<artifactId>junit</artifactId>
54+
<version>4.12</version>
55+
<scope>test</scope>
56+
</dependency>
57+
</dependencies>
58+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
/*
2+
* Copyright 2017 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
15+
package com.example.firestore;
16+
17+
import com.google.api.core.ApiFuture;
18+
import com.google.cloud.firestore.DocumentReference;
19+
import com.google.cloud.firestore.DocumentSnapshot;
20+
// [START fs_include_dependencies]
21+
import com.google.cloud.firestore.Firestore;
22+
import com.google.cloud.firestore.FirestoreOptions;
23+
// [END fs_include_dependencies]
24+
import com.google.cloud.firestore.QuerySnapshot;
25+
import com.google.cloud.firestore.WriteResult;
26+
import com.google.common.collect.ImmutableMap;
27+
28+
import java.util.HashMap;
29+
import java.util.List;
30+
import java.util.Map;
31+
32+
/**
33+
* A simple Quick start application demonstrating how to connect to Firestore
34+
* and add and query documents.
35+
*/
36+
public class Quickstart {
37+
38+
private Firestore db;
39+
40+
/**
41+
* Initialize Firestore using default project ID.
42+
*/
43+
public Quickstart() {
44+
// [START fs_initialize]
45+
Firestore db = FirestoreOptions.getDefaultInstance().getService();
46+
// [END fs_initialize]
47+
this.db = db;
48+
}
49+
50+
public Quickstart(String projectId) {
51+
// [START fs_initialize_project_id]
52+
FirestoreOptions firestoreOptions =
53+
FirestoreOptions.getDefaultInstance().toBuilder()
54+
.setProjectId(projectId)
55+
.build();
56+
Firestore db = firestoreOptions.getService();
57+
// [END fs_initialize_project_id]
58+
this.db = db;
59+
}
60+
61+
Firestore getDb() {
62+
return db;
63+
}
64+
65+
/**
66+
* Add named test documents with fields first, last, middle (optional), born.
67+
*
68+
* @param docName document name
69+
*/
70+
void addDocument(String docName) throws Exception {
71+
switch (docName) {
72+
case "alovelace": {
73+
// [START fs_add_data_1]
74+
DocumentReference docRef = db.collection("users").document("alovelace");
75+
// Add document data with id "alovelace" using a hashmap
76+
Map<String, Object> data = new HashMap<>();
77+
data.put("first", "Ada");
78+
data.put("last", "Lovelace");
79+
data.put("born", 1815);
80+
//asynchronously write data
81+
ApiFuture<WriteResult> result = docRef.set(data);
82+
// ...
83+
// result.get() blocks on response
84+
System.out.println("Update time : " + result.get().getUpdateTime());
85+
// [END fs_add_data_1]
86+
break;
87+
}
88+
case "aturing": {
89+
// [START fs_add_data_2]
90+
DocumentReference docRef = db.collection("users").document("aturing");
91+
// Add document data with an additional field ("middle")
92+
Map<String, Object> data = new HashMap<>();
93+
data.put("first", "Alan");
94+
data.put("middle", "Mathison");
95+
data.put("last", "Turing");
96+
data.put("born", 1912);
97+
98+
ApiFuture<WriteResult> result = docRef.set(data);
99+
System.out.println("Update time : " + result.get().getUpdateTime());
100+
// [END fs_add_data_2]
101+
break;
102+
}
103+
case "cbabbage": {
104+
DocumentReference docRef = db.collection("users").document("cbabbage");
105+
Map<String, Object> data =
106+
new ImmutableMap.Builder<String, Object>()
107+
.put("first", "Charles")
108+
.put("last", "Babbage")
109+
.put("born", 1791)
110+
.build();
111+
ApiFuture<WriteResult> result = docRef.set(data);
112+
System.out.println("Update time : " + result.get().getUpdateTime());
113+
break;
114+
}
115+
default:
116+
}
117+
}
118+
119+
void runAQuery() throws Exception {
120+
// [START fs_add_query]
121+
// asynchronously query for all users born before 1900
122+
ApiFuture<QuerySnapshot> query =
123+
db.collection("users").whereLessThan("born", 1900).get();
124+
// ...
125+
// query.get() blocks on response
126+
QuerySnapshot querySnapshot = query.get();
127+
List<DocumentSnapshot> documents = querySnapshot.getDocuments();
128+
for (DocumentSnapshot document : documents) {
129+
System.out.println("User: " + document.getId());
130+
System.out.println("First: " + document.getString("first"));
131+
if (document.contains("middle")) {
132+
System.out.println("Middle: " + document.getString("middle"));
133+
}
134+
System.out.println("Last: " + document.getString("last"));
135+
System.out.println("Born: " + document.getLong("born"));
136+
}
137+
// [END fs_add_query]
138+
}
139+
140+
void retrieveAllDocuments() throws Exception {
141+
// [START fs_get_all]
142+
// asynchronously retrieve all users
143+
ApiFuture<QuerySnapshot> query = db.collection("users").get();
144+
// ...
145+
// query.get() blocks on response
146+
QuerySnapshot querySnapshot = query.get();
147+
List<DocumentSnapshot> documents = querySnapshot.getDocuments();
148+
for (DocumentSnapshot document : documents) {
149+
System.out.println("User: " + document.getId());
150+
System.out.println("First: " + document.getString("first"));
151+
if (document.contains("middle")) {
152+
System.out.println("Middle: " + document.getString("middle"));
153+
}
154+
System.out.println("Last: " + document.getString("last"));
155+
System.out.println("Born: " + document.getLong("born"));
156+
}
157+
// [END fs_get_all]
158+
}
159+
160+
void run() throws Exception {
161+
String[] docNames = {"alovelace", "aturing", "cbabbage"};
162+
163+
// Adding document 1
164+
System.out.println("########## Adding document 1 ##########");
165+
addDocument(docNames[0]);
166+
167+
// Adding document 2
168+
System.out.println("########## Adding document 2 ##########");
169+
addDocument(docNames[1]);
170+
171+
// Adding document 3
172+
System.out.println("########## Adding document 3 ##########");
173+
addDocument(docNames[2]);
174+
175+
// retrieve all users born before 1900
176+
System.out.println("########## users born before 1900 ##########");
177+
runAQuery();
178+
179+
// retrieve all users
180+
System.out.println("########## All users ##########");
181+
retrieveAllDocuments();
182+
System.out.println("###################################");
183+
}
184+
185+
/**
186+
* A quick start application to get started with Firestore.
187+
*
188+
* @param args firestore-project-id (optional)
189+
*/
190+
public static void main(String[] args) throws Exception {
191+
// default project is will be used if project-id argument is not available
192+
String projectId = (args.length == 0) ? null : args[0];
193+
Quickstart quickStart = (projectId != null) ? new Quickstart(projectId) : new Quickstart();
194+
quickStart.run();
195+
}
196+
}

0 commit comments

Comments
 (0)