user1973386
user1973386

Reputation: 1135

Is it possible to delete documents in Apache CouchDB's temporary view?

All documents in my database have a timestamp:

Example document:

{
    ...
    "timestamp": 1404587326,
    ...
}

With a map reduce I am able to filter all documents older than a certain date, for instance older than yesterday, but how can I delete those documents older than yesterday?

function(doc) {
    var yesterday = Date.now() - (60*60*24);
    if(doc.timestamp < yesterday) {
        delete(doc._id); // how??
    }
}

Upvotes: 2

Views: 828

Answers (2)

dch
dch

Reputation: 1542

You can use the view approach that @dashservice as given, and then issue an HTTP DELETE /db/docname, or use the _bulk_docs API endpoint if you have many of them.

A common couchdb design pattern is to store documents into separate databases that can subsequently be dropped / deleted when those documents are not required.

Upvotes: 3

Hans
Hans

Reputation: 2910

First of all, your map reduce code does not work!

Your map function is only called when a document is changing. So the Date.now() function will be the date at the time the map function was called the first time after a change to the document, not the actual time you access the index that is build by the function.

Also I was not aware that you can delete a document in a view.

This is how you could achieve it

Use the date as the ID in your map function, and return the Id of the documents. Then use your client app to call the view with the startkey parameter, which you can set to Date.now() - 24*60*60.

The view will then only return the documents that are more recent than the startkey, but not yet delete any documents.

Your map function will look something like:

function(doc){
  emit(doc.timestamp, doc);
}

Do you really need to delete documents?

If you really want documents that are older than 2 days to be deleted, you may not have the best database using couchdb. Couchbase - which is similar to couchdb in some ways and MongoDB both offer document expiry options as far as I know.

Alternatively you could access the documents with the above map function occasionally. But use the endkey, so that you retrieve all older documents. You'd then need to individually delete them.

Finally temporary views

I'm not sure why you want to use one of these, just store your view.

Upvotes: 3

Related Questions