Working with Graphs

Overview

Globally distributed applications need a geo distributed fast data platform that can transparently replicate the data anywhere in the world to enable the applications to operate on a copy of the data that's close to its users. Similarly the applications need geo-replicated and local streams to handle pub-sub, ETL and real-time updates from the fast data platform.

Macrometa GDN is a fully managed geo-distributed data service with turnkey global distribution and transparent multi-master replication. You can run globally distributed, low-latency workloads within GDN. This article is an introduction to working with graphs in GDN with pyC8 and jsC8 drivers.

In the drivers, a document is a dictionary/object that is JSON serializable with the following properties:

  • Contains the _key field, which identifies the document uniquely within a specific collection.
  • Contains the _id field (also called the handle), which identifies the document uniquely across all collections within a fabric. This ID is a combination of the collection name and the document key using the format {collection}/{key} (see example below).
  • Contains the _rev field. GDN supports MVCC (Multiple Version Concurrency Control) and is capable of storing each document in multiple revisions. Latest revision of a document is indicated by this field. The field is populated by GDN and is not required as input unless you want to validate a document against its current revision.

Here is an example of a valid document:

    {
        '_id': 'students/bruce',
        '_key': 'bruce',
        '_rev': '_Wm3dzEi--_',
        'first_name': 'Bruce',
        'last_name': 'Wayne',
        'address': {
            'street' : '1007 Mountain Dr.',
            'city': 'Gotham',
            'state': 'NJ'
        },
        'is_rich': True,
        'friends': ['robin', 'gordon']
    }

Edge documents (edges) are similar to standard documents but with two additional required fields _from and _to. Values of these fields must be the handles of "from" and "to" vertex documents linked by the edge document in question. Here is an example of a valid edge document:

    {
        '_id': 'friends/001',
        '_key': '001',
        '_rev': '_Wm3dyle--_',
        '_from': 'students/john',
        '_to': 'students/jane',
        'closeness': 9.5
    }

A Graph consists of vertices and edges. Edges are stored as documents in edge collections. A vertex can be a document of a document collection or of an edge collection (so edges can be used as vertices). Which collections are used within a named graph is defined via edge definitions. A named graph can contain more than one edge definition, at least one is needed. Graphs allow you to structure your models in line with your domain and group them logically in collections and giving you the power to query them in the same graph queries.

In SQL you commonly have the construct of a relation table to store n:m relations between two data tables. An edge collection is somewhat similar to these relation tables. Vertex collections resemble the data tables with the objects to connect.

While simple graph queries with fixed number of hops via the relation table may be doable in SQL with several nested joins, graph databases can handle an arbitrary number of these hops over edge collections - this is called traversal. Also edges in one edge collection may point to several vertex collections. Its common to have attributes attached to edges, i.e. a label naming this interconnection.

Edges have a direction, with their relations _from and _to pointing from one document to another document stored in vertex collections. In queries you can define in which directions the edge relations may be followed i.e.,

  • OUTBOUND: _from_to
  • INBOUND: _from_to
  • ANY: _from_to.

Note

If you are new to Macrometa GDN, we strongly recommend reading Essentials of Macrometa GDN.

Pre-requisite

Let's assume your

  • Tenant name is guest@macrometa.io and
  • User password is guest.

Driver 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.

With Yarn or NPM

    yarn add jsc8
    (or)
    npm install jsc8

If you want to use the driver outside of the current directory, you can also install it globally using the `--global` flag:

    npm install --global jsc8

From source,

    git clone https://github.com/macrometacorp/jsc8.git
    cd jsC8
    npm install
    npm run dist

Connect to GDN

The first step in using GDN is to establish a connection to a local region. When this code executes, it initializes the server connection to the region URL you sepcified.

from c8 import C8Client

print("Connect to C8...")
client = C8Client(protocol='https', host='gdn1.macrometa.io', port=443)
const jsc8 = require("jsc8")
client = new jsc8("https://gdn1.macrometa.io"); 

Get GeoFabric Details

To get details of fabric,

