0
# View Operations
1
2
Traditional MapReduce view queries for data indexing and querying. Views provide a way to create secondary indexes on document data using JavaScript MapReduce functions, offering compatibility with legacy Couchbase applications.
3
4
## Capabilities
5
6
### View Query Execution
7
8
Execute queries against MapReduce views defined in design documents.
9
10
```python { .api }
11
class Bucket:
12
def view_query(self, design_doc: str, view_name: str, options: ViewOptions = None) -> ViewResult:
13
"""
14
Execute a view query.
15
16
Args:
17
design_doc (str): Name of the design document
18
view_name (str): Name of the view within the design document
19
options (ViewOptions, optional): Query options
20
21
Returns:
22
ViewResult: Query results with rows and metadata
23
24
Raises:
25
ViewException: If view execution fails
26
DesignDocumentNotFoundException: If design document not found
27
"""
28
```
29
30
### View Query Options
31
32
Configure view query execution parameters including keys, ranges, and result formatting.
33
34
```python { .api }
35
class ViewOptions:
36
def __init__(self):
37
"""Create view query options."""
38
39
def key(self, key: Any) -> ViewOptions:
40
"""Query documents with specific key."""
41
42
def keys(self, keys: List[Any]) -> ViewOptions:
43
"""Query documents with specific keys."""
44
45
def start_key(self, start_key: Any) -> ViewOptions:
46
"""Set start key for range queries."""
47
48
def end_key(self, end_key: Any) -> ViewOptions:
49
"""Set end key for range queries."""
50
51
def start_key_doc_id(self, doc_id: str) -> ViewOptions:
52
"""Set start document ID for pagination."""
53
54
def end_key_doc_id(self, doc_id: str) -> ViewOptions:
55
"""Set end document ID for pagination."""
56
57
def inclusive_end(self, inclusive: bool) -> ViewOptions:
58
"""Include end key in results."""
59
60
def skip(self, skip: int) -> ViewOptions:
61
"""Skip number of results."""
62
63
def limit(self, limit: int) -> ViewOptions:
64
"""Limit number of results."""
65
66
def scan_consistency(self, consistency: ViewScanConsistency) -> ViewOptions:
67
"""Set scan consistency level."""
68
69
def reduce(self, reduce: bool) -> ViewOptions:
70
"""Enable/disable reduce function."""
71
72
def group(self, group: bool) -> ViewOptions:
73
"""Enable/disable grouping."""
74
75
def group_level(self, level: int) -> ViewOptions:
76
"""Set grouping level."""
77
78
def descending(self, descending: bool) -> ViewOptions:
79
"""Sort results in descending order."""
80
81
def development(self, development: bool) -> ViewOptions:
82
"""Query development or production views."""
83
84
def debug(self, debug: bool) -> ViewOptions:
85
"""Enable debug mode."""
86
87
def timeout(self, timeout: timedelta) -> ViewOptions:
88
"""Set query timeout."""
89
```
90
91
### View Results
92
93
Process view query results including individual rows and metadata.
94
95
```python { .api }
96
class ViewResult:
97
def __iter__(self) -> Iterator[ViewRow]:
98
"""Iterate over view result rows."""
99
100
def rows(self) -> List[ViewRow]:
101
"""Get all result rows."""
102
103
def metadata(self) -> ViewMetaData:
104
"""Get query metadata."""
105
106
class ViewRow:
107
@property
108
def id(self) -> Optional[str]:
109
"""Document ID."""
110
111
@property
112
def key(self) -> Any:
113
"""View key."""
114
115
@property
116
def value(self) -> Any:
117
"""View value."""
118
119
@property
120
def document(self) -> Optional[dict]:
121
"""Full document (if include_docs=True)."""
122
123
class ViewMetaData:
124
@property
125
def total_rows(self) -> int:
126
"""Total number of rows in view."""
127
128
@property
129
def debug_info(self) -> Optional[dict]:
130
"""Debug information (if debug=True)."""
131
```
132
133
### View Index Management
134
135
Manage design documents containing view definitions.
136
137
```python { .api }
138
class ViewIndexManager:
139
def get_design_document(self, design_doc_name: str, namespace: DesignDocumentNamespace = None,
140
options: GetDesignDocumentOptions = None) -> DesignDocument:
141
"""
142
Retrieve a design document.
143
144
Args:
145
design_doc_name (str): Name of the design document
146
namespace (DesignDocumentNamespace, optional): Development or production namespace
147
options (GetDesignDocumentOptions, optional): Additional options
148
149
Returns:
150
DesignDocument: The design document definition
151
152
Raises:
153
DesignDocumentNotFoundException: If design document not found
154
"""
155
156
def get_all_design_documents(self, namespace: DesignDocumentNamespace = None,
157
options: GetAllDesignDocumentsOptions = None) -> List[DesignDocument]:
158
"""Get all design documents."""
159
160
def upsert_design_document(self, design_doc: DesignDocument, namespace: DesignDocumentNamespace = None,
161
options: UpsertDesignDocumentOptions = None) -> None:
162
"""Create or update a design document."""
163
164
def drop_design_document(self, design_doc_name: str, namespace: DesignDocumentNamespace = None,
165
options: DropDesignDocumentOptions = None) -> None:
166
"""Delete a design document."""
167
168
def publish_design_document(self, design_doc_name: str, options: PublishDesignDocumentOptions = None) -> None:
169
"""Publish a design document from development to production."""
170
```
171
172
### Design Documents
173
174
Define MapReduce views within design documents.
175
176
```python { .api }
177
class DesignDocument:
178
def __init__(self, name: str, views: Dict[str, View] = None):
179
"""
180
Create a design document.
181
182
Args:
183
name (str): Design document name
184
views (dict, optional): Dictionary of view name to View objects
185
"""
186
187
@property
188
def name(self) -> str:
189
"""Design document name."""
190
191
@property
192
def views(self) -> Dict[str, View]:
193
"""Dictionary of views in this design document."""
194
195
class View:
196
def __init__(self, map_function: str, reduce_function: str = None):
197
"""
198
Create a view definition.
199
200
Args:
201
map_function (str): JavaScript map function
202
reduce_function (str, optional): JavaScript reduce function
203
"""
204
205
@property
206
def map(self) -> str:
207
"""JavaScript map function."""
208
209
@property
210
def reduce(self) -> Optional[str]:
211
"""JavaScript reduce function."""
212
213
enum DesignDocumentNamespace:
214
DEVELOPMENT = "dev"
215
PRODUCTION = "prod"
216
217
enum ViewScanConsistency:
218
NOT_BOUNDED = "ok"
219
REQUEST_PLUS = "false"
220
UPDATE_AFTER = "update_after"
221
```
222
223
## Usage Examples
224
225
### Basic View Query
226
227
```python
228
from couchbase.cluster import Cluster
229
from couchbase.auth import PasswordAuthenticator
230
from couchbase.options import ClusterOptions, ViewOptions
231
232
# Connect to cluster
233
auth = PasswordAuthenticator("username", "password")
234
cluster = Cluster("couchbase://localhost", ClusterOptions(auth))
235
bucket = cluster.bucket("travel-sample")
236
237
# Query a view
238
view_options = ViewOptions()
239
view_options.limit(10)
240
view_options.descending(True)
241
242
result = bucket.view_query("travel", "by_country", view_options)
243
244
# Process results
245
for row in result:
246
print(f"Key: {row.key}, Value: {row.value}, Document ID: {row.id}")
247
248
# Get metadata
249
metadata = result.metadata()
250
print(f"Total rows: {metadata.total_rows}")
251
```
252
253
### View Query with Key Range
254
255
```python
256
from couchbase.options import ViewOptions
257
258
# Query views within a key range
259
view_options = ViewOptions()
260
view_options.start_key("A")
261
view_options.end_key("C")
262
view_options.inclusive_end(False)
263
264
result = bucket.view_query("travel", "by_country", view_options)
265
266
for row in result:
267
print(f"Country: {row.key}, Count: {row.value}")
268
```
269
270
### Creating and Managing Design Documents
271
272
```python
273
from couchbase.management.views import View, DesignDocument, DesignDocumentNamespace
274
275
# Create a view definition
276
map_function = """
277
function(doc, meta) {
278
if (doc.type === "hotel" && doc.country) {
279
emit(doc.country, 1);
280
}
281
}
282
"""
283
284
reduce_function = "_count"
285
286
# Create design document
287
view = View(map_function, reduce_function)
288
design_doc = DesignDocument("hotels", {"by_country": view})
289
290
# Get view index manager
291
view_mgr = bucket.view_indexes()
292
293
# Create design document in development namespace
294
view_mgr.upsert_design_document(design_doc, DesignDocumentNamespace.DEVELOPMENT)
295
296
# Test the view in development
297
dev_options = ViewOptions()
298
dev_options.development(True)
299
dev_options.limit(5)
300
301
result = bucket.view_query("hotels", "by_country", dev_options)
302
for row in result:
303
print(f"Development - Country: {row.key}, Count: {row.value}")
304
305
# Publish to production when ready
306
view_mgr.publish_design_document("hotels")
307
```