Introduction
This will be the third post in a series about the Couchbase Mobile stack. You can find the first and second posts here and here, respectively. They cover installing Couchbase Server and some interesting bits of Couchbase Web Console. In this post we’ll talk about working with Couchbase Server from the command line.
Background
To get comfortable with the whole stack, it’s great to install and run everything on your development machine. In this series of posts, I’ll walk through the steps get to started with each component. I’ll show how to do a little extra exploring along the way, too.
I’ll only do minimal configuration. This is not intended to explain what you need for a production environment. I assume you’re familiar with some basics of NoSQL, have some understanding of Couchbase, and know how to build apps in something like Java, Android, or iOS. If you want to read up on NoSQL databases or Couchbase, you can find lots of resources on the Couchbase site.
Couchbase is open-source. Everything I’ll use here is free to try out. See the end of the post for more resources if you need help.
Command Line
Couchbase Server has quite a number of command line tools. It also has an extensive REST API. Let’s take a look at a few interesting points.
Command Line Utilities
On a Mac, you can usually find the command line tools in /Applications/Couchbase Server.app/Contents/Resources/couchbase-core/bin.
You can find out the command locations for Linux and Windows here: http://developer.couchbase.com/documentation/server/current/cli/cli-intro.html
couchbase-cli: The Command Line Cluster Management Tool
This tool can work on single nodes or entire clusters. It supports commands for everything from manipulating buckets to cross-data center replications. Here are just a few examples.
Server list
This next command will return a brief list of servers in a cluster.
1 |
$ couchbase-cli server-list -c localhost:8091 -u Administrator -p password |
Output
1 |
ns_1@127.0.0.1 127.0.0.1:8091 healthy active |
As we’d expect, this shows we have one active server running locally.
(Note: for brevity I’ll leave off the cluster, username, and password options going forward. You’ll need them for the actual commands, though.)
Collecting logs
We can turn on logging. There are options to automatically upload the data for support.
1 |
$ couchbase-cli collect-logs-start --all-nodes |
Output
1 |
SUCCESS: Log collection started |
Next, check the status.
1 |
$ couchbase-cli collect-logs-status |
Output
1 2 3 4 5 |
Status: completed Details: Node: ns_1@127.0.0.1 Status: collected path : /Users/hod/Library/Application Support/Couchbase/var/lib/couchbase/tmp/collectinfo-2016-12-06T213207-ns_1@127.0.0.1.zip |
And stop logging.
1 |
$ couchbase-cli collect-logs-stop |
Output
1 |
SUCCESS: collect logs successfully stopped |
The log files are extensive. The sample here contained many files and over a megabyte of information. It’s all text you can look through. If you ever need support for a CB Server installation, it’s good to know how to get this data.
cbq: The Command Line Shell for N1QL
The other tool we’ll look at is cbq, the interactive shell for running N1QL queries.
In this case, the command will loop prompting us for input. Start by running with no options.
1 |
$ cbq |
You should immediately see a couple of notices and the command prompt.
1 2 3 4 5 |
No input credentials. In order to connect to a server with authentication, please provide credentials. Connected to : http://localhost:8091/. Type Ctrl-D or QUIT to exit. Path to history file for the shell : /Users/hod/.cbq_history cbq> |
Create a primary index
To run queries, you’ll at least need a primary index. Some versions of the beer-sample data come with one, some don’t.
1 |
cbq> CREATE PRIMARY INDEX on `beer-sample`; |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{ "requestID": "e708d3aa-cfa4-4322-9c8c-a6b6524ba99b", "signature": null, "results": [ ], "status": "success", "metrics": { "elapsedTime": "579.828473ms", "executionTime": "578.844657ms", "resultCount": 0, "resultSize": 0 } } |
Running queries
Here’s an example of a fairly simple query.
1 |
cbq> SELECT DISTINCT category, style FROM `beer-sample` WHERE type = "beer" AND style LIKE "%Imperial%" ORDER BY category, style; |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
{ "requestID": "2d4b3052-d42f-4081-bff1-1a06576dec92", "signature": { "category": "json", "style": "json" }, "results": [ { "category": "North American Ale", "style": "American-Style Imperial Stout" }, { "category": "North American Ale", "style": "Imperial or Double India Pale Ale" }, { "category": "North American Ale", "style": "Imperial or Double Red Ale" } ], "status": "success", "metrics": { "elapsedTime": "259.555065ms", "executionTime": "259.496458ms", "resultCount": 3, "resultSize": 331, "sortCount": 3 } } |
We’ve pulled all the beers that have “Imperial” as part of their style description.
Notice the back ticks around beer-sample. These are needed because of the dash in the name.
N1QL should look familiar if you know SQL. N1QL is a superset of SQL. JSON data often isn’t flat like relational data. N1QL has extensions to do things like unroll arrays. You can read more about N1QL here.
To understand N1QL in more depth, I recommend trying out this great interactive tutorial.
You can find a helpful post by Nic Raboy on more advanced features of cbq here.
REST API
Couchbase Server has an extensive set of REST endpoints. Most of them have to do with managing deployments.
I will show examples using curl. There’s a really nice tool that I recommend as a replacement for curl, httpie. It’s a little easier to use, and creates colorized output. I won’t use it here since curl is more commonly found.
I find other endpoints interesting see what they produce, but for our purposes I’m going to focus on queries.
View queries
In a my previous post on the Couchbase Web Console, we took a look at Views. Views create a static index that you can use to retrieve information. You can control the response with a number of options. Much of the value of Views comes from how you define the map/reduce functions, but these options further enhance using Views to query data. Filtering by key is especially useful. Let’s take a look.
You access Views using URIs of the form
1 |
GET /[bucket-name]/_design/[ddoc-name]/_view/[view-name] |
For our beer sample, we can get all the brewery and beer information like this.
1 |
$ curl http://localhost:8092/beer-sample/_design/beer/_view/brewery_beers |
That outputs a lot of information. Here’s just a short sample of the output.
1 2 3 4 |
{"total_rows":7303,"rows":[ {"id":"21st_amendment_brewery_cafe","key":["21st_amendment_brewery_cafe"],"value":null}, {"id":"21st_amendment_brewery_cafe-21a_ipa","key":["21st_amendment_brewery_cafe","21st_amendment_brewery_cafe-21a_ipa"],"value":null}, {"id":"21st_amendment_brewery_cafe-563_stout","key":["21st_amendment_brewery_cafe","21st_amendment_brewery_cafe-563_stout"],"value":null}, |
You can see the key information. We can use this to narrow the results. Here’s an example using a single key.
1 |
$ curl -g http://localhost:8092/beer-sample/_design/beer/_view/brewery_beers?key='["yuksom_breweries"]' |
And the result.
1 2 3 4 |
{"total_rows":7303,"rows":[ {"id":"yuksom_breweries","key":["yuksom_breweries"],"value":null} ] } |
Notice I added a -g flag. Curl by default allows certain types of pattern matching (globbing). This works using the special characters {} and []. We need those to specify the key in JSON. The easiest way is to turn globbing off. Don’t forget the single quotes around the parameter, too.
That example filtered by one key. Here’s one that shows how to get results matching more than one at a time.
1 |
$ curl -g -u Administrator:password http://localhost:8092/beer-sample/_design/beer/_view/brewery_beers?keys='[["yuksom_breweries"],["wild_duck_brewing"]]' |
Notice the output isn’t sorted.
1 2 3 4 5 |
{"total_rows":7303,"rows":[ {"id":"yuksom_breweries","key":["yuksom_breweries"],"value":null}, {"id":"wild_duck_brewing","key":["wild_duck_brewing"],"value":null} ] } |
Beyond the use in debugging (or just understanding what’s going on with) views, I’ve seen some cool things written just using shell scripts and this kind of querying.
N1QL queries
Turns out you can run N1QL queries from the command line, too. Here’s a simple example pulling everything from the beer sample bucket.
1 |
$ curl http://localhost:8093/query/service?statement='SELECT%20*%20FROM%20`beer-sample`' |
The output includes some stats and the full documents. (The stats are output to stderr on a Mac).
1 2 3 |
% Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 16240 0 16240 0 0 299k 0 --:--:-- --:--:-- --:--:-- 299k |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
{ "requestID": "936d7b6a-1dea-4625-a6b2-1be91967187e", "signature": { "*": "*" }, "results": [ { "beer-sample": { "address": [ "563 Second Street" ], "city": "San Francisco", "code": "94107", "country": "United States", "description": "The 21st Amendment Brewery offers a variety of award winning house made brews and American grilled cuisine in a comfortable loft like setting. Join us before and after Giants baseball games in our outdoor beer garden. A great location for functions and parties in our semi-private Brewers Loft. See you soon at the 21A!", "geo": { "accuracy": "ROOFTOP", "lat": 37.7825, "lon": -122.393 }, "name": "21st Amendment Brewery Cafe", "phone": "1-415-369-0900", "state": "California", "type": "brewery", "updated": "2010-10-24 13:54:07", "website": "http://www.21st-amendment.com/" } }, { "beer-sample": { ... |
The N1QL command must have certain characters encoded to work properly. In this case, you can probably guess that %20 is the encoding for a single space. You can read more about that on this Stack Overflow post.
Next Steps
We’ve spent a good amount of time looking at Couchbase Server. Next we’ll jump into mobile by taking a dive into Sync Gateway. I’ll follow roughly the same format. In the case of Sync Gateway, though, we’ll see there’s a lot more to do using the REST APIs. This will include some tricks to help with diagnosing common problems. After that we’ll look at Couchbase Lite, and then wrap everything up by looking at data moving from end-to-end through the complete stack. Stay tuned.
[buttongroup][button style=”btn-link btn-lg” icon=”fa fa-arrow-left” align=”left” iconcolor=”#dd3333″ type=”link” target=”false” title=”Previous: Couchbase Web Console” link=”https://www.couchbase.com/blog/comfortable-couchbase-mobile-couchbase-web-console/” linkrel=””][button style=”btn-link btn-lg” icon=”fa fa-arrow-right” align=”left” iconcolor=”#dd3333″ type=”link” target=”false” title=”Next: Installing Sync Gateway” link=”https://www.couchbase.com/blog/getting-comfortable-couchbase-mobile-installing-sync-gateway/” linkrel=””][/buttongroup]
Postscript
Check out more resources on our developer portal and follow us on Twitter @CouchbaseDev.
You can post questions on our forums. And we actively participate on Stack Overflow.
You can follow me personally at @HodGreeley
[…] Previous: Installing Couchbase Server Next: Couchbase Server via the Command Line […]
[…] Previous: Couchbase Server via the Command Line Next: Sync Gateway via the Command Line […]