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

我只是一个虾纸丫 提交于 2019-12-18 09:44:57

问题


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:


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.



来源:https://stackoverflow.com/questions/54007373/does-the-path-of-a-document-have-any-bearing-on-the-random-id-auto-generated-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!