2
votes

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?

2
Why do you want this? Wouldn't it be easier just to delete and re-create the database?Flimzy
If I drop the database, then I'd have to recreate all my views again? Is that right? Sorry, I am fairly new with Couch. @FlimzyellaRT
Yes. But hopefully you have an easy way to do that.Flimzy
Do you need to use i['id'] with delete?Istvan
that is the problem, I need _id' for the delete but Couch is returning 'id' instead. @IstvanellaRT

2 Answers

1
votes

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)
0
votes

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.