Java – Firestore’s generated key vs. a custom key in the collection?

Firestore’s generated key vs. a custom key in the collection?… here is a solution to the problem.

Firestore’s generated key vs. a custom key in the collection?

I

use a Cloud Firestore database in my Android application, and I have different documents in the collection, such as: the user’s uid, the restaurant’s button, and the number of my recipe.

My Database:

users
  uid1
  uid2
  ...
resturants
  pushedId1
  pushedId2
  ...
recipes
  0001
  0002
  ...

For users I understand using uids, but it’s better to use Firestore push IDs for my restaurant? Is this a convention or why use it?

I also tried generating unique keys using UUID Class but for me it’s easier to just use numbers in my recipe. Is this a bad approach?

Any help would be greatly appreciated, thank you!

Solution

By using predictable, such as sequential, IDs for documents, you can increase the chance of encountering hotspots in your back-end infrastructure. This reduces the scalability of write operations.

Cloud Firestore has a built-in unique ID generator when you call CollectionReference.add(...) or CollectionReference.document() (no parameters). The IDs it generates are random and highly unpredictable, which prevents attacks on certain hotspots in the backend infrastructure.

Using UIDs

for users’ documents is a good alternative to Firestore’s built-in generator, because UIDs already have high entropy: you can’t predict the UID of the next user based on what you know about the current user. In this case, using a UID (or the entity’s natural key) is a better approach, because you can find the document directly without having to query it.

Check out this discussion on the firebase-talk The mailing list is explained in more detail by some engineers who work on Firestore.

Related Problems and Solutions