-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsubdocument_ops.py
More file actions
298 lines (250 loc) · 10.5 KB
/
subdocument_ops.py
File metadata and controls
298 lines (250 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
from couchbase.durability import (Durability,
ServerDurability,
ClientDurability,
ReplicateTo,
PersistTo)
from couchbase.exceptions import (CASMismatchException,
CouchbaseException,
DocumentExistsException,
DocumentUnretrievableException,
PathExistsException,
PathNotFoundException,
SubdocCantInsertValueException,
SubdocPathMismatchException)
from couchbase.cluster import Cluster
from couchbase.auth import PasswordAuthenticator
import couchbase.subdocument as SD
from couchbase.options import ClusterOptions, MutateInOptions
cluster = Cluster.connect('couchbase://your-ip',
ClusterOptions(PasswordAuthenticator('Administrator',
'password')))
bucket = cluster.bucket('travel-sample')
collection = bucket.default_collection()
json_doc = {
'name': 'Douglas Reynholm',
'email': 'douglas@reynholmindustries.com',
'addresses': {
'billing': {
'line1': '123 Any Street',
'line2': 'Anytown',
'country': 'United Kingdom'
},
'delivery': {
'line1': '123 Any Street',
'line2': 'Anytown',
'country': 'United Kingdom'
}
},
'purchases': {
'complete': [
339, 976, 442, 666
],
'abandoned': [
157, 42, 999
]
}
}
try:
collection.insert('customer123', json_doc)
except DocumentExistsException:
collection.remove('customer123')
collection.insert('customer123', json_doc)
# tag::lookup_in[]
result = collection.lookup_in('customer123',
[SD.get('addresses.delivery.country')])
country = result.content_as[str](0) # 'United Kingdom'
# end::lookup_in[]
print(country)
# fixed in v. 3.1.0; prior to 3.1. result.exists(index)
# would throw an exception if the path did not exist
# tag::lookup_in_exists[]
result = collection.lookup_in('customer123', [SD.exists('purchases.pending[-1]')])
print(f'Path exists: {result.exists(0)}.')
# Path exists: False.
# end::lookup_in_exists[]
# NOTE: result.content_as[bool](1) would return False
# this is b/c when checking if a path exists
# no content is returned and None evaluates to False
try:
print('Path exists {}.'.format(result.content_as[bool](0)))
except PathNotFoundException:
print('Path does not exist')
# tag::lookup_in_multi[]
result = collection.lookup_in('customer123',[SD.get('addresses.delivery.country'),
SD.exists('purchases.complete[-1]')])
print('{0}'.format(result.content_as[str](0)))
print('Path exists: {}.'.format(result.exists(1)))
# path exists: True.
# end::lookup_in_multi[]
# tag::mutate_in_upsert[]
collection.mutate_in('customer123', [SD.upsert('fax', '311-555-0151')])
# end::mutate_in_upsert[]
# tag::mutate_in_insert[]
collection.mutate_in('customer123', [SD.insert('purchases.pending', [42, True, 'None'])])
try:
collection.mutate_in('customer123', [SD.insert('purchases.complete',[42, True, 'None'])])
except PathExistsException:
print('Path exists, cannot use insert.')
# end::mutate_in_insert[]
# tag::combine_dict[]
collection.mutate_in('customer123',(SD.remove('addresses.billing'),
SD.replace('email','dougr96@hotmail.com')))
# end::combine_dict[]
# NOTE: the mutate_in() operation expects a tuple or list
# tag::array_append[]
collection.mutate_in('customer123', (SD.array_append('purchases.complete', 777),))
# purchases.complete is now [339, 976, 442, 666, 777]
# end::array_append[]
# tag::array_prepend[]
collection.mutate_in('customer123', [SD.array_prepend('purchases.abandoned', 18)])
# purchases.abandoned is now [18, 157, 42, 999]
# end::array_prepend[]
# tag::create_array[]
collection.upsert('my_array', [])
collection.mutate_in('my_array', [SD.array_append('', 'some element')])
# the document my_array is now ['some element']
# end::create_array[]
# tag::add_multi[]
collection.mutate_in('my_array', [SD.array_append('', 'elem1', 'elem2', 'elem3')])
# the document my_array is now ['some_element', 'elem1', 'elem2', 'elem3']
# end::add_multi[]
# tag::add_nested_array[]
collection.mutate_in('my_array', [SD.array_append('', ['elem4', 'elem5', 'elem6'])])
# the document my_array is now ['some_element', 'elem1', 'elem2', 'elem3',
# ['elem4', 'elem5', 'elem6']]]
# end::add_nested_array[]
# tag::add_multi_slow[]
collection.mutate_in('my_array', (SD.array_append('', 'elem7'),
SD.array_append('', 'elem8'),
SD.array_append('', 'elem9')))
# end::add_multi_slow[]
# tag::create_parents_array[]
collection.upsert('some_doc', {})
collection.mutate_in('some_doc', [SD.array_prepend('some.array',
'Hello',
'World',
create_parents=True)])
# end::create_parents_array[]
# tag::array_addunique[]
try:
collection.mutate_in('customer123', [SD.array_addunique('purchases.complete', 95)])
print('Success!')
except PathExistsException:
print('Path already exists.')
try:
collection.mutate_in('customer123', [SD.array_addunique('purchases.complete', 95)])
print('Success!')
except PathExistsException:
print('Path already exists.')
# end::array_addunique[]
# cannot add JSON obj w/ array_addunique
try:
collection.mutate_in('customer123', [SD.array_addunique('purchases.complete',
{'new': 'object'})])
except SubdocCantInsertValueException:
print('Cannot add JSON value w/ array_addunique.')
# cannot add JSON obj w/ array_addunique
collection.mutate_in('customer123', [SD.upsert('purchases.cancelled',
[{'Date': 'Some date'}])])
try:
collection.mutate_in('customer123', [SD.array_addunique('purchases.cancelled', 89)])
except SubdocPathMismatchException:
print('Cannot use array_addunique if array contains JSON objs.')
# tag::array_insert[]
collection.upsert('array', [])
collection.mutate_in('array', [SD.array_append('', 'hello', 'world')])
collection.mutate_in('array', [SD.array_insert('[1]', 'cruel')])
# end::array_insert[]
# exception raised if attempt to insert in out of bounds position
try:
collection.mutate_in('array', [SD.array_insert('[6]', '!')])
except PathNotFoundException:
print('Cannot insert to out of bounds index.')
# can insert into nested arrays as long as the path is appropriate
collection.mutate_in('array', [SD.array_append('', ['another', 'array'])])
collection.mutate_in('array', [SD.array_insert('[3][2]', '!')])
# tag::counter1[]
result = collection.mutate_in('customer123', (SD.counter('logins', 1),))
num_logins = collection.get('customer123').content_as[dict]['logins']
print(f'Number of logins: {num_logins}.')
# Number of logins: 1.
# end::counter1[]
# tag::counter2[]
player_key = 'player432'
collection.upsert(player_key, {'gold': 1000})
collection.mutate_in(player_key, (SD.counter('gold', -150),))
result = collection.lookup_in(player_key, (SD.get('gold'),))
print(f'{player_key} has {result.content_as[int](0)} gold remaining.')
# player432 has 850 gold remaining.
# end::counter2[]
# tag::create_parents[]
collection.mutate_in('customer123', [SD.upsert('level_0.level_1.foo.bar.phone',
dict(
num='311-555-0101',
ext=16
), create_parents=True)])
# end::create_parents[]
# tag::cas1[]
collection.mutate_in('customer123', [SD.array_append('purchases.complete', 998)])
# end::cas1[]
# tag::cas2[]
collection.mutate_in('customer123', [SD.array_append('purchases.complete', 999)])
# end::cas2[]
try:
# tag::cas3[]
collection.mutate_in('customer123',
[SD.array_append('purchases.complete', 999)],
MutateInOptions(cas=1234))
# end::cas3[]
except (DocumentExistsException, CASMismatchException) as ex:
# we expect an exception here as the CAS value is chosen
# for example purposes
print(ex)
try:
# tag::obs_durability[]
collection.mutate_in('key',
[SD.insert('username', 'dreynholm')],
MutateInOptions(durability=ClientDurability(ReplicateTo.ONE,
PersistTo.ONE)))
# end::obs_durability[]
except CouchbaseException as ex:
print('Need to have more than 1 node for durability')
print(ex)
try:
# tag::durability[]
collection.mutate_in('customer123',
[SD.insert('username', 'dreynholm')],
MutateInOptions(durability=ServerDurability(Durability.MAJORITY)))
# end::durability[]
except CouchbaseException as ex:
print('Need to have more than 1 node for durability')
print(ex)
# tag::lookup_in_any_replica[]
try:
result = collection.lookup_in_any_replica('customer123',
[SD.get('addresses.delivery.country')])
country = result.content_as[str](0) # 'United Kingdom'
print(f'Country={country}')
print(f'Is result replica={result.is_replica}')
except PathNotFoundException as ex:
print(('The version of the document on the server node '
'that responded quickest did not have the requested '
'field.'))
print(f'Exception={ex}')
except DocumentUnretrievableException as ex:
print('Document not present on any server node.')
print(f'Exception={ex}')
# end::lookup_in_any_replica[]
# tag::lookup_in_all_replicas[]
result = collection.lookup_in_all_replicas('customer123',
[SD.get('addresses.delivery.country')])
for res in result:
try:
country = res.content_as[str](0) # 'United Kingdom'
print(f'Country={country}')
print(f'Is result replica={res.is_replica}')
except PathNotFoundException as ex:
print(('The version of the document on one of the server nodes '
'did not have the requested field.'))
print(f'Exception={ex}')
# end::lookup_in_all_replicas[]