Skip to content
  1. Tutorials
  2. Getting started

Working with graph data

Ogma exposes an API to access and modify its internal graph. Those functions use nodes and edges in the Node, Edge, NodeList and EdgeList formats.

Creating nodes and edges

Let's add some nodes and edges to the graph. Note that nodes have to be added before edges. When adding or deleting many nodes or edges (more than 1,000) it is more performant to use the batch functions (e.g. ogma.addNodes()) than their individual counterparts (e.g. ogma.addNode()).

js
// Manually create nodes
ogma.addNodes([
  { id: 'john', data: { name: 'John Doe', age: 55 } },
  { id: 'jane', data: { name: 'Jane Doe', age: 55 } },
  { id: 'john_jr', data: { name: 'John Doe Jr', age: 15 } },
  { id: 'jane_jr', data: { name: 'Jane Doe Jr', age: 18 } }
]);

ogma.addEdges([
  { id: 'e1', source: 'john_jr', target: 'jane', data: { name: 'parent' } },
  { id: 'e2', source: 'jane_jr', target: 'jane', data: { name: 'parent' } },
  { id: 'e3', source: 'john', target: 'jane', data: { name: 'spouse' } }
]);

Creating nodes and edges

Accessing nodes and edges

The functions ogma.getNode() and ogma.getNodes() (resp. ogma.getEdge() and ogma.getEdges()) retrieve nodes (resp. edges) from Ogma's internal graph. These functions can be chained to traverse the graph and collect the nodes that match certain criteria.

js
// Get node by id.
// nJohnJr is a Node object.
const nodeJohnJr = ogma.getNode('john_jr');

// Get nodes by id.
// parents is a NodeList object.
const parents = ogma.getNodes(['john', 'jane']);

// Get all edges
// addEdges is an EdgeList object.
const addEdges = ogma.getEdges();

// Get the children of Jane
const neighbors = ogma
  .getNode('jane')
  .getAdjacentEdges()
  .filter(edge => edge.getData('name') === 'parent')
  .getSource();

Custom data

Edges and nodes can also store custom data (in the data property). Custom data can be retrieved with the function ogma.getData(propertyName)available for Node, Edge, NodeList and EdgeList objects. Let's retrieve the nodes that match a specific condition, then print their names to the console.

js
// Store all nodes with an age property above 50 in an NodeList object.
const youngsters = ogma.getNodes().filter(node => node.getData('age') > 50);

console.log(youngsters.getData('name').join(', '));