Searching from the SDK
Edit this article in GitHub
Version 2.2

Searching from the SDK

You can use the 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 Python SDK you can search full-text indexes by using the iterator-based Bucket.search() 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).
Querying a FTS index through the Python client is performed through the Bucket.search(). This method takes two parameters, the index name to query and the actual search query itself. Additional search options may be specified as keyword arguments.
import couchbase.fulltext as FT
results = cb.search('travel-search', FT.TermQuery('office'), limit=25)
for result in results:
    print(result['id'])

The Bucket.search() method returns an object which may be iterated over to retrieve the results. Each result is a dictionary comprising the layout defined in Response Object Schema.

Other search result data may be accessed using the iterator's meta and facets properties:
results = cb.search(indexname, query)
for result in results:
    handle_result(result)
print(results.meta)
print(results.facets)

Query Types

Query types may be found inside the couchbase.fulltext module. The module contains query classes corresponding to those enumerated in Types of Queries. Query object should be instantiated by 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 as keyword arguments to search().

Query Facets

Query facets may also be added to the general search parameters by using the facets={} keyword argument. The facets keyword argument accepts a dictionary with facet names as keys and facets themselves as values. You can create facet queries by instantiating Facet objects found in the couchbase.fulltext module.

results = cb.search(
        'travel-search', FT.MatchQuery('wine'),
        facets={'countries': FT.TermFacet('country', limit=5)}, limit=0)

# Exhaust the iterator
for _ in results:
    pass

for info in results.facets['countries']['terms']:
    print('Got {} results from {}'.format(info['count'], info['term']))