from c8 import C8Client
client = C8Client(protocol='https', host='gdn1.macrometa.io', port=443)

demotenant = client.tenant(email='guest@macrometa.io', password='guest')
print("Get geo fabric...")
fabric = demotenant.useFabric('_system')
print("Get geo fabric details...")
print(fabric.fabrics_detail())
const jsc8 = require("jsc8")

const client = new jsc8("https://gdn1.macrometa.io");

async function getFabric() {
    await console.log("Logging in...");
    await client.login("guest@macrometa.io", "guest");
    await console.log("Using the demotenant...");  
    client.useTenant("guest");

    try{
      await console.log("Using the fabric");
      client.useFabric("_system")

      await console.log("Getting the fabric details...");
      let result = await client.get();

      await console.log("result is: ", result)
    } catch(e){
      await console.log("Fabric details could not be fetched because "+ e)
    }
}

getFabric();

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
client = C8Client(protocol='https', host='gdn1.macrometa.io', port=443)

demotenant = client.tenant(email='guest@macrometa.io', password='guest')
print("Get geo fabric...")
fabric = demotenant.useFabric('_system')
employees = fabric.create_collection('employees') # Create a new collection named "employees".
const jsc8 = require("jsc8")

const client = new jsc8("https://gdn1.macrometa.io");

async function createColl() {
    await console.log("Logging in...");
    await client.login("guest@macrometa.io", "guest");
    await console.log("Using the tenant...");  
    client.useTenant("guest");

    try{
      await console.log("Using the Fabric...");  
      client.useFabric("_system")
      console.log(`Creating the edge collection`);
      let employeecoll = client.collection("employees")
      let exists_coll = await employeecoll.exists()
      if (exists_coll === false) {
            await callscollection.create()

        }
    } catch(e){
      await console.log("Collection could not be created because "+ e)
    }
}

createColl();

Create Edge Collection

An edge collection contains edge documents and shares its namespace with all other types of collections. You can manage edge documents via standard collection API wrappers, but using edge collection API wrappers provides additional safeguards:

  • All modifications are executed in transactions.
  • Edge documents are checked against the edge definitions on insert.

from c8 import C8Client

# Initialize the C8 Data Fabric client.
client = C8Client(protocol='https', host='gdn1.macrometa.io', port=443)

# Connect to "test" fabric as tenant admin.
demotenant = client.tenant(email="guest@macrometa.io", password='guest')
fabric = demotenant.useFabric("_system")


# Get the API wrapper for graph "school".
school = fabric.graph('school')


if fabric.has_graph('school'):
    school = fabric.graph('school')
else:
    school = fabric.create_graph('school')

if school.has_vertex_collection('lectures'):
        lectures = school.vertex_collection('lectures')
else:
    lectures = school.create_vertex_collection('lectures')
# The "_id" field is required instead of "_key" field (except for insert).
school.insert_vertex('lectures', {'_key': 'CSC101'})
school.update_vertex({'_id': 'lectures/CSC101', 'difficulty': 'easy'})
school.replace_vertex({'_id': 'lectures/CSC101', 'difficulty': 'hard'})
school.has_vertex('lectures/CSC101')
school.vertex('lectures/CSC101')

if school.has_vertex_collection('teachers'):
        teachers = school.vertex_collection('teachers')
else:
    teachers = school.create_vertex_collection('teachers')
# List vertex collections in the graph.
school.vertex_collections()
# Vertex collections have similar interface as standard collections.
teachers.insert({'_key': 'jon', 'name': 'Jon'})
teachers.update({'_key': 'jon', 'age': 35})
teachers.replace({'_key': 'jon', 'name': 'Jon', 'age': 36})


# Get the API wrapper for edge collection "teach".
if school.has_edge_definition('teach'):
    teach = school.edge_collection('teach')
else:
    teach = school.create_edge_definition(
        edge_collection='teach',
        from_vertex_collections=['teachers'],
        to_vertex_collections=['lectures']
    )

