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.
Sunday, April 24, 2016
Thursday, April 7, 2016
Handling null in Scala
When you are using Java APIs, you might find yourself in the situation that you have to deal with null. In plain Scala, usually you wouldn't use null, but use an Option instead.
The apply method of the Option singleton object has a nice way to convert null to None (see Option.scala):
Hence, you can do Option(null) and you'll get None.
A simple example that handles null in a safe way:
val maybeNull = someJavaMethodThatMightReturnNull(42)
Option(maybeNull).foreach(println)
On the other hand, if you do Some(null) you'll get back Some(null).
The apply method of the Option singleton object has a nice way to convert null to None (see Option.scala):
def apply[A](x: A): Option[A] = if (x == null) None else Some(x)
Hence, you can do Option(null) and you'll get None.
A simple example that handles null in a safe way:
val maybeNull = someJavaMethodThatMightReturnNull(42)
Option(maybeNull).foreach(println)
On the other hand, if you do Some(null) you'll get back Some(null).
Subscribe to:
Posts (Atom)