relate()

Create typed relationships between entities in your knowledge graph.

Signature

brain.relate(options: RelateOptions): Promise<string>

Parameters

Property Type Required Description
from string Yes Source entity ID
to string Yes Target entity ID
type string | VerbType Yes Relationship type
metadata object No Additional properties on the relationship

Returns

A Promise that resolves to the relationship ID (string).

Examples

Basic Relationship

basic-relate.js
// Create entities first
const ts = await brain.add({ data: "TypeScript" })
const js = await brain.add({ data: "JavaScript" })

// Create relationship
const relationId = await brain.relate({
  from: ts,
  to: js,
  type: "extends"
})

console.log(relationId) // "rel_abc123..."

Using VerbType Enum

verb-types.js
import { Brainy, VerbType } from '@soulcraft/brainy'

// Use built-in verb types
await brain.relate({
  from: authorId,
  to: bookId,
  type: VerbType.Creates
})

await brain.relate({
  from: chapterId,
  to: bookId,
  type: VerbType.PartOf
})

await brain.relate({
  from: packageId,
  to: dependencyId,
  type: VerbType.DependsOn
})

Relationship with Metadata

relation-metadata.js
// Add properties to the relationship itself
await brain.relate({
  from: userId,
  to: projectId,
  type: "contributesTo",
  metadata: {
    role: "maintainer",
    since: "2023-01-15",
    commits: 150
  }
})

// Employment relationship with dates
await brain.relate({
  from: employeeId,
  to: companyId,
  type: "worksAt",
  metadata: {
    startDate: "2022-03-01",
    department: "Engineering",
    title: "Senior Developer"
  }
})

Building a Graph

build-graph.js
// Add entities
const react = await brain.add({ data: "React" })
const vue = await brain.add({ data: "Vue.js" })
const angular = await brain.add({ data: "Angular" })
const js = await brain.add({ data: "JavaScript" })
const meta = await brain.add({ data: "Meta" })
const google = await brain.add({ data: "Google" })

// Build relationships
await brain.relate({ from: react, to: js, type: "uses" })
await brain.relate({ from: vue, to: js, type: "uses" })
await brain.relate({ from: angular, to: js, type: "uses" })
await brain.relate({ from: meta, to: react, type: "creates" })
await brain.relate({ from: google, to: angular, type: "creates" })

// Query the graph
const jsFrameworks = await brain.find({
  connected: { to: js, type: "uses" }
})

Bidirectional Relationships

bidirectional.js
// Relationships are directional
// For bidirectional, create both directions

// Symmetric relationship
await brain.relate({ from: alice, to: bob, type: "knows" })
await brain.relate({ from: bob, to: alice, type: "knows" })

// Or use semantic inverses
await brain.relate({ from: parent, to: child, type: "parentOf" })
await brain.relate({ from: child, to: parent, type: "childOf" })

Notes

See Also

Next: update() →