pythonnosqlcouchdbcloudantcouchdb-mango

Create view in CouchDB in a python application


I have a DB in CouchDB and I'm wondering if is it possible to create a view directly from python instead of using GUI. I'm a beginner in CouchDB and I need a function that's equivalent at SELECT DISTINCT in SQL and a view like

function (doc) {
  if(doc.MovieId == "1254")
    emit(doc.Rating, 1);
}

is the ideal. The problem is that I've to do this view for much more MovieIds (taken from keyboard input).

I'm asking you if is possible to create/delete views like this directly from python because on the net I've found nothing. If isn't possible, is that a good idea to make a Mango query and map results by myself?

---EDIT---

json_data = {
  "_id": "_design/titaRat",
  "_rev": "3-ceb11154b13457c55b1f98f4e9d15b03",
  "views": {
    "titRat": {
      "map": "function (doc) { var id_prefix = \"ratings :\"; if(doc._id.substr(0, id_prefix.length) === id_prefix && doc.MovieId == \"1721\") emit(doc.Rating, 1);}",
      "reduce": "_count"
    }
  },
  "language": "javascript",
  "options": {
    "partitioned": False
  }
}

db.save(json_data)


ResourceConflict: ('conflict', 'Document update conflict.')

I got this error, but there aren't document that have this name


Solution

  • You can create a view from python the same way you would create any document in couch deb.

    The difference is that you would need to create a design document.

    The document for your function would look like this:

    {
      "views": {
        "movie_ratings_view": {
          "map": "function(doc) { if(doc.MovieId == "1254") emit(doc.Rating, 1); }",
        }
      }
    }
    

    As you see the map function is saved as a string. If you want to add formating you would need to add it with \n and \t for example.

    To save this document you would POST it to POST /{db}/_design/movie_ratings_ddoc

    You can then call your view via GET /{db}/_design/movie_rations_ddoc/_view/movie_ratings_view

    You can save multiple views per design document.

    If you want to delete a view you can either delete the entire design document or just update the design doc with the view removed from the object.

    For further information on how to use views read: https://docs.couchdb.org/en/master/api/ddoc/views.html