Does the path of a Document have any bearing on the random ID auto-generated by Firestore?
Asked Answered
L

1

0

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
Limassol answered 2/1, 2019 at 13:37 Comment(0)
H
5

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():

final DocumentReference ref = document();
return ref.set(data)

So that leaves the ID generation to the document method:

public DocumentReference document() {
  return document(Util.autoId());
}

Which delegates to Util.autoId():

private static final int AUTO_ID_LENGTH = 20;

private static final String AUTO_ID_ALPHABET =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

private static final Random rand = new Random();

public static String autoId() {
  StringBuilder builder = new StringBuilder();
  int maxRandom = AUTO_ID_ALPHABET.length();
  for (int i = 0; i < AUTO_ID_LENGTH; i++) {
    builder.append(AUTO_ID_ALPHABET.charAt(rand.nextInt(maxRandom)));
  }
  return builder.toString();
}

As said: pure client-side randomness with enough entropy to ensure global uniqueness.

Huckster answered 2/1, 2019 at 15:0 Comment(1)
This implementation is statistically certain to ensure no collision of IDs in a project? Where does the entropy come from? AFA I can see, it's just java.util.Random's implementation that is providing the entropy.Limassol

© 2022 - 2024 — McMap. All rights reserved.