MCPcopy Create free account
hub / github.com/couchbase/couchbase-python-client / main

Function main

examples/couchbase/couchbase_query_operations.py:18–119  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

16
17
18def main():
19 cluster = Cluster.connect('couchbase://localhost',
20 ClusterOptions(PasswordAuthenticator('Administrator', 'password')))
21 bucket = cluster.bucket("travel-sample")
22 collection = bucket.default_collection()
23
24 # basic query
25 try:
26 result = cluster.query(
27 "SELECT * FROM `travel-sample` LIMIT 10;", QueryOptions(metrics=True))
28
29 for row in result.rows():
30 print(f'Found row: {row}')
31
32 metrics = result.metadata().metrics()
33 print(f'Query execution time: {metrics.execution_time()}')
34
35 except ParsingFailedException as ex:
36 import traceback
37 traceback.print_exc()
38
39 # positional params
40 q_str = "SELECT ts.* FROM `travel-sample` ts WHERE ts.`type`=$1 LIMIT 10"
41 result = cluster.query(q_str, "hotel")
42 rows = [r for r in result]
43
44 # positional params via QueryOptions
45 result = cluster.query(q_str, QueryOptions(positional_parameters=["hotel"]))
46 rows = [r for r in result]
47
48 # named params
49 q_str = "SELECT ts.* FROM `travel-sample` ts WHERE ts.`type`=$doc_type LIMIT 10"
50 result = cluster.query(q_str, doc_type='hotel')
51 rows = [r for r in result]
52
53 # name params via QueryOptions
54 result = cluster.query(q_str, QueryOptions(named_parameters={'doc_type': 'hotel'}))
55 rows = [r for r in result]
56
57 # iterate over result/rows
58 q_str = "SELECT ts.* FROM `travel-sample` ts WHERE ts.`type`='airline' LIMIT 10"
59 result = cluster.query(q_str)
60
61 # iterate over rows
62 for row in result:
63 # each row is an serialized JSON object
64 name = row["name"]
65 callsign = row["callsign"]
66 print(f'Airline name: {name}, callsign: {callsign}')
67
68 # query metrics
69 result = cluster.query("SELECT 1=1", QueryOptions(metrics=True))
70 # ignore results
71 result.execute()
72
73 print("Execution time: {}".format(
74 result.metadata().metrics().execution_time()))
75

Callers 1

Calls 15

ClusterOptionsClass · 0.90
QueryOptionsClass · 0.90
MutationStateClass · 0.90
connectMethod · 0.45
bucketMethod · 0.45
default_collectionMethod · 0.45
queryMethod · 0.45
rowsMethod · 0.45
metricsMethod · 0.45
metadataMethod · 0.45
execution_timeMethod · 0.45

Tested by

no test coverage detected