Skip to main content

REST API: Graph & Relationships

Knowledge graph traversal and relationship management in the Trix REST API.

Overview

Trix organizes memories in a knowledge graph, allowing you to create meaningful connections between related information. The Graph API enables you to create relationships, traverse connections, and extract contextual subgraphs.

Relationships are automatically created when memories reference each other. Use the explicit API when you need fine-grained control over the graph structure.

Managing Relationships

Create Relationship

Create a directed relationship between two memories with an optional type and weight:

create-relationship.sh
curl -X POST "https://api.trixdb.com/v1/relationships/mem_abc123" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "target_id": "mem_xyz789",
    "relationship_type": "related_to",
    "weight": 0.85,
    "metadata": {
      "reason": "User explicitly connected these topics",
      "created_by": "user_action"
    }
  }'

Relationship Types

The full enum is defined in trix-api/src/lib/constants.js (RELATIONSHIP_TYPES). Custom strings outside the enum are rejected by the API schema.

TypeDescriptionBidirectional
related_toGeneral semantic relationshipYes
parent_of / child_ofHierarchical containmentInverse pair
supersedesUpdated/replaced informationNo
references / cites / quotes / paraphrases / summarizesCitation-style links (ADR-031)No
derived_fromMemory was derived from sourceNo
contradicts / supportsConflicting vs corroborating informationYes
similar_toSemantic similarity linkYes
depends_on / caused_by / leads_toCausal / dependency linksNo
blocks / blocked_by / requires / required_by / implements / implemented_byTask-style relationships (inverse pairs)Inverse pair

List Relationships

Get all relationships for a memory:

list-relationships.sh
curl -X GET "https://api.trixdb.com/v1/relationships/mem_abc123?direction=both&type=related_to" \
  -H "Authorization: Bearer YOUR_API_KEY"

# Response
{
  "relationships": [
    {
      "id": "rel_001",
      "source_id": "mem_abc123",
      "target_id": "mem_xyz789",
      "relationship_type": "related_to",
      "weight": 0.85,
      "direction": "outgoing",
      "metadata": {},
      "created_at": "2024-01-15T10:30:00Z"
    }
  ],
  "total": 2
}

Query Parameters

ParameterTypeDescription
directionstringincoming, outgoing, or both (default)
typestringFilter by relationship type
min_weightnumberMinimum relationship weight (0-1)
include_memoriesbooleanInclude full memory objects
limitintegerMax results (default: 50, max: 200)

Delete Relationship

delete-relationship.sh
curl -X DELETE "https://api.trixdb.com/v1/relationships/mem_abc123/mem_xyz789" \
  -H "Authorization: Bearer YOUR_API_KEY"

# Delete specific relationship type only
curl -X DELETE "https://api.trixdb.com/v1/relationships/mem_abc123/mem_xyz789?type=related_to" \
  -H "Authorization: Bearer YOUR_API_KEY"

Graph Traversal

Traverse the knowledge graph to discover connected memories across multiple hops. This is useful for building context, finding related topics, or exploring knowledge domains.

Multi-Hop Traversal

traverse.sh
curl -X POST "https://api.trixdb.com/v1/graph/traverse" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "start_ids": ["mem_abc123"],
    "depth": 3,
    "max_nodes": 50,
    "relationship_types": ["related_to", "derived_from"],
    "min_weight": 0.5,
    "direction": "outgoing"
  }'

# Response
{
  "nodes": [
    { "id": "mem_abc123", "depth": 0, "content": "Machine learning fundamentals", "tags": ["ml", "ai"] },
    { "id": "mem_xyz789", "depth": 1, "content": "Neural network architectures", "tags": ["ml", "deep-learning"] },
    { "id": "mem_def456", "depth": 2, "content": "Transformer models explained", "tags": ["transformers", "nlp"] }
  ],
  "edges": [
    { "source": "mem_abc123", "target": "mem_xyz789", "relationship_type": "related_to", "weight": 0.92 },
    { "source": "mem_xyz789", "target": "mem_def456", "relationship_type": "derived_from", "weight": 0.88 }
  ],
  "paths": [["mem_abc123", "mem_xyz789", "mem_def456"]]
}

