3

I need to create CouchDB design-documents from R, so that others can use my code without learning or switching to CouchDB.

This link was very useful for learning how to use CouchDB from R: http://digitheadslabnotebook.blogspot.com/2010/10/couchdb-and-r.html. Following it I can make and fill a database:

library(RJSONIO)
library(RCurl)
httpPUT("http://127.0.0.1:5984/fooddb")  # Creates the fooddb database
# Add two documents
fromJSON(getURL("http://127.0.0.1:5984/fooddb", customrequest='POST', httpheader=c('Content-Type'='application/json'), postfields=toJSON(list(day="Monday", dinner="Pasta"))))
fromJSON(getURL("http://127.0.0.1:5984/fooddb", customrequest='POST', httpheader=c('Content-Type'='application/json'), postfields=toJSON(list(day="Tuesday", dinner="Soup"))))

In the CouchDB web-gui Futon, I manually create this view (this is the step I want to do from R).

function(doc) {
  emit(doc.day, doc.dinner);
}

And back in R I can get the view results:

view.results <- fromJSON(httpGET("http://127.0.0.1:5984/fooddb/_design/fooddoc/_view/foodview"))
view.results.df <- do.call(rbind.data.frame, view.results$rows)
colnames(view.results.df) <- c("key", "day", "dinner")

To create the view from R, I save the view to file and try to put it into the CouchDB

writeLines(toJSON("function(doc) {
           emit(doc.day, doc.dinner);
           }"),
           "foodview.json")
fromJSON(getURL("http://127.0.0.1:5984/fooddb/_design/foodview", customrequest='PUT', httpheader=c('Content-Type'='application/json'), postfields="@foodview.json"))

But that results in ("bad_request" "invalid_json").

What can be wrong? I suspect the last line or the "writeLines" command, but haven't found a way to get them to work.

Update: Based on Kxepals good answer, I created a new writeLines that create a view that can be parsed with curl.

writeLines("{
   \"_id\": \"_design/foodview\",
   \"views\": {
     \"foodview\": {
       \"map\": \"function(doc) {emit(doc.day, doc.dinner);}\"
     }
   }
  }"
, "foodview.json")

But the following line still give the same error. Now I'm sure the error is in this line.

fromJSON(getURL("http://127.0.0.1:5984/fooddb/_design/foodview", customrequest='PUT', httpheader=c('Content-Type'='application/json'), postfields="@foodview.json"))
Chris
  • 2,256
  • 1
  • 19
  • 41

1 Answers1

2

To create view on CouchDB you need to create new or update existed design document, not just put function code. I don't know R to write a bit of code, but to create new design document with your view you need to send next JSON instead of just view function code:

{
   "_id": "_design/foodview",
   "views": {
     "foodview": {
       "map": "function(doc) {emit(doc.day, doc.dinner);}"
     }
   }
}
Kxepal
  • 4,659
  • 1
  • 19
  • 16
  • Thanks. That solved the first part of the problem. Now I just need to get the R-part too. – Chris Jun 25 '13 at 15:41