Couchbase Python Client Library
4.5.0

Using the Couchbase Python SDK

  • Using the Python SDK

Synchronous API

  • Analytics
  • BinaryCollection
  • Core couchbase API
  • Datastructures
  • Diagnostics
  • Query (SQL++)
  • Management
  • Full Text Search
    • Enumerations
      • SearchScanConsistency
        • SearchScanConsistency.NOT_BOUNDED
        • SearchScanConsistency.REQUEST_PLUS
        • SearchScanConsistency.AT_PLUS
    • Options
    • SearchRequest
      • SearchRequest
        • SearchRequest.create()
        • SearchRequest.search_query
        • SearchRequest.vector_search
        • SearchRequest.with_search_query()
        • SearchRequest.with_vector_search()
    • SearchQuery
      • QueryString Queries
        • QueryStringQuery
      • Analytic Queries
        • MatchQuery
        • MatchPhraseQuery
      • Non-Analytic Queries
        • BooleanFieldQuery
        • DocIdQuery
        • PrefixQuery
        • PhraseQuery
        • RegexQuery
        • TermQuery
        • WildcardQuery
      • Range Queries
        • DateRangeQuery
        • NumericRangeQuery
        • TermRangeQuery
      • Compound Queries
        • BooleanQuery
        • ConjunctionQuery
        • DisjunctionQuery
      • Geo Queries
        • GeoBoundingBoxQuery
        • GeoDistanceQuery
        • GeoPolygonQuery
      • Special Queries
        • MatchAllQuery
        • MatchNoneQuery
    • Results
      • SearchMetaData
        • SearchMetaData
      • SearchMetrics
        • SearchMetrics
      • SearchResult
    • Vector Search
      • VectorQuery
        • VectorQuery.boost
        • VectorQuery.create()
        • VectorQuery.field_name
        • VectorQuery.num_candidates
        • VectorQuery.prefilter
        • VectorQuery.vector
        • VectorQuery.vector_base64
      • VectorSearch
        • VectorSearch.from_vector_query()
        • VectorSearch.options
        • VectorSearch.queries
      • Enumerations
        • VectorQueryCombination
      • Options
        • VectorSearchOptions
  • Range Scan
  • Transactions
  • Views

Global API

  • Authentication
  • Exceptions
  • Management Options
  • Options
  • Results
  • Subdocument
  • Parallelism

Asynchronous APIs

  • acouchbase
  • txcouchbase
Couchbase Python Client Library
  • Full Text Search
  • View page source

Full Text Search

Note

Further updates to the search docs will come with future 4.x releases.

  • Enumerations

  • Options

  • SearchRequest

  • SearchQuery

    • QueryString Queries

    • Analytic Queries

    • Non-Analytic Queries

    • Range Queries

    • Compound Queries

    • Geo Queries

    • Special Queries

  • Results

    • SearchMetaData

    • SearchMetrics

    • SearchResult

  • Vector Search

    • Enumerations

    • Options

Enumerations

enum couchbase.search.SearchScanConsistency(value)

SearchScanConsistency

This can be:

NOT_BOUNDED

Which means we just return what is currently in the indexes.

Valid values are as follows:

NOT_BOUNDED = <SearchScanConsistency.NOT_BOUNDED: 'not_bounded'>
REQUEST_PLUS = <SearchScanConsistency.REQUEST_PLUS: 'request_plus'>
AT_PLUS = <SearchScanConsistency.AT_PLUS: 'at_plus'>

Options

class couchbase.options.SearchOptions(timeout=None, limit=None, skip=None, explain=None, fields=None, highlight_style=None, highlight_fields=None, scan_consistency=None, consistent_with=None, facets=None, raw=None, sort=None, disable_scoring=None, scope_name=None, collections=None, include_locations=None, client_context_id=None, serializer=None, show_request=None, log_request=None, log_response=None)

Available options to for a search (FTS) query.

Warning

Importing options from couchbase.search is deprecated. All options should be imported from couchbase.options.