# Edge collections have a similar interface as standard collections.
teach.insert({
    '_key': 'jon-CSC101',
    '_from': 'teachers/jon',
    '_to': 'lectures/CSC101'
})
teach.replace({
    '_key': 'jon-CSC101',
    '_from': 'teachers/jon',
    '_to': 'lectures/CSC101',
    'online': False
})
teach.update({
    '_key': 'jon-CSC101',
    'online': True
})
teach.has('jon-CSC101')
teach.get('jon-CSC101')
teach.delete('jon-CSC101')

# Create an edge between two vertices (essentially the same as insert).
teach.link('teachers/jon', 'lectures/CSC101', data={'online': False})

# List edges going in/out of a vertex.
teach.edges('teachers/jon', direction='in')
teach.edges('teachers/jon', direction='out')
const jsc8 = require("jsc8")

const client = new jsc8("https://gdn1.macrometa.io");

async function createEdgeColl() {
    await console.log("Logging in...");
    await client.login("guest@macrometa.io", "guest");
    await console.log("Using the tenant...");  
    client.useTenant("guest");

    try{
      await console.log("Using the Fabric...");  
      client.useFabric("_system")
      console.log(`Creating the edge collection`);
      callscollection = client.edgeCollection("edgeCollection")
      exists_coll = await callscollection.exists()
      if (exists_coll === false) {
            await callscollection.create({waitForSync: true})

        }
    } catch(e){
      await console.log("Edge Collection could not be created because "+ e)
    }
}

createEdgeColl();

You can manage edges via graph API wrappers also, but you must use document IDs instead of keys where applicable.

Insert Documents

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

from c8 import C8Client
client = C8Client(protocol='https', host='gdn1.macrometa.io', port=443)

demotenant = client.tenant(email='guest@macrometa.io', password='guest')
print("Get geo fabric...")
fabric = demotenant.useFabric('_system')
employees = fabric.create_collection('employees') # Create a new collection named "employees".

# insert documents into the collection
employees.insert({'_key':'Jean', 'firstname': 'Jean', 'lastname':'Picard', 'email':'jean.picard@macrometa.io'})
employees.insert({'_key':'James', 'firstname': 'James', 'lastname':'Kirk', 'email':'james.kirk@macrometa.io'})
employees.insert({'_key': 'Han', 'firstname': 'Han', 'lastname':'Solo', 'email':'han.solo@macrometa.io'})
employees.insert({'_key': 'Bruce', 'firstname': 'Bruce', 'lastname':'Wayne', 'email':'bruce.wayne@macrometa.io'})
const jsc8 = require("jsc8")

const client = new jsc8("https://gdn1.macrometa.io");

async function insertDoc() {
    await console.log("Logging in...");
    await client.login("guest@macrometa.io", "guest");
    await console.log("Using the tenant...");  
    client.useTenant("guest");

    try{
      await console.log("Using the Fabric...");  
      client.useFabric("_system")
      console.log(`Creating the edge collection`);
      empcollection = client.collection("employees")
      await empcollection.save({ firstname: 'Jean', lastname: 'Picard' });
      await empcollection.save({ firstname: 'Bruce', lastname: 'Wayne' });
    } catch(e){
      await console.log("Document could not be inserted because "+ e)
    }
}

insertDoc();

Create Graph

A graph consists of vertices and edges. Vertices are stored as documents in vertex collections and edges stored as documents in edge collections. The collections used in a graph and their relations are specified with edge definitions.

from c8 import C8Client

# Initialize the C8 Data Fabric client.
client = C8Client(protocol='https', host='gdn1.macrometa.io', port=443)

# For the "mytenant" tenant, connect to "test" fabric as tenant admin.
# This returns an API wrapper for the "test" fabric on tenant 'mytenant'
# Note that the 'mytenant' tenant should already exist.
tenant = client.tenant(email="guest@macrometa.io", password='guest')
fabric = tenant.useFabric("_system")



# List existing graphs in the fabric.
fabric.graphs()

# Create a new graph named "school" if it does not already exist.
# This returns an API wrapper for "school" graph.
if fabric.has_graph('school'):
    school = fabric.graph('school')
else:
    school = fabric.create_graph('school')
