Skip to main content

Document Store Example

This page provides an example of how to create and use a document store using code.

Assume the following credentials for this example:

  • Tenant name is nemo@nautilus.com.
  • User password is xxxxxx.

SDK download


pyC8 requires Python 3.5+. Python 3.6 or higher is recommended

To install pyC8, simply run

$ pip3 install pyC8

or, if you prefer to use conda:

conda install -c conda-forge pyC8

or pipenv:

pipenv install --pre pyC8

Once the installation process is finished, you can begin developing applications in Python.

Connect to GDN

The first step in using GDN is to establish a connection to a region. When this code executes, it initializes the server connection to the *closest region to your location.

from c8 import C8Client

HOST = 'play.paas.macrometa.io'
EMAIL ='nemo@nautilus.com'
PASSWORD = 'xxxxx'
GEOFABRIC = '_system'

print("--- Connecting to C8")

client = C8Client(protocol='https', host=HOST, port=443,
email=EMAIL, password=PASSWORD,
geofabric=GEOFABRIC)

Get GeoFabric Details

To get details of fabric,

from c8 import C8Client

HOST = 'play.paas.macrometa.io'
EMAIL = 'nemo@nautilus.com'
PASSWORD = 'xxxxx'
GEOFABRIC = '_system'

print("--- Connecting to C8")

client = C8Client(protocol='https', host=HOST, port=443,
email=EMAIL, password=PASSWORD,
geofabric=GEOFABRIC)

print("Getting GeoFabric details...")
print(client.get_fabric_details())

Create Collection

We can now create collection in the fabric. To do this, first you connect to fabric and then create a collection called employees.

The below example shows the steps.

from c8 import C8Client

HOST = 'play.paas.macrometa.io'
EMAIL = 'nemo@nautilus.com'
PASSWORD = 'xxxxx'
GEOFABRIC = '_system'
COLLECTION_NAME = 'employees'

print("--- Connecting to C8")

client = C8Client(protocol='https', host=HOST, port=443,
email=EMAIL, password=PASSWORD,
geofabric=GEOFABRIC)

print("Creating collection…")

client.create_collection(name=COLLECTION_NAME, stream=True)

Create Index

Let's add a hash_index called emails to our collection employees. Please refer to reference guide for details on other available index types.

from c8 import C8Client

HOST = 'play.paas.macrometa.io'
EMAIL = 'nemo@nautilus.com'
PASSWORD = 'xxxxx'
GEOFABRIC = '_system'
COLLECTION_NAME = 'employees'
FIELDS = ['email', 'name']

print("--- Connecting to C8")

client = C8Client(protocol='https', host=HOST, port=443,
email=EMAIL, password=PASSWORD,
geofabric=GEOFABRIC)

print("Adding hash index...")

client.add_hash_index(COLLECTION_NAME, fields=FIELDS, unique=False)

Insert Documents

Let's insert documents to the employees collection as shown below.

from c8 import C8Client

HOST = 'play.paas.macrometa.io'
EMAIL = 'nemo@nautilus.com'
PASSWORD = 'xxxxx'
GEOFABRIC = '_system'
COLLECTION_NAME = 'employees'
DOCS = [
{'_key':'James', 'firstname': 'James', 'lastname':'Kirk', 'email':'james.kirk@macrometa.io'},
{'_key': 'Han', 'firstname': 'Han', 'lastname':'Solo', 'email':'han.solo@macrometa.io'},
{'_key': 'Bruce', 'firstname': 'Bruce', 'lastname':'Wayne', 'email':'bruce.wayne@macrometa.io'}
]

print("--- Connecting to C8")

client = C8Client(protocol='https', host=HOST, port=443,
email=EMAIL, password=PASSWORD,
geofabric=GEOFABRIC)

print("Inserting documents...")

client.insert_document(collection_name=COLLECTION_NAME, document=DOCS)

Query documents using C8QL

C8QL is C8's query language. You can execute C8QL query on our newly created collection employees to get its contents.

The query FOR employee IN employees RETURN employee is equivalent to SQL's SELECT query.

from c8 import C8Client

HOST = 'play.paas.macrometa.io'
EMAIL = 'nemo@nautilus.com'
PASSWORD = 'xxxxx'
GEOFABRIC = '_system'
QUERY = 'FOR employee IN employees RETURN employee'

