如果在Google Datastore中不存在该键,则只写入实体。

huangapple go评论72阅读模式
英文:

Write entity only if the key isn't present in Google Datastore

问题

我试图解决的问题是:我有一个每天生成实体的服务。其中一些实体是新的,而另一些在之前的运行中已经找到过。

我需要做到以下几点:

  1. 保持数据库最新,即包含所有已经找到的实体。
  2. 能够判断何时找到新的实体。每个实体都包含一个时间戳,所以如果我能确保实体不被覆盖,这应该不太困难(我只需查询数据库中今天找到的实体,这些应该是新的实体),所以这就是我要做的。

生成的数据如下所示:

[
{"key": "a",
"foo": "bar",
"timestamp": "EXMAPLE_TIMESTAMP" },
{"key": "b",
"foo": "baz",
"timestamp": "EXMAPLE_TIMESTAMP" }
] 

注意:实体具有唯一的数据存储键。

编辑:我尝试使用Put(),但如果它们的键已经存在,它只会覆盖实体,这导致时间戳被更新,即使实际内容相同。

英文:

The problem I'm trying to solve is: I have a service that generates entities every day. Some of those entities will be new, and some will have already been found in a previous run.

I need to:

  1. keep the database up-to-date, i.e. containing all the entities that have ever been found
  2. be able to tell when a new entity is found. Each entity contains a timestamp, so if I can make sure entities aren't over-written, this shouldn't be too hard (I'll just query the database for the entities that were found today and these should be the new ones), so this is what I'm trying to do.

The generated data looks like this

[
{"key": "a",
"foo": "bar",
"timestamp": "EXMAPLE_TIMESTAMP" },
{"key": "b",
"foo": "baz",
"timestamp": "EXMAPLE_TIMESTAMP" }
] 

Note: The entities have unique datastore keys

Edit: I tried using Put(), but it just overwrites the entities if their keys already exist, which leads to the timestamps being updated even if the actual content is the same.

答案1

得分: 3

使用插入变异来保存实体,仅当键不存在时才保存。

_, err = client.Mutate(ctx, datastore.NewInsert(key, value))
if merr, ok := err.(datastore.MultiError); ok && merr[0] == codes.AlreadyExists {
    err = nil
}
if err != nil {
    // 处理错误
}
英文:

Use an insert mutation to save the entity only if the key does not exist.

_, err = client.Mutate(ctx, datastore.NewInsert(key, value))
if merr, ok := err.(datastore.MultiError); ok && merr[0] == codes.AlreadyExists {
	err = nil
}
if err != nil {
	// handle error
}

huangapple
  • 本文由 发表于 2021年7月1日 20:31:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/68210242.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定