const jsc8 = require("jsc8")

const client = new jsc8("https://gdn1.macrometa.io");
async function createGraph(){
    await console.log("Logging in...");
    await client.login("guest@macrometa.io", "guest");
    await console.log("Using the tenant...");  
    client.useTenant("guest");
    const graph = client.graph('some-graph');
    const info = await graph.create({
        edgeDefinitions: [{
            collection: 'edges',
            from: ['start-vertices'],
            to: ['end-vertices']
        }]
        });
}

createGraph();

Graph Traversals

A graph consists of vertices and edges. Vertices are stored as documents in vertex collections and edges stored as documents in edge collections. The collections used in a graph and their relations are specified with edge definitions.

from c8 import C8Client
import pprint

# Variables - Queries
global_url = "gdn1.macrometa.io"
email = "guest@macrometa.io"
password = "guest"
geo_fabric = "_system"
collection_people = "CDRpeople"
collection_calls = "CDRcalls"
collection_cellsites = "CDRcellsites"
collection_graph = "CDRgraphdocs"
read_people = "FOR person IN CDRpeople RETURN person"
read_calls = "FOR call IN CDRcalls RETURN call"
person = "Lou Feaveer"
graph_traversal1 = "FOR c IN CDRpeople FILTER c.full_name == \"{}\" FOR v IN 1..1 INBOUND c CDRcalls RETURN v".format(person)
graph_traversal2 = "FOR c IN CDRpeople FILTER c.full_name == \"{}\" FOR v IN 1..1 OUTBOUND c CDRcalls RETURN v".format(person)

pp = pprint.PrettyPrinter(indent=4)

# Initialize the C8 Data Fabric client.
# Step1: Open connection to GDN. You will be routed to closest region.
print("1. CONNECT: federation: {},  user: {}".format(global_url, email))
client = C8Client(protocol='https', host='gdn1.macrometa.io', port=443)

# For the "mytenant" tenant, connect to "test" fabric as tenant admin.
# This returns an API wrapper for the "test" fabric on tenant 'mytenant'
# Note that the 'mytenant' tenant should already exist.
tenant = client.tenant(email="guest@macrometa.io", password="guest")
fabric = tenant.useFabric('_system')


# Step2: Create collections if not exists
print("2a. CREATE_PEOPLE_VERTEX_COLLECTION: region: {},  collection: {}".format(global_url, collection_people))
if fabric.has_collection(collection_people):
    peopleCol = fabric.collection(collection_people)
else:
    peopleCol = fabric.create_collection(collection_people)

print("2b. CREATE_CALLS_EDGE_COLLECTION: region: {},  collection: {}".format(global_url, collection_calls))
if fabric.has_collection(collection_calls):
    callsCol = fabric.collection(collection_calls)
else:
    callsCol = fabric.create_collection(collection_calls, edge=True)

# Step3: Insert data into collections.
print("3a. INSERT_PEOPLE_DATA: region: {}, collection: {}".format(global_url, collection_people))