client = C8Client(protocol='https', host=HOST, port=443,
email=EMAIL, password=PASSWORD,
geofabric=GEOFABRIC)

cursor = client.execute_query(QUERY)
docs = [document for document in cursor]
print(f"Response from Query: {docs}")

Get realtime updates

Example for real-time updates from a collection in fabric:

note

Enable the 'Stream' parameter within the collection to get real-time updates.

from c8 import C8Client

HOST = 'play.paas.macrometa.io'
EMAIL = 'nemo@nautilus.com'
PASSWORD = 'xxxxx'
GEOFABRIC = '_system'
COLLECTION_NAME = 'employees'

client = C8Client(protocol='https', host=HOST, port=443,
email=EMAIL, password=PASSWORD,
geofabric=GEOFABRIC)

def callback_fn(event):
print(event)

client.on_change(COLLECTION_NAME, callback=callback_fn)

Query as API

Query as API (aka RESTQL) enables developers to quickly convert saved C8QL queries into geo-distributed REST APIs. This eliminates the need for separate backend servers & containers for CRUD operations.

import time
from c8 import C8Client

HTTP_URL = "play.paas.macrometa.io"
GUEST_MAIL = "nemo@nautilus.com"
GUEST_PASSWORD = "xxxxxx"
GEO_FABRIC = "_system"
COLLECTION_NAME = "person"

VALUE = "INSERT {'firstname':@firstname, 'lastname':@lastname, 'email':@email, 'zipcode':@zipcode, '_key': 'abc'} IN %s" % COLLECTION_NAME
PARAMETER = {"firstname": "", "lastname": "", "email": "", "zipcode": ""}

INSERT_DATA = {"query": {"name": "insertRecord", "parameter": PARAMETER, "value": VALUE}}
GET_DATA = {"query": {"name": "getRecords", "value": "FOR doc IN %s RETURN doc" % COLLECTION_NAME}}
UPDATE_DATA = {"query": {"name": "updateRecord", "value": "UPDATE 'abc' WITH { \"lastname\": \"cena\" } IN %s" % COLLECTION_NAME }}
DELETE_DATA = {"query": {"name": "deleteRecord", "value": "REMOVE 'abc' IN %s" % COLLECTION_NAME}}
GET_COUNT = {"query": {"name": "countRecords", "value": "RETURN COUNT(FOR doc IN %s RETURN 1)" % COLLECTION_NAME}}

if __name__ == '__main__':

print("\n ------- CONNECTION SETUP ------")
print(f"tenant: {GUEST_MAIL}, geofabric:{GEO_FABRIC}")
client = C8Client(protocol='https', host=HTTP_URL, port=443,
email=GUEST_MAIL, password=GUEST_PASSWORD,
geofabric=GEO_FABRIC)

print("\n ------- CREATE GEO-REPLICATED COLLECTION ------")
if client.has_collection(COLLECTION_NAME):
print("Collection exists")
else:
employees = client.create_collection(COLLECTION_NAME, stream=True)
print(f"Created collection: {COLLECTION_NAME}")

print("\n ------- CREATE RESTQLs ------")
client.create_restql(INSERT_DATA) # name: insertRecord
client.create_restql(GET_DATA) # name: getRecords
client.create_restql(UPDATE_DATA) # name: updateRecord
client.create_restql(DELETE_DATA) # name: deleteRecord
client.create_restql(GET_COUNT) # name: countRecords
print(f"Created RESTQLs:{client.get_restqls}")

time.sleep(3)
print("\n ------- EXECUTE RESTQLs ------")
print("Insert data....")
response = client.execute_restql(
"insertRecord",
{"bindVars": {"firstname": "john", "lastname": "doe",
"email": "john.doe@macrometa.io", "zipcode": "511037"}})
print(response)

print("Get data....")
response = client.execute_restql("getRecords")
print(response)

print("Update data....")
response = client.execute_restql("updateRecord")
print(response)

print("Get data....")
response = client.execute_restql("getRecords")
print(response)

print("Count records....")
response = client.execute_restql("countRecords")
print(response)

print("Delete data....")
response = client.execute_restql("deleteRecord")
print(response)

print("\n ------- DELETE RESTQLs ------")
client.delete_restql("insertRecord")
client.delete_restql("getRecords")
client.delete_restql("updateRecord")
client.delete_restql("countRecords")
client.delete_restql("deleteRecord")

print("\n ------- DONE ------")