英文:
Write entity only if the key isn't present in Google Datastore
问题
我试图解决的问题是:我有一个每天生成实体的服务。其中一些实体是新的,而另一些在之前的运行中已经找到过。
我需要做到以下几点:
- 保持数据库最新,即包含所有已经找到的实体。
- 能够判断何时找到新的实体。每个实体都包含一个时间戳,所以如果我能确保实体不被覆盖,这应该不太困难(我只需查询数据库中今天找到的实体,这些应该是新的实体),所以这就是我要做的。
生成的数据如下所示:
[
{"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:
- keep the database up-to-date, i.e. containing all the entities that have ever been found
- 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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论