# insert documents into the collection
docs = [
  {
    "full_name": "Kiel Dummer",
    "first_name": "Kiel",
    "last_name": "Dummer",
    "city": "Burbank",
    "state": "CA",
    "address": "40317 5th Crossing",
    "calling_nbr": "757-697-9065",
    "_key": "757-697-9065"
  },
  {
    "full_name": "Pernell Winspare",
    "first_name": "Pernell",
    "last_name": "Winspare",
    "city": "San Diego",
    "state": "CA",
    "address": "596 Packers Pass",
    "calling_nbr": "718-208-8096",
    "_key": "718-208-8096"
  },
  {
    "full_name": "Ava Kermath",
    "first_name": "Ava",
    "last_name": "Kermath",
    "city": "Berkeley",
    "state": "CA",
    "address": "2 Doe Crossing Junction",
    "calling_nbr": "765-623-5328",
    "_key": "765-623-5328"
  },
  {
    "full_name": "Tremain McGrah",
    "first_name": "Tremain",
    "last_name": "McGrah",
    "city": "Torrance",
    "state": "CA",
    "address": "079 Russell Street",
    "calling_nbr": "859-783-3227",
    "_key": "859-783-3227"
  },
  {
    "full_name": "Vidovik Boddam",
    "first_name": "Vidovik",
    "last_name": "Boddam",
    "city": "Los Angeles",
    "state": "CA",
    "address": "3 Brentwood Crossing",
    "calling_nbr": "703-265-1313",
    "_key": "703-265-1313"
  },
  {
    "full_name": "Oralie Goward",
    "first_name": "Oralie",
    "last_name": "Goward",
    "city": "Los Angeles",
    "state": "CA",
    "address": "922 Columbus Park",
    "calling_nbr": "617-815-8610",
    "_key": "617-815-8610"
  },
  {
    "full_name": "Lou Feaveer",
    "first_name": "Lou",
    "last_name": "Feaveer",
    "city": "San Jose",
    "state": "CA",
    "address": "55223 Hooker Crossing",
    "calling_nbr": "716-463-8993",
    "_key": "716-463-8993"
  },
  {
    "full_name": "Peria King",
    "first_name": "Peria",
    "last_name": "King",
    "city": "Stockton",
    "state": "CA",
    "address": "8 Troy Plaza",
    "calling_nbr": "713-707-8699",
    "_key": "713-707-8699"
  }
]
peopleCol.insert_many(docs)

print("3a. INSERT_CALL_RECORDS_DATA: region: {}, collection: {}".format(global_url, collection_calls))
docs = [
        {
    "calling_nbr": "757-697-9065",
    "called_nbr": "716-463-8993",
    "_from": "CDRpeople/757-697-9065",
    "_to": "CDRpeople/716-463-8993",
    "call_date": "1/4/2020",
    "call_time": "13:33",
    "call_duration": 30,
    "cell_site": 4044703906
  },
  {
    "calling_nbr": "716-463-8993",
    "called_nbr": "713-707-8699",
    "_from": "CDRpeople/716-463-8993",
    "_to": "CDRpeople/713-707-8699",
    "call_date": "1/28/2020",
    "call_time": "3:02",
    "call_duration": 18,
    "cell_site": 2289973823
  },
  {
    "calling_nbr": "765-623-5328",
    "called_nbr": "713-707-8699",
    "_from": "CDRpeople/765-623-5328",
    "_to": "CDRpeople/713-707-8699",
    "call_date": "1/28/2020",
    "call_time": "3:02",
    "call_duration": 18,
    "cell_site": 2289973823
  }
    ]
callsCol.insert_many(docs)

#Step4: Create a graph
print("4. CREATE_GRAPH...CDRgraph")
graph = fabric.create_graph(collection_graph)
register = graph.create_edge_definition(
        edge_collection=collection_calls,
        from_vertex_collections=[collection_people],
        to_vertex_collections=[collection_people]
    )

# Step5: Read Data
print("5a. GRAPH_TRAVERSAL: Find outbound calls TO: {}".format(person))
cursor = fabric.c8ql.execute(graph_traversal1)
docs = [document for document in cursor]
pp.pprint(docs)
print("5b. GRAPH_TRAVERSAL: Find inbound calls FROM: {}".format(person))
cursor = fabric.c8ql.execute(graph_traversal2)
docs = [document for document in cursor]
pp.pprint(docs)

# Step6: Delete Data
print("6. DELETE_DATA...")
#callsCol.truncate()
#peopleCol.truncate()
fabric.delete_graph(name=collection_graph, drop_collections=False)
const jsc8 = require('jsc8')

// Variables - DB
const global_url = "https://gdn1.macrometa.io"

const client = new jsc8(global_url)
const guest_password = "guest"
const geo_fabric = "_system"
const guest_email = "guest@macrometa.io"
const collection_people = "CDRpeople"
const collection_calls = "CDRcalls"
const collection_cellsites = "CDRcellsites"
const collection_graph = "CDRgraphdocs"
const person = "Lou Feaveer"
let peoplecollection = null
let callscollection = null
let graphcollection = null

