代码之家  ›  专栏  ›  技术社区  ›  markvgti

文档路径是否与Firestore自动生成的随机ID有关?

  •  0
  • markvgti  · 技术社区  · 7 年前

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

    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
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Frank van Puffelen    7 年前

    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();
    }
    

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

    推荐文章