Traversal Options

ParameterTypeDefaultDescription
start_idsstring[]requiredStarting memory IDs
depthinteger2Maximum traversal depth (1-5)
max_nodesinteger100Maximum nodes to return
relationship_typesstring[]allFilter by relationship types
min_weightnumber0Minimum edge weight
directionstringbothincoming, outgoing, both

Context Extraction

Extract a contextual subgraph around specific memories, perfect for providing relevant context to LLMs or building focused knowledge views.

context.sh
curl -X POST "https://api.trixdb.com/v1/graph/context" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "machine learning fundamentals",
    "depth": 2,
    "semantic_limit": 20,
    "semantic_threshold": 0.6,
    "relationship_types": ["related_to", "derived_from"],
    "max_nodes": 50
  }'

# Response
{
  "context": {
    "primary_memories": [...],
    "related_memories": [...]
  },
  "graph": {
    "nodes": [...],
    "edges": [...]
  }
}

Context Options

ParameterTypeDescription
querystringSearch query for context extraction (required)
depthintegerGraph traversal depth
semantic_limitintegerMax memories to include from semantic search
semantic_thresholdnumberMin semantic similarity score (0-1)
relationship_typesstring[]Filter by relationship types
max_nodesintegerMaximum nodes to return

Path Finding

Find the shortest or strongest paths between memories in the knowledge graph.

paths.sh
curl -X POST "https://api.trixdb.com/v1/graph/path" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "source_id": "mem_abc123",
    "target_id": "mem_xyz789",
    "max_paths": 3,
    "max_length": 5,
    "algorithm": "weighted_shortest"
  }'

# Response
{
  "paths": [
    {
      "nodes": ["mem_abc123", "mem_mid1", "mem_xyz789"],
      "length": 2,
      "total_weight": 1.75,
      "edges": [
        { "source": "mem_abc123", "target": "mem_mid1", "weight": 0.9 },
        { "source": "mem_mid1", "target": "mem_xyz789", "weight": 0.85 }
      ]
    }
  ],
  "direct_connection": false
}

Path Algorithms

AlgorithmDescription
shortestFewest hops between nodes
weighted_shortestHighest total edge weight
allAll paths up to max_length

Code Examples

Build Knowledge Context for LLM

const searchResult = await fetch(
  'https://api.trixdb.com/v1/memories?q=user+preferences',
  { headers: { 'Authorization': `Bearer ${apiKey}` } }
).then(r => r.json());

const memoryId = searchResult.memories[0].id;

const context = await fetch('https://api.trixdb.com/v1/graph/context', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    memory_ids: [memoryId],
    context_size: 15,
    relevance_threshold: 0.7
  })
}).then(r => r.json());

const contextText = context.context.related_memories
  .map(m => m.content)
  .join('\n');

Create Relationship Chain

async function createChain(memoryIds: string[], type: string) {
  for (let i = 0; i < memoryIds.length - 1; i++) {
    await fetch(`https://api.trixdb.com/v1/relationships/${memoryIds[i]}`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        target_id: memoryIds[i + 1],
        relationship_type: type,
        weight: 0.9 - (i * 0.05)
      })
    });
  }
}

await createChain(['mem_001', 'mem_002', 'mem_003'], 'derived_from');

Endpoints Reference

MethodEndpointDescription
POST/relationships/:memoryIdCreate relationship from memory
GET/relationships/:memoryIdList memory relationships
DELETE/relationships/:memoryId/:targetIdDelete relationship
POST/graph/traverseMulti-hop graph traversal
POST/graph/contextExtract contextual subgraph
POST/graph/pathFind paths between memories