Parameters:
  • timeout (timedelta, optional) – The timeout for this operation. Defaults to global search query operation timeout.

  • limit (int, optional) – Specifies the limit to the number of results that should be returned. Defaults to None.

  • skip (int, optional) – Specifies the number of results to skip from the index before returning results. Defaults to None.

  • explain (bool, optional) – Configures whether the result should contain the execution plan for the search query. Defaults to False.

  • fields (List[str], optional) – Specifies the list of fields which should be searched. Defaults to None.

  • highlight_style (HighlightStyle, optional) – Specifies the mode used for highlighting. Defaults to None.

  • highlight_fields (List[str], optional) – Specifies the list of fields that should be highlighted. Defaults to None.

  • scan_consistency (SearchScanConsistency, optional) – Specifies the consistency requirements when executing the search query.

  • facets (Dict[str, Facet], optional) – Specifies any facets that should be included in the search query. Defaults to None.

  • client_context_id (str, optional) – The returned client context id for this query. Defaults to None.

  • disable_scoring (bool, optional) – Specifies that scoring should be disabled. This improves performance but makes it impossible to sort based on how well a particular result scored. Defaults to False.

  • include_locations (bool optional) – If set to True, will include the locations in the search result. Defaults to False.

  • sort (Union[List[str],List[Sort]], optional) – Specifies a list of fields or search Sort’s to use when sorting the result sets. Defaults to None.

  • scope_name (string, optional) – Specifies the scope which should be searched as part of the search query. Defaults to None.

  • collections (List[str], optional) – Specifies the collections which should be searched as part of the search query. Defaults to None.

  • consistent_with (MutationState, optional) – Specifies a MutationState which the search query should be consistent with. Defaults to None.

  • serializer (Serializer, optional) – Specifies an explicit serializer to use for this specific search query. Defaults to DefaultJsonSerializer.

  • raw (Dict[str, Any], optional) – Specifies any additional parameters which should be passed to the search query engine when executing the search query. Defaults to None.

  • show_request (bool, optional) – Specifies if the search response should contain the request for the search query. Defaults to False.

  • log_request (bool, optional) – UNCOMMITTED Specifies if search request body should appear the log. Defaults to False.

  • log_response (bool, optional) – UNCOMMITTED Specifies if search response should appear in the log. Defaults to False.

SearchRequest

class couchbase.search.SearchRequest(query)

Represents a search query and/or vector search to execute via the Couchbase Full Text Search (FTS) service.

Parameters:

query (Union[SearchQuery, VectorSearch]) – A SearchQuery or VectorSearch to initialize the search request.

Raises:

InvalidArgumentException – If neither a SearchQuery or VectorSearch is provided.

Returns:

The created search request.

Return type:

SearchRequest

classmethod create(query) → SearchRequest

Creates a SearchRequest.

Parameters:

query (Union[SearchQuery, VectorSearch]) – A SearchQuery or VectorSearch to initialize the search request.

Raises:

InvalidArgumentException – If neither a SearchQuery or VectorSearch is provided.

Returns:

The created search request.

Return type:

SearchRequest

property search_query: SearchQuery | None

Returns the search request’s SearchQuery, if it exists.

Type:

Optional[SearchQuery]

property vector_search: VectorSearch | None

Returns the search request’s VectorSearch, if it exists.

Type:

Optional[VectorSearch]

with_search_query(query) → SearchRequest

Add a SearchQuery to the search request.

Parameters:

query (SearchQuery) – The SearchQuery to add to the search request.

Raises:
  • InvalidArgumentException – If the search request already contains a SearchQuery.

  • InvalidArgumentException – If the provided query is not an instance of a SearchQuery.

Returns:

The search request in order to allow method chaining.

Return type:

SearchRequest

with_vector_search(vector_search) → SearchRequest

Add a VectorSearch to the search request.

Parameters:

vector_search (VectorSearch) – The VectorSearch to add to the search request.

Raises:
  • InvalidArgumentException – If the search request already contains a VectorSearch.

  • InvalidArgumentException – If the provided query is not an instance of a VectorSearch.

Returns:

The search request in order to allow method chaining.

Return type:

SearchRequest

SearchQuery

QueryString Queries

class couchbase.search.QueryStringQuery(*args, **kwargs)

Query that specifies the Search Service should search for a match to the specified query string.

See also

Query Language

Examples

Basic search using QueryStringQuery:

from couchbase.search import QueryStringQuery, SearchRequest

