Sunday, April 24, 2016

Recording temperature values with CouchDB

After you have successfully installed CouchDB as decribed here, you can simply start it like this:

~$ couchdb start

This short example is build upon the offical tutorial of the core API. Lets create a new database called temperatures.

~$ curl -X PUT http://127.0.0.1:5984/temperatures

Inserting new documents into the temperatures database is as simple as creating a database:

~$ curl -X PUT http://127.0.0.1:5984/temperatures/e7e56c6c-822f-442d-a707-973e20fc8d87 -d '{"celsius": "23.73", "timestamp": 1461326744.1631064}'

I used the Python3 uuid module to create the UUID e7e56c6c-822f-442d-a707-973e20fc8d87 which is used as the document ID. I also created a view called "by-timestamp" inside the design document with the help of Futon and wrote the following map function:

function(doc) {
  var celsius, timestamp;
  if (
doc.celsius && doc.timestamp) {
    celsius = doc.celsius;
    timestamp = doc.timestamp;
    emit(timestamp, {temperature: celsius});
  }
}


Since the view can be parameterized with sort and filter options, its possible to make a GET request that yields the newest document:

http://127.0.0.1:5984/temperatures/_design/foo/_view/by-timestamp?descending=true&limit=1

Furthermore, I created a show called "celsius" in the design document, which adds some HTML around the document content. To insert a show into the design document, the key "shows" must be added with the following value:

{
"celsius" : "function (doc, req) {
               return '<p>Temperature: ' + doc.celsius + '°C</p>';
            }"




The following URL can be used to query the celsius show with a document ID:

http://127.0.0.1:5984/temperaturues/_design/foo/_show/celsius/1644712d-e5ab-48c3-aaa7-ac6eb75b750b

That's it! Any easy way to persist your data, but the concepts behind views and shows are a bit tricky.

No comments:

Post a Comment