I have seen a lot of interest in the field about using Couchbase with R. It is an easy integration, so here you have some examples to start using it right now.

As a little background, R is a language and environment for statistical computing and graphics. You will find it in the firsts positions in best languages rankings for Data Analysis, Machine Learning or Data Crunching. Data Scientist use R as one of their most powerful tools.

For data ingestion, R can load files in different formats like csv, excel, html, plain text, and more with a simple command line. R can also load data from remote sites using HTTP, and can easily work with JSON.

With all of this in mind, how can we load data from Couchbase into R? Do we need a special adapter? N1QL is the answer. Couchbase query engine accept REST requests, returning JSON documents, so we can directly import data into R. No extra components needed.

Here you have some examples with data from the “travel-sample” bucket, included in Couchbase as an example data set. I am using here the versions R 3.4.1 and Couchbase 4.6.2.

As first exercise, let us load the top 20 airline companies with more flights in our system. We will load this data into an R Data Frame, show the results in the console and built a simple bar graph.

From Couchbase side, this is the query to run:

For the R side, we will use the R Console. First, we have to import the libraries used in this exercise:

Next step is to build some variables, including the Couchbase Query node address and the query. Note the escaped double quotes (\”):

Then we must construct the HTTP request, and read the response in JSON format:

NOTE: If you are using a password protected bucket you have to include credentials as the following:

Then we can save the result in a variable.

To see the value it is enough to type the variable name:

We can also build a bar graph using the ggplot library:

This is the result:

As a second example, we are going to search for the available pet friendly hotels in London, and show them over a map. The N1QL query is like this:

The R code to execute the query and save results:

This are the results:

Now we can use the leaflet library for drawing the results over a map:

The map is opened in a browser:

That’s all. I hope this is useful as first steps in using Couchbase from R. Happy Data Analysis!

For more detail, visit:
N1QL REST API reference
R: The R Project for Statistical Computing
Leaflet for R

Posted by Manuel Hurtado, Solutions Engineer, Couchbase

Manuel is a Couchbase Solutions Engineer, with more than 15 years of experience helping companies to architect their systems, as developer, consultant, trainer and project manager. Happy to learn from the field how people use technology to success.

Leave a reply