2

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
ellaRT
  • 1,346
  • 2
  • 16
  • 39

2 Answers2

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)
eiri
  • 321
  • 1
  • 3
0

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.

Istvan
  • 7,500
  • 9
  • 59
  • 109