Skip to content

Commit

Permalink
DML (UPDATE/DELETE)
Browse files Browse the repository at this point in the history
  • Loading branch information
mnunberg committed Dec 9, 2015
1 parent c4a4594 commit 9d34c9d
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,18 @@ Python |
Go |
node.js

### Query - UPDATE and DELETE

Show how these statements can be used to modify existing documents using
secondary document attributes. Also show how a single document can be
modified via the `USE KEYS` clause.

C |
[Python](python/n1ql-update-delete.py)
| .NET |
Go |
node.js

### CAS Handling - Using CAS for concurrent mutations
This example will demonstrate concurrent mutations with and without using the
CAS value. Without using the CAS value, some modifications may end up getting
Expand Down
68 changes: 68 additions & 0 deletions python/n1ql-update-delete.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#!/usr/bin/env python
from couchbase.bucket import Bucket
from couchbase.n1ql import N1QLQuery

cb = Bucket('couchbase://localhost/default')

# Create a set of 'product' documents
docs = {
'bundt_cake_pan1': {
'type': 'product',
'name': 'Bundt Cake Pan',
'price': 7.35,
'categories': ['kitchen', 'home']
},
'led_4d_900in_tv1': {
'type': 'product',
'name': '4D 900" LED TV',
'price': 1250000.99,
'categories': ['technology', 'electronics']
},
'light_bulb_40w_led': {
'type': 'product',
'name': '40-Watt LED Bulb',
'price': 4.40,
'categories': ['electronics', 'home']
},
'red_puff_parka3': {
'type': 'product',
'name': 'Parka (red)',
'price': 54.99,
'categories': ['clothing']
},
'utilikilt1_speaker': {
'type': 'product',
'name': 'Utilikilt with Bluetooth Speaker in Rear',
'price': 124.95,
'categories': ['clothing', 'electronics', 'technology']
}
}

# Delete any prior products so we start with a clean dataset
meta = cb.n1ql_query(
N1QLQuery('DELETE from default WHERE type=$1', 'product')
).execute().meta
print 'Deleted {0} items!'.format(meta['metrics'].get('mutationCount', 0))

# Everything's 25% off!
cb.upsert_multi(docs)
query = N1QLQuery(
'UPDATE default '
'SET sale_price=ROUND(price-(price * 0.25), 2) '
'WHERE type=$1'
'RETURNING name, price, sale_price',
'product'
)
for row in cb.n1ql_query(query):
print '{0} WAS: {1:2}. NOW ONLY {2:2}'.format(
row['name'], row['price'], row['sale_price'])

# Show how we can update a single document by its ID
query = N1QLQuery(
'UPDATE default USE KEYS $keys SET description=$desc',
keys=['utilikilt1_speaker'],
desc='Use this handy utilikilt as a fashion accessory or in the garage, and lets '
)
cb.n1ql_query(query).execute()
# Show the new value
print cb.get('utilikilt1_speaker').value['description']

0 comments on commit 9d34c9d

Please sign in to comment.