# ... other code ...

query = QueryStringQuery('+description:sea -color_hex:fff5ee')
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using QueryStringQuery with kwargs:

from couchbase.search import QueryStringQuery, SearchRequest

# ... other code ...

query = QueryStringQuery(query='+description:sea -color_hex:fff5ee')
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using QueryStringQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import QueryStringQuery, SearchRequest

# ... other code ...

query = QueryStringQuery('+description:sea -color_hex:fff5ee')
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Analytic Queries

class couchbase.search.MatchQuery(*args, **kwargs)

Query that specifies the Search Service should search for an exact match to the specified term inside the Search index’s default field.

Examples

Basic search using MatchQuery:

from couchbase.search import MatchQuery, SearchRequest

# ... other code ...

query = MatchQuery('secondary', field='color_wheel_pos')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using MatchQuery with kwargs:

from couchbase.search import MatchQuery, SearchRequest

# ... other code ...

query = MatchQuery(match='secondary', field='color_wheel_pos')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using MatchQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import MatchQuery, SearchRequest

# ... other code ...

query = MatchQuery('secondary', field='color_wheel_pos')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
property analyzer

Use a defined server-side analyzer to process the input term prior to executing the search

property field

Restrict searching to a given document field

property fuzziness

Allow a given degree of fuzz in the match. Matches which are closer to the original term will be scored higher.

You can apply the fuzziness to only a portion of the string by specifying prefix_length - indicating that only the part of the field after the prefix length should be checked with fuzziness.

This value is specified as a float

property prefix_length

When using fuzziness, this controls how much of the term or phrase is excluded from fuzziness. This may help improve performance at the expense of omitting potential fuzzy matches at the beginning of the string.

class couchbase.search.MatchPhraseQuery(*args, **kwargs)

Query that specifies the Search Service should search for exact matches to the specified phrase. The phrase is composed of one or more terms.

Examples

Basic search using MatchPhraseQuery:

from couchbase.search import MatchPhraseQuery, SearchRequest

# ... other code ...

query = MatchPhraseQuery('white sands', field='description')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using MatchPhraseQuery with kwargs:

from couchbase.search import MatchPhraseQuery, SearchRequest

# ... other code ...

query = MatchPhraseQuery(match_phrase='white sands', field='description')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using MatchPhraseQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import MatchPhraseQuery, SearchRequest

# ... other code ...

query = MatchPhraseQuery('white sands', field='description')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
property analyzer

Use a defined server-side analyzer to process the input term prior to executing the search

property field

Restrict searching to a given document field

Non-Analytic Queries

class couchbase.search.BooleanFieldQuery(*args, **kwargs)

Query that specifies the Search Service should search for to the specified boolean value in the provided field.

Examples

Basic search using BooleanFieldQuery:

from couchbase.search import BooleanFieldQuery, SearchRequest

# ... other code ...

query = BooleanFieldQuery(True, field='perfect_rating')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using BooleanFieldQuery with kwargs:

from couchbase.search import BooleanFieldQuery, SearchRequest

# ... other code ...

query = BooleanFieldQuery(bool=True, field='perfect_rating')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using BooleanFieldQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import BooleanFieldQuery, SearchRequest

# ... other code ...

query = BooleanFieldQuery(True, field='perfect_rating')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
property field

Restrict searching to a given document field

class couchbase.search.DocIdQuery(*args, **kwargs)

Query that specifies the Search Service should search matches to the specified list of document ids.

Examples

Basic search using DocIdQuery:

from couchbase.search import DocIdQuery, SearchRequest

# ... other code ...

query = DocIdQuery(['34','43','61'])
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using DocIdQuery with kwargs:

from couchbase.search import DocIdQuery, SearchRequest

# ... other code ...

query = DocIdQuery(ids=['34','43','61'])
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using DocIdQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import DocIdQuery, SearchRequest

# ... other code ...

