If I want to know the (random) ID of a document before saving it to Firestore (without writing custom code), I can do the following:
String id = db.collection("collection-name").document().getId();
Does it make a difference if I give "collection-name"
in the code above but use that id
to save the document to collection "some-other-collection"
?
In other words, does the collection name (or more generally, path of the document) have any bearing on the random ID generated by Firestore?
Are Firestore IDs generated similarly to what is described in The 2^120 Ways to Ensure Unique Identifiers?
How good would the following code be for auto-generating known IDs for Firestore documents:
private static SecureRandom RANDOMIZER = new SecureRandom();
.
.
.
byte[] randomId = new byte[120];
RANDOMIZER.nextBytes(randomId);
// Base64-encode randomId
The Document IDs generated by Cloud Firestore are generated client-side, completely random, and not dependent on the collection that you generate them in.
You can see this for yourself if you dig a bit into the (open-source) SDKs. For example, in the Android SDK, here's the source for
CollectionReference.add()
:So that leaves the ID generation to the
document
method:Which delegates to
Util.autoId()
:As said: pure client-side randomness with enough entropy to ensure global uniqueness.