【问题标题】:Python - Cloudant Get ChangesPython - Cloudant 获取更改
【发布时间】:2017-06-21 13:06:06
【问题描述】:

我正在使用 Cloudant 库来从 Cloudant 数据库中收集文档。每次运行 python 脚本时,我都会获取所有文档,但我只想检索从上次执行脚本时添加的文档,即 get_changes 函数。

我已经找到了答案,但似乎并不容易找到。

感谢您的帮助,

菲利波。

【问题讨论】:

    标签: python cloudant


    【解决方案1】:

    使用changes() 方法。跟踪最后一个序列 id,然后从那里重新开始以仅检索看不见的更改。

    # Iterate over a "normal" _changes feed
    changes = db.changes()
    for change in changes:
        print(change)
    
    # ...time passes
    new_changes = db.changes(since=changes.last_seq)
    for new_change in new_changes:
        print(new_change)
    

    如果你也想要文档正文,可以传递include_docs=True

    https://github.com/cloudant/python-cloudant/blob/master/src/cloudant/database.py#L458

    如果您只想捕获新增内容(而不是所有更改),您可以在 db 设计文档中按照以下方式创建过滤器函数:

    function(doc, req) {
        // Skip deleted docs
        if (doc._deleted) {
            return false;
        }
        // Skip design docs
        if (doc._id.startsWith('_design')) {
            return false;
        }
    
        // Skip updates
        if (!doc._rev.startsWith('1-')) {
            return false;
        }
    
        return true;
    }
    

    并将其应用于更改提要:

    new_changes = db.changes(since=changes.last_seq, filter='myddoc/myfilter'):
        # do stuff here
    

    但在 Python 代码中简单地获取所有更改和过滤器可能同样容易。

    过滤函数:https://console.bluemix.net/docs/services/Cloudant/guides/replication_guide.html#filtered-replication

    【讨论】:

    • 是的,发帖后我尝试了这个方法,效果很好。我必须编辑这个问题,因为我想做的是只检索在最后一个序列 ID 之后上传的附加文档。您发布的脚本还返回设计文档和文档修改,但我对这些结果不感兴趣。顺便谢谢你的回答
    • 非常感谢xpqz,你们的cmets帮了很多忙
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    相关资源
    最近更新 更多