Firestore: The New Database

Get ready to Fire up your Firestore, beware of what you do…

Many of you may wonder, why not Firebase? What’s up with this new feature of firebase?

Well, Firebase offers two cloud-based, client-accessible database solutions that support real-time data syncing:

  • Cloud Firestore is Firebase’s newest database for mobile app development. It builds on the successes of the Realtime Database with a new, more intuitive data model.
  • Realtime Database is Firebase’s original database. It’s an efficient, low-latency solution for mobile apps that require synced states across clients in real-time.

So, the next question is, which one should I go for? Cloud Firestore or Firebase’s original database?

Since most of us know what Firebase is, let’s dive deep into “What is Firestore ?

Cloud Firestore is a database for mobile, web, and server development from Firebase and Google Cloud. Like Firebase Realtime Database, it keeps your data in-sync across client apps through real-time listeners and offers offline support for mobile and web so you can build responsive apps that work regardless of network latency or Internet connectivity. Cloud Firestore also offers seamless integration with other Firebase and Google Cloud products, including Cloud Functions.

So let’s get started.

First, you have to create a Firebase account. Then,
1) Create a Firebase project :
In the Firebase console, click Add project, then follow the on-screen instructions to create a Firebase project or add Firebase
services to an existing GCP (Google Cloud Platform) project.

2) Create Database:
Navigate to the Cloud Firestore section of the Firebase console. You’ll be prompted to select an existing Firebase project. Follow the database creation workflow.

3) Select a starting mode for your Cloud Firestore Security Rules:
Test Mode: Good for getting started with the mobile and web client libraries but allows anyone to read and overwrite your data. After testing, make sure to review the Secure your data section. To get started with the web, iOS, or Android SDK, select test mode.
Locked Mode: Denies all reads and writes from mobile and web clients. Your authenticated application servers (C#, Go, Java, Node.js, PHP, Python, or Ruby) can still access your database. To get started with the C#, Go, Java, Node.js, PHP, Python, or Ruby server client library, select locked mode.

4) After the Selection of mode, select a location for your database. Once the location is set, you cannot change it. Click done.

That’s it you are set with your first Firestore project.

Further on in this blog, we’ll be focusing on the Java implementation of Firestore for Android. Now, let's begin with the next steps.

1) Set up Development Environment:
Using the Firebase Android BoM, declare the dependency for the Cloud Firestore Android library in the app/build.gradle .

dependencies {
// Import the BoM for the Firebase platform
implementation platform('com.google.firebase:firebase-bom:26.8.0')

// Declare the dependency for the Cloud Firestore library
// When using the BoM, you don't specify versions in Firebase library dependencies
implementation 'com.google.firebase:firebase-firestore'
}

2) Initialize an instance of Cloud Firestore:

// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();

3) Add Data:
Cloud Firestore stores data in Documents, which are stored in Collections. It creates collections and documents implicitly the first time you add data to the document. You do not need to explicitly create collections or documents.
Create a new collection and a document using the following example code.

// Create a new user with a first and last name
Map<String, Object> user = new HashMap<>();
user.put("first", "Ada");
user.put("last", "Lovelace");
user.put("born", 1815);

// Add a new document with a generated ID
db.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});

Now add another document to the Users collection. Notice that this document includes a key-value pair (middle name) that does not appear in the first document. Documents in a collection can contain different sets of information.

// Create a new user with a first, middle, and last name
Map<String, Object> user = new HashMap<>();
user.put("first", "Alan");
user.put("middle", "Mathison");
user.put("last", "Turing");
user.put("born", 1912);

// Add a new document with a generated ID
db.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});

4) Read Data:
To quickly verify that you’ve added data to Cloud Firestore, use the data viewer in the Firebase Console.

db.collection("users")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot()
{
@Override
public void onComplete(@NonNull Task<QuerySnapshot>task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});

5) Secure Data:
If you’re using the Web, Android SDK, use Firebase Authentication and Cloud Firestore Security Rules to secure your data in Cloud Firestore.

// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}

That is for the setup and some basic functioning of Cloud Firestore. If you would like to try it out for different applications using different languages Click Here.

Let’s get back to the question Cloud Firestore or Realtime database?

Let’s quickly go through it

Conclusion:

If one is choosing a real-time database, the data is stored in a single large file, regional, limited functionalities of sorting, server connection supported and the cost is higher. if one is going for Firestore, the data is stored as a collection of documents, multi-regional, server connection not supported and the cost is cheaper than the real-time database has to offer.

Hope you all are ready to choose your Database Solution. All the best!!

Do go through the official site of Firestore, most of the topics covered in this blog are available on it and some additional content too.

--

--