Couchbase : Making views via script file automatially without using GUI.

Table of contents
Reading Time: 2 minutes

The problem that we faced is that we have to make views manually from the GUI of the couchbase, but it was quite a cumbersome task, so this blog is about how to make views automatically.

In this blog we’ll learn how to create a script of curl commands and just run that script for making views and the  views  will automatically get created on the couchbase server.

You do not have to make views manually now, just run a script file and it automatically gets created , so that you don’t have to make views manually on staging server and it can easily be made just by running a simple script file.

For creating a design document and views from a script file :

Firstly , you have to make a .ddoc file, the name of file should be same as that of the design document that you want to create.

Screenshot from 2015-07-23 12:25:35

Then inside that .ddoc file you have to write the json for creating view

Its format would be like :

{“views”:{“email”:{“map”:”function (doc, meta) {\n  emit(,;\n}”}}}

Where email is the view name and map has the function that we write in the views.

If you are using Javascript functions inside your view then you can change the value of the function accordingly.

{"views":{"name":{"map":"function (doc, meta) {\n  if(!=null){\n  emit(,;\n}\n}"}}}

If you are using reduce function then also you can give it in the same json using reduce element.

For Example:

{"views":{"name":{"map":"function (doc, meta) {\n  if(!=null){\n  emit(,;\n}\n}","reduce":"_stats"}}}

If you want to make more than one view inside a design document then you can change the json accordingly

(doc, meta) {\n  if(!=null){\n  emit(,;\n}\n}","reduce":"_stats"},"code":{\n emit(,null);\n}}}

Then save this file with name emailDocument.ddoc

So for example now you have

Design document: emailDocument

View Name : email

Now for making this view make a script file for example

And inside script file ,write this command :

curl -X PUT -H ‘Content-Type: application/json’ http://Administrator:<password>@localhost:8092/user-account/_design/dev_email -d @email.ddoc

And then save this file.

And now when you execute this script using ./ command

It will automatically make the view in the Couchbase.

And It will give you a response json, if it gets made up successfully. The json would be like