Deleting all documents in CouchDB

好久不见. 提交于 2021-02-10 07:14:51

问题


I have a database and I want to truncate all records, I know it is possible to just add a _deleted key to every document or call db.delete() on CouchDB-python library. I am using the delete of couchdb-python but it does not seem to work when I fetch all the documents and then call .delete on each document excluding design documents.

Here is my code.

docs = get_db().view('_all_docs', include_docs=True)
for i in docs:
    if not(i['id'].startswith('_')):
        get_db().delete(i)

This is the error. Because the result from _all_docs is returning a id instead _id.

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\couchdb\client.py", line 625, in delete
if doc['_id'] is None:
KeyError: '_id'

My question is how do I fetch all documents that returns _id instead of just the id? Or is there any way around this?


回答1:


In couchdb-python a view query returns a list of couchdb.client.Row objects, not a list of the docs. You need to pass an attribute doc to that delete, i.e. get_db().delete(i['doc']).

From performance perspective, however, it's better to use bulk api. With couchdb-python it should look something like this:

rows = get_db().view('_all_docs', include_docs=True)
docs = []
for row in rows:
    if row['id'].startswith('_'):
        continue
    doc = row['doc']
    doc['_deleted'] = True
    docs.append(doc)
get_db().update(docs)



回答2:


Deleting documents from CouchDB you can create in two step:

  • create a view (with filtering the documents you want to delete)
  • use the view to delete all documents using the view

I have written a tool for this.



来源:https://stackoverflow.com/questions/46884089/deleting-all-documents-in-couchdb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!