query = DocIdQuery(['34','43','61','72])
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
validate()

Optional validation function. Invoked before encoding

class couchbase.search.PrefixQuery(*args, **kwargs)

Query that specifies the Search Service should search for matches to the specified prefix.

Examples

Basic search using PrefixQuery:

from couchbase.search import PrefixQuery, SearchRequest

# ... other code ...

query = PrefixQuery('yellow', field='description')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using PrefixQuery with kwargs:

from couchbase.search import PrefixQuery, SearchRequest

# ... other code ...

query = PrefixQuery(prefix='yellow', field='description')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using PrefixQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import PrefixQuery, SearchRequest

# ... other code ...

query = PrefixQuery('yellow', field='description')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
property field

Restrict searching to a given document field

class couchbase.search.PhraseQuery(*phrases, **kwargs)

Query that specifies the Search Service should search for terms provided in the specified order. The field property must be provided.

Examples

Basic search using PhraseQuery:

from couchbase.search import PhraseQuery, SearchRequest

# ... other code ...

query = PhraseQuery('white sand', field='description')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using PhraseQuery with kwargs:

from couchbase.search import PhraseQuery, SearchRequest

# ... other code ...

query = PhraseQuery(terms='white sand', field='description')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using PhraseQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import PhraseQuery, SearchRequest

# ... other code ...

query = PhraseQuery('white sand', field='description')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
property field

Restrict searching to a given document field

validate()

Optional validation function. Invoked before encoding

class couchbase.search.RegexQuery(*args, **kwargs)

Query that specifies the Search Service should search for matches to the specified regular expression.

Examples

Basic search using RegexQuery:

from couchbase.search import RegexQuery, SearchRequest

# ... other code ...

query = RegexQuery('f[58]f.*', field='color_hex')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using RegexQuery with kwargs:

from couchbase.search import RegexQuery, SearchRequest

# ... other code ...

query = RegexQuery(regexp='f[58]f.*', field='color_hex')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using RegexQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import RegexQuery, SearchRequest

# ... other code ...

query = RegexQuery('f[58]f.*', field='color_hex')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
property field

Restrict searching to a given document field

class couchbase.search.TermQuery(*args, **kwargs)

Query that specifies the Search Service should search for an exact match to the specified term.

Examples

Basic search using TermQuery:

from couchbase.search import TermQuery, SearchRequest

# ... other code ...

query = TermQuery('park', field='description')
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using TermQuery with kwargs:

from couchbase.search import TermQuery, SearchRequest

# ... other code ...

query = TermQuery(term='park', field='description')
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using TermQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import TermQuery, SearchRequest

# ... other code ...

query = TermQuery('park', field='description')
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
property field

Restrict searching to a given document field

property fuzziness

Allow a given degree of fuzz in the match. Matches which are closer to the original term will be scored higher.

You can apply the fuzziness to only a portion of the string by specifying prefix_length - indicating that only the part of the field after the prefix length should be checked with fuzziness.

This value is specified as a float

property prefix_length

When using fuzziness, this controls how much of the term or phrase is excluded from fuzziness. This may help improve performance at the expense of omitting potential fuzzy matches at the beginning of the string.

class couchbase.search.WildcardQuery(*args, **kwargs)

Query that specifies the Search Service should search for a match to the specified wildcard string.

Use ? to allow a match to any single character. Use * to allow a match to zero or many characters.

Examples

Basic search using WildcardQuery:

from couchbase.search import WildcardQuery, SearchRequest

# ... other code ...

query = WildcardQuery('f0f???', field='color_hex')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using WildcardQuery with kwargs:

from couchbase.search import WildcardQuery, SearchRequest

# ... other code ...

query = WildcardQuery(wildcard='f0f???', field='color_hex')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using WildcardQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import WildcardQuery, SearchRequest

# ... other code ...

query = WildcardQuery('f0f???', field='color_hex')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
property field

Restrict searching to a given document field

Range Queries

class couchbase.search.DateRangeQuery(start=None, end=None, **kwargs)

Query that specifies the Search Service should search for matches to the specified date range.

Note

At least one of start or end must be specified.

The date ranges are parsed according to a given datetime_parser. If no parser is specified, the RFC 3339 parser is used. See Generating an RFC 3339 Timestamp <http://goo.gl/LIkV7G>_.

Examples

Basic search using DateRangeQuery:

from couchbase.search import DateRangeQuery, SearchRequest

# ... other code ...

query = DateRangeQuery('2024-01-01',
                       '2024-01-05',
                       inclusive_start=True,
                       inclusive_end=True,
                       field='last_rated')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using DateRangeQuery with kwargs:

from couchbase.search import DateRangeQuery, SearchRequest

# ... other code ...

query = DateRangeQuery(start='2024-01-01',
                       end='2024-01-05',
                       inclusive_start=True,
                       inclusive_end=True,
                       field='last_rated')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using DateRangeQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import DateRangeQuery, SearchRequest

# ... other code ...

query = NumericRangeQuery(3.0,
                          3.2,
                          inclusive_min=True,
                          inclusive_max=False,
                          field='rating')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
property field

Restrict searching to a given document field

class couchbase.search.NumericRangeQuery(min=None, max=None, **kwargs)

Query that specifies the Search Service should search for matches to the specified numerical range.

Note

At least one of min or max must be specified.

Examples

Basic search using NumericRangeQuery:

from couchbase.search import NumericRangeQuery, SearchRequest

# ... other code ...

query = NumericRangeQuery(3.0,
                          3.2,
                          inclusive_min=True,
                          inclusive_max=False,
                          field='rating')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using NumericRangeQuery with kwargs:

from couchbase.search import NumericRangeQuery, SearchRequest

# ... other code ...

query = NumericRangeQuery(min=3.0,
                          max=3.2,
                          inclusive_min=True,
                          inclusive_max=False,
                          field='rating')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using NumericRangeQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import NumericRangeQuery, SearchRequest

# ... other code ...

query = NumericRangeQuery(3.0,
                          3.2,
                          inclusive_min=True,
                          inclusive_max=False,
                          field='rating')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
property field

Restrict searching to a given document field

class couchbase.search.TermRangeQuery(start=None, end=None, min=None, max=None, **kwargs)

Query that specifies the Search Service should search for matches to the specified range of terms.

Note

At least one of min or max must be specified.

Examples

Basic search using TermRangeQuery:

from couchbase.search import TermRangeQuery, SearchRequest

# ... other code ...

query = TermRangeQuery('mist',
                       'misty',
                       inclusive_min=True,
                       inclusive_max=True,
                       field='description')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using TermRangeQuery with kwargs:

from couchbase.search import TermRangeQuery, SearchRequest

# ... other code ...

query = TermRangeQuery(min='mist',
                       max='misty',
                       inclusive_min=True,
                       inclusive_max=True,
                       field='description')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using TermRangeQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import TermRangeQuery, SearchRequest

# ... other code ...

query = TermRangeQuery(min='mist',
                       max='misty',
                       inclusive_min=True,
                       inclusive_max=True,
                       field='description')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
property field

Restrict searching to a given document field

Compound Queries

class couchbase.search.BooleanQuery(must=None, should=None, must_not=None)

A compound query that specifies multiple child queries.

For a BooleanQuery, a document must match the combination of queries to be included in the search results.

Examples

Basic search using BooleanQuery:

from couchbase.search import (BooleanQuery,
                              DateRangeQuery,
                              TermQuery,
                              PrefixQuery,
                              WildcardQuery,
                              SearchRequest)

# ... other code ...

must = [DateRangeQuery('2024-10-01',
                       '2024-12-31',
                       inclusive_start=True,
                       inclusive_end=True,
                       field='last_rated'),
        WildcardQuery('ff????', field='color_hex')]
must_not = [TermQuery('smoke', field='description'),
            PrefixQuery('rain', field='description')]
query = BooleanQuery(must, None, must_not)
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using BooleanQuery with kwargs:

from couchbase.search import (BooleanQuery,
                              DateRangeQuery,
                              TermQuery,
                              PrefixQuery,
                              WildcardQuery,
                              SearchRequest)

# ... other code ...

must = [DateRangeQuery('2024-10-01',
                       '2024-12-31',
                       inclusive_start=True,
                       inclusive_end=True,
                       field='last_rated'),
        WildcardQuery('ff????', field='color_hex')]
must_not = [TermQuery('smoke', field='description'),
            PrefixQuery('rain', field='description')]
query = BooleanQuery(must=must, must_not=must_not)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using BooleanQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import (BooleanQuery,
                              DateRangeQuery,
                              TermQuery,
                              PrefixQuery,
                              WildcardQuery,
                              SearchRequest)

# ... other code ...

must = [DateRangeQuery('2024-10-01',
                       '2024-12-31',
                       inclusive_start=True,
                       inclusive_end=True,
                       field='last_rated'),
        WildcardQuery('ff????', field='color_hex')]
must_not = [TermQuery('smoke', field='description'),
            PrefixQuery('rain', field='description')]
query = BooleanQuery(must, None, must_not)
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
class couchbase.search.ConjunctionQuery(*queries, **kwargs)

A compound query that specifies multiple child queries.

For a ConjunctionQuery, every query object in the array must have a match in a document to include the document in search results.

Examples

Basic search using ConjunctionQuery:

from couchbase.search import ConjunctionQuery, DateRangeQuery, TermQuery, SearchRequest

# ... other code ...

queries = [DateRangeQuery('2024-01-01',
                          '2024-02-15',
                          start_inclusive=False,
                          end_inclusive=False,
                          field='last_rated'),
            TermQuery('sand', field='description')]
query = ConjunctionQuery(*queries)
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using ConjunctionQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import ConjunctionQuery, DateRangeQuery, TermQuery, SearchRequest

# ... other code ...

queries = [DateRangeQuery('2024-01-01',
                          '2024-02-15',
                          start_inclusive=False,
                          end_inclusive=False,
                          field='last_rated'),
            TermQuery('sand', field='description')]
query = ConjunctionQuery(*queries)
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
class couchbase.search.DisjunctionQuery(*queries, **kwargs)

A compound query that specifies multiple child queries.

For a DisjunctionQuery, the min property sets the number of query objects from the disjuncts array that must have a match in a document. If a document does not match the min number of query objects, the Search Service does not include the document in search results.

Examples

Basic search using DisjunctionQuery:

from couchbase.search import DisjunctionQuery, NumericRangeQuery, TermQuery, SearchRequest

# ... other code ...

queries = [NumericRangeQuery(3.0,
                             3.1,
                             inclusive_min=True,
                             inclusive_max=True,
                             field='rating'),
            TermQuery('smoke', field='description')]
query = DisjunctionQuery(*queries)
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using DisjunctionQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import DisjunctionQuery, NumericRangeQuery, TermQuery, SearchRequest

# ... other code ...

queries = [NumericRangeQuery(3.0,
                             3.1,
                             inclusive_min=True,
                             inclusive_max=True,
                             field='rating'),
            TermQuery('smoke', field='description')]
query = DisjunctionQuery(*queries)
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Geo Queries

class couchbase.search.GeoBoundingBoxQuery(top_left=None, bottom_right=None, **kwargs)

Query that specifies the Search Service should search for geo location values in a defined rectangle.

If you use location as an array, your array must contain a longitude value followed by a latitude value.

Examples

Basic search using GeoBoundingBoxQuery:

from couchbase.search import GeoBoundingBoxQuery, SearchRequest

# ... other code ...

query = GeoBoundingBoxQuery((-0.489, 51.686), (0.236, 51.28), field='geo_location')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using GeoBoundingBoxQuery with bounding box points as list:

from couchbase.search import GeoBoundingBoxQuery, SearchRequest

# ... other code ...

query = GeoBoundingBoxQuery([-0.489, 51.686], [0.236, 51.28], field='geo_location')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using GeoBoundingBoxQuery with location as dict:

from couchbase.search import GeoBoundingBoxQuery, SearchRequest

# ... other code ...

query = GeoBoundingBoxQuery({'lon': -0.489, 'lat': 51.686},
                            {'lon': 0.236, 'lat': 51.28},
                            field='geo_location')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using GeoBoundingBoxQuery with kwargs:

from couchbase.search import GeoBoundingBoxQuery, SearchRequest

# ... other code ...

query = GeoBoundingBoxQuery(top_left=(-0.489, 51.686), bottom_right=(0.236, 51.28), field='geo_location')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using GeoDistanceQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import GeoBoundingBoxQuery, SearchRequest

# ... other code ...

query = GeoBoundingBoxQuery((-0.489, 51.686), (0.236, 51.28), field='geo_location')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
class couchbase.search.GeoDistanceQuery(distance=None, location=None, **kwargs)

Query that specifies the Search Service should search for geo location values in a set radius around a specified latitude and longitude.

If you use location as an array, your array must contain a longitude value followed by a latitude value.

The following distance units:
  • mm: Millimeters

  • cm: Centimeters

  • in: Inches

  • yd: Yards

  • ft: Feet

  • m: Meters

  • km: Kilometers

  • mi: Miles

  • nm: Nautical miles

Examples

Basic search using GeoDistanceQuery:

from couchbase.search import GeoDistanceQuery, SearchRequest

# ... other code ...

query = GeoDistanceQuery('130mi', (-115.1391, 36.1716), field='geo_location')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using GeoDistanceQuery with location as dict:

from couchbase.search import GeoDistanceQuery, SearchRequest

# ... other code ...

query = GeoDistanceQuery('130mi', {'lon': -115.1391, 'lat': 36.1716}, field='geo_location')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using GeoDistanceQuery with kwargs:

from couchbase.search import GeoDistanceQuery, SearchRequest

# ... other code ...

query = GeoDistanceQuery(distance='130mi', location=(-115.1391, 36.1716), field='geo_location')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using GeoDistanceQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import GeoDistanceQuery, SearchRequest

# ... other code ...

query = GeoDistanceQuery('130mi', (-115.1391, 36.1716), field='geo_location')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
class couchbase.search.GeoPolygonQuery(polygon_points=None, **kwargs)

Query that specifies the Search Service should search for geo location values in a defined polygon.

The point tuple must contain a longitude value followed by a latitude value.

Examples

Basic search using GeoPolygonQuery:

from couchbase.search import GeoPolygonQuery, SearchRequest

# ... other code ...

query = GeoPolygonQuery([(37.79393211306212, -122.44234633404847),
                         (37.77995881733997, -122.43977141339417),
                         (37.788031092020155, -122.42925715405579),
                         (37.79026946582319, -122.41149020154114),
                         (37.79571192027403, -122.40735054016113),
                         (37.79393211306212, -122.44234633404847)],
                         field='geo_location')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using GeoPolygonQuery with kwargs:

from couchbase.search import GeoPolygonQuery, SearchRequest

# ... other code ...

pts = [(37.79393211306212, -122.44234633404847),
       (37.77995881733997, -122.43977141339417),
       (37.788031092020155, -122.42925715405579),
       (37.79026946582319, -122.41149020154114),
       (37.79571192027403, -122.40735054016113),
       (37.79393211306212, -122.44234633404847)]
query = GeoPolygonQuery(polygon_points=pts, field='geo_location')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Basic search using GeoPolygonQuery with SearchOptions:

from couchbase.options import SearchOptions
from couchbase.search import GeoPolygonQuery, SearchRequest

# ... other code ...

query = GeoPolygonQuery([(37.79393211306212, -122.44234633404847),
                         (37.77995881733997, -122.43977141339417),
                         (37.788031092020155, -122.42925715405579),
                         (37.79026946582319, -122.41149020154114),
                         (37.79571192027403, -122.40735054016113),
                         (37.79393211306212, -122.44234633404847)],
                         field='geo_location')
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name, req, SearchOptions(limit=3, fields=['*']))
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Special Queries

class couchbase.search.MatchAllQuery(**kwargs)

Special query which matches all documents

Examples

Basic search using MatchAllQuery:

from couchbase.search import MatchAllQuery, SearchRequest

# ... other code ...

query = MatchAllQuery()
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')
class couchbase.search.MatchNoneQuery(**kwargs)

Special query which matches no documents

Examples

Basic search using MatchNoneQuery:

from couchbase.search import MatchNoneQuery, SearchRequest

# ... other code ...

query = MatchNoneQuery()
req = SearchRequest.create(query)
search_res = scope.search(scope_index_name)
for r in search_res.rows():
    print(f'Found search result: {r}')
print(f'metadata={search_res.metadata()}')

Results

SearchMetaData

class couchbase.search.SearchMetaData(raw)

Represents the meta-data returned along with a search query result.

SearchMetrics

class couchbase.search.SearchMetrics(raw)

SearchResult

class couchbase.result.SearchResult
rows()

The rows which have been returned by the search query.

Note

If using the acouchbase API be sure to use async for when looping over rows.

Returns:

Either an iterable or async iterable.

Return type:

Iterable

metadata()

The meta-data which has been returned by the search query.

Returns:

An instance of SearchMetaData.

Return type:

SearchMetaData

Vector Search

class couchbase.vector_search.VectorQuery(field_name, vector, num_candidates=None, boost=None, prefilter=None)

Represents a vector query.

Parameters:
  • field_name (str) – The name of the field in the search index that stores the vector.

  • vector (Union[List[float], str]) – The vector to use in the query.

  • num_candidates (int, optional) – Specifies the number of results returned. If provided, must be greater or equal to 1.

  • boost (float, optional) – Add boost to query.

  • prefilter (~couchbase.search.SearchQuery, optional) – Specifies a pre-filter to use for the vector query.

Raises:
  • InvalidArgumentException – If the vector is not provided.

  • InvalidArgumentException – If the vector is not a list or str.

  • InvalidArgumentException – If vector is a list and all values of the provided vector are not instances of float.

Returns:

The created vector query.

Return type:

VectorQuery

property boost: float | None

Returns vector query’s boost value, if it exists.

Type:

Optional[float]

classmethod create(field_name, vector, num_candidates=None, boost=None, prefilter=None) → VectorQuery

Creates a VectorQuery.

Parameters:
  • field_name (str) – The name of the field in the search index that stores the vector.

  • vector (Union[List[float], str]) – The vector to use in the query.

  • num_candidates (int, optional) – Specifies the number of results returned. If provided, must be greater or equal to 1.

  • boost (float, optional) – Add boost to query.

  • prefilter (~couchbase.search.SearchQuery, optional) – Specifies a pre-filter to use for the vector query.

Raises:
  • InvalidArgumentException – If the vector is not provided.

  • InvalidArgumentException – If the vector is not a list or str.

  • InvalidArgumentException – If vector is a list and all values of the provided vector are not instances of float.

Returns:

The created vector query.

Return type:

VectorQuery

property field_name: str

Returns vector query’s field name

Type:

str

property num_candidates: int | None

Returns vector query’s num candidates value, if it exists.

Type:

Optional[int]

property prefilter: SearchQuery | None

Returns vector query’s prefilter query, if it exists.

Type:

Optional[SearchQuery]

property vector: List[float] | None

Returns the vector query’s vector.

Type:

Optional[List[float]]

property vector_base64: str | None

Returns the vector query’s base64 vector str.

Type:

Optional[str]

class couchbase.vector_search.VectorSearch(queries, options=None)

Represents a vector search.

Parameters:
  • queries (List[VectorQuery]) – The list of VectorQuery’s to use for the vector search.

  • options (VectorSearchOptions, optional) – Options to set for the vector search.

Raises:
  • InvalidArgumentException – If a list of VectorQuery is not provided.

  • InvalidArgumentException – If all values of the provided queries are not instances of VectorQuery.

Returns:

The created vector search.

Return type:

VectorSearch

classmethod from_vector_query(query) → VectorSearch

Creates a VectorSearch from a single VectorQuery.

Parameters:

query (VectorQuery) – A VectorQuery’s to use for the vector search.

Raises:

InvalidArgumentException – If the provided query is not an instance of VectorQuery.

Returns:

The created vector search.

Return type:

VectorSearch

property options: VectorSearchOptions | None

INTERNAL

property queries: List[VectorQuery]

INTERNAL

Enumerations

enum couchbase.vector_search.VectorQueryCombination(value)

Specifies how multiple vector searches are combined.

This can be one of:

AND: Indicates that multiple vector queries should be combined with logical AND.

OR: Indicates that multiple vector queries should be combined with logical OR.

Valid values are as follows:

AND = <VectorQueryCombination.AND: 'and'>
OR = <VectorQueryCombination.OR: 'or'>

Options

class couchbase.options.VectorSearchOptions(vector_query_combination=None)

Available options to for a FTS vector search.

Parameters:

vector_query_combination (VectorQueryCombination, optional) – Specifies logical operation to use with multiple vector queries.

Previous Next

© Copyright 2013-2025, Couchbase, Inc..

Built with Sphinx using a theme provided by Read the Docs.