Search code examples
pythonpython-2.7couchdbcouchdb-python

CouchDB-Python retrieving documents


The following document is a small example and is stored in CouchDB.

{
  "_id": "Test4",
  "referenceName": "refA",
  "positions": {
      "A": 422,
      "B": 5442
  },
  "details": {
      ...
      "infoA": "AQQ811P0",
      ...
  },
  ...
}

Now I am not quite sure how write a function def retrieve_infoA(name="AQQ811P0") to only retrieve:

  • id
  • referenceName
  • positions

Solution

  • Have you created a CouchDB view to retrieve the data? It will look something like this:

    {
      "_id": "_design/ddoc",
      "views": {
        "by_infoA": {
          "map": "function(doc) {
                       if(doc.details && doc.details.infoA)  {
                          emit(doc.details.infoA);
                       }
                  }"
        }
      },
      "language": "javascript"
    }
    

    You can then call the view with a URL fragment similar to this:

    /dbname/_design/ddoc/_view/by_infoA?key="AQQ811P0"
    

    You will retrieve the whole document, but in your application you only use the fields that you are interested in.

    See here for more information.