Google.Cloud.Datastore.V1中的Key是什么

What is Key in Google.Cloud.Datastore.V1

我是这个 nuget 包的新手,对 Key class.

感到困惑

这是我基于 Google.Cloud.Datastore.V1 文档的代码:

public long InsertMessage<T>(T iEntity) where T : IEntity<T>
{
    var keyFactory = _db.CreateKeyFactory(Kind);
    var entity = iEntity.ToEntity();
    entity.Key = keyFactory.CreateIncompleteKey();

    using (var transaction = _db.BeginTransaction())
    {
        transaction.Insert(entity);
        var commitResponse = transaction.Commit();
        var insertedKey = commitResponse.MutationResults[0].Key;
        Logger.Info($"Inserted key: {insertedKey}");
        return insertedKey.Path[0].Id;
    }
}

我所做的就是创建一个实体并创建一个不完整的密钥,发送到服务器,然后从服务器取回填充的密钥。

我认为 key 用作实体的唯一标识

如有误解请指正

我可以通过如下查询获取实体:

var query = new Query(Kind)
{
    Filter = Filter.Equal("key", key),
    Order = { { "created", PropertyOrder.Types.Direction.Ascending } }
};
foreach (var entity in _db.RunQueryLazily(query))
{
    list.Add(entity);
}

但是我不知道如何使用我插入时得到的密钥通过Filter.Equal("key", key)获得唯一实体。

示例显示 Key 的结构 是:

{
    "partitionId":
    {
        "projectId": "projectId",
        "namespaceId": "namespaceId"
    },
    "path": [
    {
        "kind": "kind",
        "id": "id"
    }]
}

这里我总结一下我的问题:

  1. Keyclass有什么用?
  2. Key 的路径是什么,为什么是数组?
  3. id 是实体的唯一键吗?
  4. 如何通过KeyIdQuery

感谢阅读,请不要介意我的英语不好。

键是文档的唯一标识符。 documentation 说得最好:

Each entity in Cloud Datastore has a key that uniquely identifies it. The key consists of the following components:

  • The namespace of the entity, which allows for multitenancy
  • The kind of the entity, which categorizes it for the purpose of Cloud Datastore queries
  • An identifier for the individual entity, which can be either
    • a key name string
    • an integer numeric ID
  • An optional ancestor path locating the entity within the Cloud Datastore hierarchy An optional ancestor path locating the entity within the Cloud Datastore hierarchy

“祖先路径”部分是 Path 属性 中存在数组的原因 - 完全限定键是一个名称空间,后跟一系列 path elements,每个它由种类和“整数 ID”或“字符串名称”部分组成。

例如,您可能有一个图书馆应用程序。那有架子和书。忽略命名空间部分,特定书籍的 ID 可能包含以下路径元素:

  • 种类=货架; Id=1(数字ID)
  • 种类=书籍; Name=xyz(字符串名称)

另一种思考方式就像集合和文档名称的交替序列,例如“/shelves/1/books/xyz”。这就是 Firestore 表示其文档 ID 的方式。

任何一个路径元素不必是唯一的,但完整路径是唯一的。没有通过“键和 ID”查询的真正概念 - 您可以查找完整的键(例如 DatastoreDb.Lookup)或包含父键作为祖先路径查询。