GUN is a graph database, which means it stores data as interconnected nodes and edges rather than in rigid tables or document hierarchies. This fundamental design choice enables GUN to handle complex relationships, circular references, and flexible data structures that would be difficult or impossible in traditional SQL or NoSQL databases.
Every piece of data in GUN is stored as a node. You reference nodes using .get():
var gun = Gun();// Store data at a nodegun.get('mark').put({ name: "Mark", email: "[email protected]",});// Read data from a nodegun.get('mark').on((data, key) => { console.log("User data:", data); // Output: {name: "Mark", email: "[email protected]"}});
Nodes can reference other nodes, creating edges in the graph:
// Create nodesgun.get('alice').put({name: 'Alice'});gun.get('bob').put({name: 'Bob'});// Create an edge from alice to bobgun.get('alice').get('friend').put(gun.get('bob'));// Traverse the edgegun.get('alice').get('friend').get('name').once(name => { console.log("Alice's friend is:", name); // "Bob"});
GUN provides sets to create unordered collections:
// Add items to a list/setgun.get('list').set({name: 'Apple', type: 'fruit'});gun.get('list').set({name: 'Carrot', type: 'vegetable'});gun.get('list').set(gun.get('mark')); // Add reference to existing node// Iterate over the setgun.get('list').map().once(function(item){ console.log("Item:", item);});
Sets in GUN are unordered. If you need ordered data, store an index or timestamp as part of your data structure.
{ id: "alice", name: "Alice", friends: ["bob", "charlie"] // IDs only, need separate lookups}
GUN Graph Approach:
// Direct relationships, no joins neededgun.get('alice').get('friends').set(gun.get('bob'));gun.get('alice').get('friends').set(gun.get('charlie'));// Traverse naturallygun.get('alice').get('friends').map().get('name').on(console.log);
From the GUN benchmarks, the graph engine can handle:
20M+ ops/sec for read operations
Native handling of circular references with no performance penalty
Efficient memory usage through reference sharing
GUN’s graph structure means nodes are stored once in memory, even if referenced from multiple places. This is more efficient than duplicating data in traditional databases.