【问题标题】:Does the path of a Document have any bearing on the random ID auto-generated by Firestore?文档的路径对 Firestore 自动生成的随机 ID 有影响吗?
【发布时间】:2019-01-02 13:37:34
【问题描述】:

如果我想知道文档保存到 Firestore 之前的(随机)ID(无需编写自定义代码),我可以执行以下操作:

String id = db.collection("collection-name").document().getId();

如果我在上面的代码中提供"collection-name",但使用id 将文档保存到集合"some-other-collection",这会有所不同吗?

换句话说,集合名称(或更一般地说,文档的路径)是否与 Firestore 生成的随机 ID 有任何关系?

生成的 Firestore ID 是否与 The 2^120 Ways to Ensure Unique Identifiers 中描述的类似?

以下代码对于为 Firestore 文档自动生成已知 ID 有多好:

private static SecureRandom RANDOMIZER = new SecureRandom();
.
.
.
byte[] randomId = new byte[120];
RANDOMIZER.nextBytes(randomId);
// Base64-encode randomId

【问题讨论】:

    标签: java google-app-engine google-cloud-firestore id-generation


    【解决方案1】:

    Cloud Firestore 生成的文档 ID 是在客户端生成的,完全随机,不依赖于您在其中生成它们的集合。

    如果您深入了解(开源)SDK,您可以自己看到这一点。例如,在 Android SDK 中,这里是 source for CollectionReference.add()

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

    因此,ID 生成留给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();
    }
    

    如前所述:具有足够熵的纯客户端随机性以确保全局唯一性。

    【讨论】:

    • 这个实现在统计上可以确保项目中没有 ID 冲突?熵从何而来?我可以看到 AFA,它只是 java.util.Random 的实现提供了熵。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2018-08-27
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多