June 22, 2014

Using RavenDB in Clojure, part three.

This is part three of "Using RavenDB in Clojure". You can find the second part here.

In this part we will carry on with the ravendbtest project we created in part 1 and part 2. Lets cd into the ravendbtest diretory and start a lein repl to get started.

Watching Documents

Using the clj-ravendb client we can "watch" one or more documents for changes.

Open project.clj in your editor of choice.

vim project.clj

Watching documents makes use of Clojures core.async library. Lets add it as a dependecy to our project.

We will also need to require it in the REPL so that we can do some testing.

In part 2 we created some new documents.

We can "watch" these documents for changes using the following code.

First we create a channel, then we create a "watcher" and tell it the document keys we want to "watch" and the channel we want it to use to publish changes. We then perform a blocking read from the channel to retrieve the changed documents.

This read will block until something is put on the channel. If you were to open another Clojure REPL, require the clj-ravendb client and run the following.

clj-ravendb will notice that the document has changed and put it on the channel, the blocking read operation we created earlier will finish and we can evaluate it by typing changes and hitting enter in the original REPL.

Changes will look something like this.

Note. If you don't want to block when reading from the channel then you can read using a go block.

Watching Indexes

We can also watch index queries for changes. This works in exactly the same way as watching documents.


RavenDB supports replication out of the box. I enabled replication for my northwind database and replicated it to http://localhost:8081.

All we need to make use of it when using clj-ravendb is to indicate the database we are using is replicated.

Internally clj-ravendb will call the Raven/Replication/Destinations endpoint on http://localhost:8080 and capture the replications. northwind is now represented as a map like this.

The map contains a :replications key that has a sequence of RavenDB URLs as its value.

When using this client to do any read based operations such as loading documents or querying indexes the client will use one of the :replications if it cannot contact the master, in our case http://localhost:8080.

Thats all for now.

Tags: clojure clj-ravendb ravendb