关键与 ID/Name?

Key vs ID/Name?

我不想为我的实体创建自动生成的密钥,所以我指定了我自己的密钥:

Entity employee = Entity.newBuilder().setKey(makeKey("Employee", "bobby"))
        .addProperty(makeProperty("fname", makeValue("fname").setIndexed(false)))
        .addProperty(makeProperty("lname", makeValue("lname").setIndexed(false)))    
        .build();

CommitRequest request = CommitRequest.newBuilder()
    .setMode(CommitRequest.Mode.NON_TRANSACTIONAL)
    .setMutation(Mutation.newBuilder().addInsert(employee))
    .build();
datastore.commit(request);

当我查看实体的外观时,它看起来像这样:

如果我指定了自己的密钥 (bobby),为什么会生成这个自动生成的密钥?似乎还创建了 bobby,但现在我有了 bobby 和这个自动生成的密钥。 key和id/name有什么区别?

您使用 makeKey("Employee", "bobby") 创建的是实体名称 Employee 和名称 bobby 的实体的键。您在数据存储区查看器中看到的 Key 正是它的代表。

一般来说一个键总是由

组成
  • 可选父键(带有实体类型和 name/id)
  • 实体类型
  • 实体name/id

也许这里有人可以告诉您如何将密钥解码为其组件,但请放心,您所做的一切都是正确的,并且行为符合预期。

这是您的密钥的 url 安全版本,适合在链接中使用。使用 KeyFactory.stringToKey 将其转换为实际密钥,您会看到它包含您的字符串名称。

您不能指定自己的密钥,密钥实际上包含数据存储操作所需的信息。 the documentation 中的这个注释给了你一个想法:

Note: The URL-safe string looks cryptic, but it is not encrypted! It can easily be decoded to recover the original entity's kind and identifier:

key = Key(urlsafe=url_string)
kind_string = key.kind()
ident = key.id()

If you use such URL-safe keys, don't use sensitive data such as email addresses as entity identifiers. (A possible solution would be to use the MD5 hash of the sensitive data as the identifier. This stops third parties, who can see the encrypted keys, from using them to harvest email addresses, though it doesn't stop them from independently generating their own hash of a known email address and using it to check whether that address is present in the Datastore.)

什么 you can specify 是密钥的 ID 部分,可以是数字还是字符串:

A key is a series of kind-ID pairs. You want to make sure each entity has a key that is unique within its application and namespace. An application can create an entity without specifying an ID; the Datastore automatically generates a numeric ID. If an application picks some IDs "by hand" and they're numeric and the application lets the Datastore generate some IDs automatically, the Datastore might choose some IDs that the application already used. To avoid, this, the application should "reserve" the range of numbers it will use to choose IDs (or use string IDs to avoid this issue entirely).