A newer version of this documentation is available.

View Latest

N1QL Queries from the SDK

    You can query for documents in Couchbase using the N1QL query language, a language based on SQL, but designed for structured and flexible JSON documents. Querying can solve typical programming tasks such as finding a user profile by email address, facebook login, or user ID.

    Our query service uses N1QL, which will be fairly familiar to anyone who’s used any dialect of SQL. Further resources for learning about N1QL are listed at the bottom of the page. Before you get started you may wish to checkout the N1QL intro page, or just dive in with a query against our travel sample data set. In this case, the one thing that you need to know is that in order to make a Bucket queryable, it must have at least one index defined. You can define a _primary index on a bucket. When a primary index is defined you can issue non-covered queries on the bucket as well.

    Use cbq, our interactive Query shell. Open it, and enter the following:

    CREATE PRIMARY INDEX ON `travel-sample`

    or replace travel-sample with a different Bucket name to build an index on a different dataset.

    The default installation places cbq in /opt/couchbase/bin/ on Linux, /Applications/Couchbase Server.app/Contents/Resources/couchbase-core/bin/cbq on OS X, and C:\Program Files\Couchbase\Server\bin\cbq.exe on Microsoft Windows.


    As well as the API docs, there are examples in the GitHub repo for:

    Querying at Scope Level

    Developer Preview

    From version 3.0.4 of the C SDK, it is possible to query off the Scope level with the beta version of the next Couchbase Server release, 7.0β, using the lcb_cmdquery_scope_name() method. It takes the statement as a required argument, and then allows additional options if needed.

    This feature is marked Uncommitted. Expect a promotion to Committed API in a future release.

    usage details for this and lcb_cmdquery_scope_qualifier() can be found in the API docs.

    Additional Resources

    N1QL is not the only query option in Couchbase. Be sure to check that your use case fits your selection of query service.

    The Server doc N1QL intro introduces up a complete guide to the N1QL language, including all of the latest additions.

    The N1QL interactive tutorial is a good introduction to the basics of N1QL use.