let datalist = []


// Variables - Queries
const read_people = "FOR person IN CDRpeople RETURN person"
const read_calls = "FOR call IN CDRcalls RETURN call"
const graph_traversal1 = `FOR c IN CDRpeople FILTER c.full_name == \"${person}\" FOR v IN 1..1 INBOUND c CDRcalls RETURN v`
const graph_traversal2 = `FOR c IN CDRpeople FILTER c.full_name == \"${person}\" FOR v IN 1..1 OUTBOUND c CDRcalls RETURN v`

async function login(){
  console.log(`\n 1. CONNECT: federation: ${global_url}`);
  await client.login(guest_email, guest_password);
  await client.useFabric(geo_fabric);
}


async function createCollection() {

  console.log("\n 2. CREATE_COLLECTION")

  try{
     console.log(`Creating the collection ${collection_people}...`);
      peoplecollection = client.collection(collection_people)
      let exists_coll = await peoplecollection.exists()
      if (exists_coll === false) {
            await peoplecollection.create()

        }

      console.log(`Creating the collection ${collection_people}...`);
      callscollection = client.edgeCollection(collection_calls)
      exists_coll = await callscollection.exists()
      if (exists_coll === false) {
            await callscollection.create({waitForSync: true})

        }

      }
    catch (e) {
    await console.log("Collection creation did not succeed due to " + e)
    }
    }

    async function insertData() {

    console.log(`\n 3a. INSERT_PEOPLE_DATA in region ${global_url}`)
    let people_data =[
  {
    "full_name": "Kiel Dummer",
    "first_name": "Kiel",
    "last_name": "Dummer",
    "city": "Burbank",
    "state": "CA",
    "address": "40317 5th Crossing",
    "calling_nbr": "757-697-9065",
    "_key": "757-697-9065"
  },
  {
    "full_name": "Pernell Winspare",
    "first_name": "Pernell",
    "last_name": "Winspare",
    "city": "San Diego",
    "state": "CA",
    "address": "596 Packers Pass",
    "calling_nbr": "718-208-8096",
    "_key": "718-208-8096"
  },
  {
    "full_name": "Ava Kermath",
    "first_name": "Ava",
    "last_name": "Kermath",
    "city": "Berkeley",
    "state": "CA",
    "address": "2 Doe Crossing Junction",
    "calling_nbr": "765-623-5328",
    "_key": "765-623-5328"
  },
  {
    "full_name": "Tremain McGrah",
    "first_name": "Tremain",
    "last_name": "McGrah",
    "city": "Torrance",
    "state": "CA",
    "address": "079 Russell Street",
    "calling_nbr": "859-783-3227",
    "_key": "859-783-3227"
  },
  {
    "full_name": "Vidovik Boddam",
    "first_name": "Vidovik",
    "last_name": "Boddam",
    "city": "Los Angeles",
    "state": "CA",
    "address": "3 Brentwood Crossing",
    "calling_nbr": "703-265-1313",
    "_key": "703-265-1313"
  },
  {
    "full_name": "Oralie Goward",
    "first_name": "Oralie",
    "last_name": "Goward",
    "city": "Los Angeles",
    "state": "CA",
    "address": "922 Columbus Park",
    "calling_nbr": "617-815-8610",
    "_key": "617-815-8610"
  },
  {
    "full_name": "Lou Feaveer",
    "first_name": "Lou",
    "last_name": "Feaveer",
    "city": "San Jose",
    "state": "CA",
    "address": "55223 Hooker Crossing",
    "calling_nbr": "716-463-8993",
    "_key": "716-463-8993"
  },
  {
    "full_name": "Peria King",
    "first_name": "Peria",
    "last_name": "King",
    "city": "Stockton",
    "state": "CA",
    "address": "8 Troy Plaza",
    "calling_nbr": "713-707-8699",
    "_key": "713-707-8699"
  }
]
    await peoplecollection.save(people_data)
    peoplecollection.closeOnChangeConnection()

    console.log(`\n 3a. INSERT_CALL_RECORDS_DATA in region ${global_url}`)
    let callsdata = [
        {
    "calling_nbr": "757-697-9065",
    "called_nbr": "716-463-8993",
    "_from": "CDRpeople/757-697-9065",
    "_to": "CDRpeople/716-463-8993",
    "call_date": "1/4/2020",
    "call_time": "13:33",
    "call_duration": 30,
    "cell_site": 4044703906
  },
  {
    "calling_nbr": "716-463-8993",
    "called_nbr": "713-707-8699",
    "_from": "CDRpeople/716-463-8993",
    "_to": "CDRpeople/713-707-8699",
    "call_date": "1/28/2020",
    "call_time": "3:02",
    "call_duration": 18,
    "cell_site": 2289973823
  },
  {
    "calling_nbr": "765-623-5328",
    "called_nbr": "713-707-8699",
    "_from": "CDRpeople/765-623-5328",
    "_to": "CDRpeople/713-707-8699",
    "call_date": "1/28/2020",
    "call_time": "3:02",
    "call_duration": 18,
    "cell_site": 2289973823
  }
    ]
    await callscollection.save(callsdata)
    callscollection.closeOnChangeConnection()

    }

