0
# Couchbase Python Client
1
2
A comprehensive Python client library for Couchbase, a distributed NoSQL document database. The SDK enables developers to connect to and interact with Couchbase Server clusters, offering both synchronous and asynchronous operations through asyncio and Twisted frameworks. It supports key-value operations, SQL++ (N1QL) queries, full-text search, analytics, and management operations including bucket, user, and index management.
3
4
## Package Information
5
6
- **Package Name**: couchbase
7
- **Language**: Python
8
- **Installation**: `pip install couchbase`
9
10
## Core Imports
11
12
```python
13
from couchbase.cluster import Cluster
14
from couchbase.auth import PasswordAuthenticator
15
from couchbase.options import ClusterOptions
16
```
17
18
Asynchronous operations:
19
20
```python
21
from acouchbase.cluster import ACluster
22
```
23
24
Twisted framework:
25
26
```python
27
from txcouchbase.cluster import TxCluster
28
```
29
30
## Basic Usage
31
32
```python
33
from couchbase.cluster import Cluster
34
from couchbase.auth import PasswordAuthenticator
35
from couchbase.options import ClusterOptions
36
import couchbase.subdocument as SD
37
38
# Connect to cluster
39
auth = PasswordAuthenticator("username", "password")
40
cluster = Cluster("couchbase://localhost", ClusterOptions(auth))
41
42
# Get bucket and collection
43
bucket = cluster.bucket("travel-sample")
44
collection = bucket.default_collection()
45
46
# Basic document operations
47
doc = {"name": "John Doe", "age": 30, "city": "San Francisco"}
48
result = collection.upsert("user::123", doc)
49
print(f"CAS: {result.cas}")
50
51
# Retrieve document
52
get_result = collection.get("user::123")
53
print(f"Document: {get_result.content_as[dict]}")
54
55
# N1QL query
56
query = "SELECT name, age FROM `travel-sample` WHERE type = 'user' LIMIT 10"
57
query_result = cluster.query(query)
58
for row in query_result:
59
print(row)
60
```
61
62
## Architecture
63
64
The Couchbase Python client follows a hierarchical structure:
65
66
- **Cluster**: Top-level connection and management interface
67
- **Bucket**: Database-level operations and container for scopes
68
- **Scope**: Logical grouping of collections (default scope: "_default")
69
- **Collection**: Document container with key-value and subdocument operations
70
- **Management APIs**: Administrative operations for buckets, users, indexes, etc.
71
72
The client supports multiple operation modes:
73
- **Synchronous**: Standard blocking operations (couchbase module)
74
- **Asynchronous**: asyncio-based non-blocking operations (acouchbase module)
75
- **Twisted**: Twisted framework integration (txcouchbase module)
76
77
## Capabilities
78
79
### Cluster Connection and Authentication
80
81
Essential cluster connection, authentication, and configuration management. Supports multiple authentication methods including RBAC, certificate-based authentication, and connection pooling.
82
83
```python { .api }
84
class Cluster:
85
def __init__(self, connection_string: str, options: ClusterOptions = None): ...
86
def bucket(self, bucket_name: str) -> Bucket: ...
87
def query(self, statement: str, options: QueryOptions = None) -> QueryResult: ...
88
```
89
90
[Cluster Operations](./cluster-operations.md)
91
92
### Document Operations
93
94
Core key-value operations for creating, reading, updating, and deleting documents. Includes support for atomic operations, durability requirements, and bulk operations.
95
96
```python { .api }
97
class CBCollection:
98
def get(self, key: str, options: GetOptions = None) -> GetResult: ...
99
def upsert(self, key: str, value: Any, options: UpsertOptions = None) -> MutationResult: ...
100
def insert(self, key: str, value: Any, options: InsertOptions = None) -> MutationResult: ...
101
def replace(self, key: str, value: Any, options: ReplaceOptions = None) -> MutationResult: ...
102
def remove(self, key: str, options: RemoveOptions = None) -> MutationResult: ...
103
```
104
105
[Document Operations](./document-operations.md)
106
107
### Subdocument Operations
108
109
Efficient operations on specific paths within JSON documents without retrieving or replacing entire documents. Supports atomic mutations and lookups on document fragments.
110
111
```python { .api }
112
class CBCollection:
113
def lookup_in(self, key: str, spec: List[Spec], options: LookupInOptions = None) -> LookupInResult: ...
114
def mutate_in(self, key: str, spec: List[Spec], options: MutateInOptions = None) -> MutateInResult: ...
115
```
116
117
[Subdocument Operations](./subdocument-operations.md)
118
119
### N1QL Queries
120
121
SQL++ (N1QL) query execution with support for prepared statements, parameterized queries, and various consistency levels. Enables complex data analysis and retrieval operations.
122
123
```python { .api }
124
class Cluster:
125
def query(self, statement: str, options: QueryOptions = None) -> QueryResult: ...
126
127
class QueryResult:
128
def __iter__(self) -> Iterator[dict]: ...
129
def metadata(self) -> QueryMetaData: ...
130
```
131
132
[N1QL Queries](./n1ql-queries.md)
133
134
### Full-Text Search
135
136
Advanced search capabilities with support for complex queries, faceting, sorting, and highlighting. Enables powerful text search across document collections.
137
138
```python { .api }
139
class Cluster:
140
def search_query(self, index: str, query: SearchQuery, options: SearchOptions = None) -> SearchResult: ...
141
142
class SearchQuery:
143
@staticmethod
144
def match(match: str) -> MatchQuery: ...
145
@staticmethod
146
def term(term: str) -> TermQuery: ...
147
```
148
149
[Full-Text Search](./search-operations.md)
150
151
### Analytics
152
153
Analytics query execution for complex data analysis and reporting. Supports large-scale analytical workloads with integration to external data sources.
154
155
```python { .api }
156
class Cluster:
157
def analytics_query(self, statement: str, options: AnalyticsOptions = None) -> AnalyticsResult: ...
158
159
class AnalyticsResult:
160
def __iter__(self) -> Iterator[dict]: ...
161
def metadata(self) -> AnalyticsMetaData: ...
162
```
163
164
[Analytics Operations](./analytics-operations.md)
165
166
### Management Operations
167
168
Administrative operations for managing cluster resources including buckets, collections, users, roles, and indexes across all service types.
169
170
```python { .api }
171
class Cluster:
172
def buckets(self) -> BucketManager: ...
173
def users(self) -> UserManager: ...
174
def query_indexes(self) -> QueryIndexManager: ...
175
def analytics_indexes(self) -> AnalyticsIndexManager: ...
176
def search_indexes(self) -> SearchIndexManager: ...
177
def eventing_functions(self) -> EventingFunctionManager: ...
178
```
179
180
[Management Operations](./management-operations.md)
181
182
### View Operations
183
184
Traditional MapReduce view queries for data indexing and querying. Provides compatibility with legacy Couchbase applications using design documents.
185
186
```python { .api }
187
class Bucket:
188
def view_query(self, design_doc: str, view_name: str, options: ViewOptions = None) -> ViewResult: ...
189
def view_indexes(self) -> ViewIndexManager: ...
190
```
191
192
[View Operations](./view-operations.md)
193
194
### Asynchronous Operations
195
196
Asyncio-based asynchronous operations for high-performance, non-blocking applications. Provides the same API surface as synchronous operations with async/await support.
197
198
```python { .api }
199
class ACluster:
200
async def bucket(self, bucket_name: str) -> ABucket: ...
201
async def query(self, statement: str, options: QueryOptions = None) -> QueryResult: ...
202
203
class AsyncCBCollection:
204
async def get(self, key: str, options: GetOptions = None) -> AsyncGetResult: ...
205
async def upsert(self, key: str, value: Any, options: UpsertOptions = None) -> AsyncMutationResult: ...
206
```
207
208
[Asynchronous Operations](./async-operations.md)
209
210
## Common Types
211
212
```python { .api }
213
class ClusterOptions:
214
def __init__(self, authenticator: Authenticator = None): ...
215
216
class PasswordAuthenticator:
217
def __init__(self, username: str, password: str): ...
218
219
class GetResult:
220
@property
221
def content_as(self) -> ContentProxy: ...
222
@property
223
def cas(self) -> int: ...
224
225
class MutationResult:
226
@property
227
def cas(self) -> int: ...
228
@property
229
def mutation_token(self) -> MutationToken: ...
230
231
class ContentProxy:
232
def __getitem__(self, t: Type[T]) -> T: ...
233
234
class MutationToken:
235
@property
236
def bucket_name(self) -> str: ...
237
@property
238
def partition_id(self) -> int: ...
239
@property
240
def partition_uuid(self) -> int: ...
241
@property
242
def sequence_number(self) -> int: ...
243
244
enum Durability:
245
NONE = 0
246
MAJORITY = 1
247
MAJORITY_AND_PERSIST_TO_ACTIVE = 2
248
PERSIST_TO_MAJORITY = 3
249
250
enum ServiceType:
251
KV = "kv"
252
QUERY = "n1ql"
253
SEARCH = "fts"
254
ANALYTICS = "cbas"
255
MANAGEMENT = "mgmt"
256
VIEWS = "views"
257
EVENTING = "eventing"
258
259
class CouchbaseException(Exception): ...
260
class DocumentNotFoundException(CouchbaseException): ...
261
class DocumentExistsException(CouchbaseException): ...
262
```