Does the path of a Document have any bearing on th

2019-03-06 15:49发布

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

1条回答
We Are One
2楼-- · 2019-03-06 16:27

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.

查看更多
登录 后发表回答