Couchdb example: basics
From wikinotes
This can be a lot to take in, so here is an example using curl and cdbcli.
NOTE:
in retrospect, I would have used curl exclusively
NOTE:
also note that JSON does not support comments
Create a database, and 4x documents
cdbcli mkdir test_database cd test_database touch will # { # "name": "will", # "age' : 30, # "shoesize" : 13, # } touch alex # { # "name": "alex", # "age' : 26, # "shoesize" : 9, # } touch zaphod # (zaphod has no shoesize) # { # "name": "zaphod", # "age' : 27, # } touch arthur # (zaphod has no shoesize) # { # "name": "arthur", # "age' : 20, # "shoesize": 15 # }
Create a design, and within it 3x views (queries)
cdbcli cd test_database touch _design/shoeinfo{ "views": { /* * returns everything * =================== */ "all_docs" : { "map" : "function(doc) { emit( doc.id, doc.shoesize ); }" } /* * checks for existence of doc.shoesize, emits only those docs * =========================================================== */ "docs_with_shoesizes" : { "map" : "function(doc) { if (doc.shoesize){ emit( doc.id, doc.shoesize ); } }" } /* * ( returned documents are sorted by the first argument to emit ) * ( multiple fields can also be returned in a list, dict, or other ) * =================================================================== */ "sorted_by_shoesize" : { "map" : "function(doc) { if (doc.shoesize && doc.age){ emit( doc.shoesize, [doc.name,doc.age] ); } }" } } }
Query your view
curl -X GET http://127.0.0.1:5984/test_database/_design/showinfo/_view/all_docs ## function(doc) { emit( doc.name, doc.shoesize ); }{"total_rows":4,"offset":0,"rows":[ {"id":"alex" , "key":"alex" , "value":8 }, {"id":"arthur" , "key":"arthur" , "value":15}, {"id":"will" , "key":"will" , "value":13}, {"id":"zaphod" , "key":"zaphod" , "value":null} // zaphod's document is returned (with a shoesize of null , because the key does not exist) ]}
curl -X GET http://127.0.0.1:5984/test_database/_design/showinfo/_view/docs_with_shoesizes ## function(doc) { if (doc.shoesize){ emit( doc.name, doc.shoesize ); } }{"total_rows":3,"offset":0,"rows":[ {"id":"alex" , "key":"alex" , "value":8 } , {"id":"arthur" , "key":"arthur" , "value":15} , {"id":"will" , "key":"will" , "value":13} ]}
curl -X GET http://127.0.0.1:5984/test_database/_design/showinfo/_view/sorted_by_shoesize ## function(doc) { if (doc.shoesize && doc.age){ emit( doc.shoesize, [doc.name,doc.age] ); } }{"total_rows":3,"offset":0,"rows":[ {"id":"alex" , "key":8 , "value":["alex" , 26 ]} , {"id":"will" , "key":13 , "value":[ "will" , 30 ]} , {"id":"arthur" , "key":15 , "value":[ "arthur" , 35 ]} ]}