文档的路径与Firestore自动生成的随机ID有关系吗? [英] Does the path of a Document have any bearing on the random ID auto-generated by Firestore?
问题描述
如果要在将文档保存到Firestore之前(不编写自定义代码)之前知道文档的(随机)ID,可以执行以下操作:
String id = db.collection("collection-name").document().getId();
如果我在上面的代码中给出"collection-name"
,但使用该id
将文档保存到集合"some-other-collection"
,会有所不同吗?
换句话说,集合名称(或更笼统地说,是文档的路径)与Firestore生成的随机ID有什么关系吗?
是否生成的Firestore ID与解决方案
Cloud Firestore生成的文档ID是在客户端生成的,完全是随机的,并且不依赖于您在其中生成它们的集合.
如果您深入研究(开源)SDK,则可以自己看到.例如,在Android SDK中,这是 document
方法:
public DocumentReference document() {
return document(Util.autoId());
}
哪个代表 如前所述:具有足够熵的纯客户端随机性,以确保全局唯一性. 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: Does it make a difference if I give 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:
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 So that leaves the ID generation to the Which delegates to As said: pure client-side randomness with enough entropy to ensure global uniqueness. 这篇关于文档的路径与Firestore自动生成的随机ID有关系吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!String id = db.collection("collection-name").document().getId();
"collection-name"
in the code above but use that id
to save the document to collection "some-other-collection"
?private static SecureRandom RANDOMIZER = new SecureRandom();
.
.
.
byte[] randomId = new byte[120];
RANDOMIZER.nextBytes(randomId);
// Base64-encode randomId
CollectionReference.add()
:final DocumentReference ref = document();
return ref.set(data)
document
method:public DocumentReference document() {
return document(Util.autoId());
}
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();
}