Searching from the SDK
Edit this article in GitHub
Version 2.2

Searching from the SDK

Using the Node.js SDK, you can use the Couchbase Full Text Search service (FTS) to create queryable full-text indexes in Couchbase Server.

Couchbase offers Full-text search support, allowing you to search for documents that contain certain words or phrases. In the Node.js SDK you can search full-text indexes by using the SearchQuery object and executing it with the Bucket.query() API.

Important: The FTS feature is a developer preview in Couchbase Server 4.5. As such, the support in the SDK is still uncomitted and the API is subject to change (although no major changes are expected as of this writing).

The following example shows how to send a simple Search query:

var SearchQuery = couchbase.SearchQuery;
var query = SearchQuery.new('travel-search', SearchQuery.term('office'));
bucket.query(query, function(err, res, meta) {
  for (var i = 0; i < res.length; ++i) {
    console.log('Hit:', res[i].id);
  }
});

The Bucket.query() method returns a SearchQueryResponse object which provides access to all of the information returned by the query.

Other search result data may be accessed using the various other available methods on the SearchResults interface.
bucket.query(…, function(err, res, meta) {
  console.log('Total Hits:', meta.status.total);
  for (var i in meta.facets) {
    console.log('Facet:', i);
  }
});

Query Types

Query types may be found within the SearchQuery class. The package contains query classes corresponding to those enumerated in Types of Queries. The query object should be instantiated by using the associated function matching the type of query you wish to create (i.e.: SearchQuery.term() for a TermQuery), passing the search term (usually a string) as the first argument, followed by some query modifiers.

It is important to distinguish between query options and general search options. Some options affect the search process in general (such as the Limit, indicating how many results to return) while others only affect a specific query (such as Fuzziness for a given query). Because multiple queries can be combined in a single search operation, query specific options can be specified only in the query object itself, while search options are specified through methods on the SearchQuery object itself.

Query Facets

Query facets may also be added to the general search parameters by using the addFacet method. The addFacet method accepts a facet name as well as a facet definition You can create facets by instantiating a Facet object using methods found in the SearchFacet class (i.e.: SearchFacet.term() for a TermFacet).

var query = SearchQuery.new('travel-search', SearchQuery.term('office'));
query.addFacet('countries', SearchFacet.term('country', 5);
bucket.query(query, function(err, res, meta) {
  console.log('Total Countries:', meta.facets['countries'].total);
});