async function createGraph(){
  console.log(`\n 4. CREATE_GRAPH region ${global_url}`)

  graphcollection = client.graph(collection_graph)
  await graphcollection.create({
  edgeDefinitions: [{
    collection: collection_calls,
    from: [collection_people],
    to: [collection_people]
  }]
});
}


async function readData(){
  console.log(`5a. GRAPH_TRAVERSAL: Find outbound calls TO: ${person}`)
  let cursor = await client.query(graph_traversal1);
  let result = await cursor.all()
  console.log(result)

  console.log(`5b. GRAPH_TRAVERSAL: Find inbound calls FROM: ${person}`)
  cursor = await client.query(graph_traversal2);
  result = await cursor.all()
  console.log(result)

}



async function deleteData(){
  console.log("\ 6. DELETE_DATA")
  await graphcollection.drop()
  await peoplecollection.truncate()
  await callscollection.truncate()
}


(async function(){
  await login();
  await createCollection();
  await insertData();
  await createGraph();
  await readData();
  await deleteData();

})();

Outbound Traversal

# Step4: Read Data
print("4a. GRAPH_TRAVERSAL: Find outbound calls TO: {}".format(person))
cursor = fabric.c8ql.execute(graph_traversal1)
docs = [document for document in cursor]
pp.pprint(docs)
console.log(`5a. GRAPH_TRAVERSAL: Find outbound calls TO: ${person}`)
  let cursor = await client.query(graph_traversal1);
  let result = await cursor.all()
  console.log(result)

Inbound Traversal

print("4b. GRAPH_TRAVERSAL: Find inbound calls FROM: {}".format(person))
cursor = fabric.c8ql.execute(graph_traversal2)
docs = [document for document in cursor]
pp.pprint(docs)
  console.log(`5b. GRAPH_TRAVERSAL: Find inbound calls FROM: ${person}`)
  cursor = await client.query(graph_traversal2);
  result = await cursor.all()
  console.log(result)

Delete Graph

from c8 import C8Client

# Initialize the C8 Data Fabric client.
client = C8Client(protocol='https', host='gdn1.macrometa.io', port=443)

# For the "mytenant" tenant, connect to "test" fabric as tenant admin.
# This returns an API wrapper for the "test" fabric on tenant 'mytenant'
# Note that the 'mytenant' tenant should already exist.
tenant = client.tenant(email="guest@macrometa.io", password="guest")
fabric = tenant.useFabric('_system')

# This returns an API wrapper for "school" graph and deletes the graph
fabric.graph('school').delete()
const jsc8 = require("jsc8")

const client = new jsc8("https://gdn1.macrometa.io");
async function DeleteGraph(){
    await console.log("Logging in...");
    await client.login("guest@macrometa.io", "guest");
    await console.log("Using the tenant...");  
    client.useTenant("guest");
    const graph = client.graph('some-graph');
    await graph.drop();
}

DeleteGraph();
Top