检索记录中已更新的字段

Retrieve the fields that have been updated in a record

我可以检索视图中已更新的字段吗?理想情况下,我将能够检索已更新的字段总数(添加到列表字段或字段已更改的项目)和各个字段的 names/count。

给定一个数据库记录,例如:

{
    "_id": "e3cfb5e19e5c05fb6822c5ee228c4f2e",
    "_rev": "52-c78a26776b0e0736dd45e44a47634031",
    "last_updated": "23/04/2015",
    "title", "testdoc",
    "samples": [
        {
            "confidence": "high",
            "handle": "joetest"
        }
    ],
    "locations": [
        {"Toronto", "Ontario"},
        {"Vancouver", "British Columbia"}
    ]
}

如果 "samples" 中有 2 个新项目,"locations" 中有 1 个新项目,我会看到更新后的计数为 3。

假设您在更新前检索数据,您可以将其与更新后的数据进行比较。以下简单函数查看原始数据中带有数组的任何键和 returns 新数据的长度。

def list_delta(before, after):
    out = {}

    for key in before:
        if isinstance(before[key], list):
            out[key] = len(after[key]) - len(before[key])

    return out

before = {'name': 'davidism', 'numbers': [0, 1, 2, 3, 4]}
after = do_update(before)
# after = {'name': 'davidism', 'numbers': [0, 1, 2, 3, 4, 5]}
list_delta(before, after)
# returns {'numbers': 1}

如果添加或删除键,或者实际值是否更改,或者对嵌套结构进行更深入的递归比较,您可以变得更聪明,但这超出了本答案的范围。