NDB 写入是如何计算的?

How NDB writes are counted?

如果我第二次将相同的数据添加到数据存储中,是否需要额外的写入操作?

比如我有下面的class:

class Song(ndb.Model):
    artist = ndb.StringProperty(required=True, indexed=True)
    title = ndb.StringProperty(required=True, indexed=False)

和以下代码以在其中添加新歌曲或更新现有值:

def add_song(artist, title):
    song_id = artist+ ' - ' + title
    record = Song.get_by_id(song_id)
    if not record:
        record = Song(id=song_id)
    record.artist = artist
    record.title = title
    record.put()

它会有效地工作吗? IE。不会写艺术家和标题值,如果它们已经存在并且相同?或者,我应该像下面这样优化代码:

def add_song(artist, title):
    song_id = artist+ ' - ' + title
    record = Song.get_by_id(song_id)
    if not record:
        record = Song(id=song_id)
    if record.artist != artist: # new line!
        record.artist = artist
    if record.title != title: # new line!
        record.title = title
    if record.artist != artist or record.title != title: # new line!
        record.put()

这两个代码在调用时会产生相同数量的写操作吗:

add_song('Artist Name', 'Song Title')
add_song('Artist Name', 'Song Title') # same artist, same title - second addition

add_song('Artist Name', 'Song Title')
add_song('Artist Name', 'New Song Title') # same artist, new title - second addition

?

是的,重新放置完全相同的对象会导致写入数据存储。

实际上,不止一次写入,具体取决于为您提供服务的索引。

如果您查看 ndb doc and this article

,您可能会获得更多信息

是的,你应该优化——你只是做错了。

具体来说,您正在检查 if record.artist != artist &c) 您的代码段

之后
if record.artist != artist: # new line!
    record.artist = artist

这当然确保了 != 条件不会持续。因此,您永远不会达到可以调用 .put().

的条件

尝试,而不是像这样:

def add_song(artist, title):
    song_id = artist+ ' - ' + title
    record = Song.get_by_id(song_id)
    if record:
        if record.artist != artist or record.title != title: # new line!
            record.artist = artist
            record.title = title
            is_new = True
        else:
            is_new = False
    else:
        record = Song(id=song_id, artist=artist, title=title)
        is_new = True
    if is_new:
         record.put()