Advanced Knowledge Graph Query Patterns

User Intent

"What are advanced patterns for querying my knowledge graph? Show me graph traversal, subgraph extraction, and complex relationship queries."

Operation

SDK Methods: queryObservables(), queryContents(), queryGraph() (if available) GraphQL: Complex graph queries with filters Entity: Advanced observable query patterns

Prerequisites

  • Knowledge graph with extracted entities

  • Understanding of relationship queries

  • Familiarity with graph concepts


Complete Code Example (TypeScript)

import { Graphlit } from 'graphlit-client';
import { ObservableTypes, EntityState } from 'graphlit-client/dist/generated/graphql-types';

const graphlit = new Graphlit();

console.log('=== Advanced Graph Query Patterns ===\n');

// Pattern 1: Subgraph Extraction (N-hop neighborhood)
console.log('Pattern 1: Extract 2-Hop Subgraph\n');

async function extractSubgraph(
  entityId: string,
  depth: number = 2
): Promise<{ nodes: any[]; edges: any[] }> {
  const nodes = new Map();
  const edges: any[] = [];
  const visited = new Set<string>();
  
  async function traverse(id: string, currentDepth: number) {
    if (currentDepth > depth || visited.has(id)) return;
    visited.add(id);
    
    const content = await graphlit.queryContents({
      filter: {
        observations: [{ observable: { id } }]
      }
    });
    
    content.contents.results.forEach(item => {
      item.observations?.forEach(obs => {
        nodes.set(obs.observable.id, obs.observable);
        if (obs.observable.id !== id) {
          edges.push({ from: id, to: obs.observable.id });
        }
        
        if (currentDepth < depth) {
          traverse(obs.observable.id, currentDepth + 1);
        }
      });
    });
  }
  
  await traverse(entityId, 0);
  
  return {
    nodes: Array.from(nodes.values()),
    edges
  };
}

const subgraph = await extractSubgraph('entity-id-here', 2);
console.log(`Subgraph: ${subgraph.nodes.length} nodes, ${subgraph.edges.length} edges\n`);

// Pattern 2: Centrality Calculation (most connected entities)
console.log('Pattern 2: Entity Centrality\n');

async function calculateCentrality(
  entityType: ObservableTypes
): Promise<Array<{ name: string; degree: number }>> {
  const entities = await graphlit.queryObservables({
    filter: { types: [entityType] }
  });
  
  const centrality: Array<{ name: string; degree: number }> = [];
  
  for (const entity of entities.observables.results.slice(0, 20)) {  // Limit for demo
    const content = await graphlit.queryContents({
      filter: {
        observations: [{ observable: { id: entity.observable.id } }]
      }
    });
    
    // Count unique connected entities
    const connected = new Set<string>();
    content.contents.results.forEach(item => {
      item.observations?.forEach(obs => {
        if (obs.observable.id !== entity.observable.id) {
          connected.add(obs.observable.id);
        }
      });
    });
    
    centrality.push({
      name: entity.observable.name,
      degree: connected.size
    });
  }
  
  return centrality.sort((a, b) => b.degree - a.degree);
}

const topEntities = await calculateCentrality(ObservableTypes.Person);
console.log('Most connected people:');
topEntities.slice(0, 5).forEach((e, i) => {
  console.log(`${i + 1}. ${e.name}: ${e.degree} connections`);
});

console.log('\n✓ Advanced graph queries complete!');

Key Patterns

1. Subgraph Extraction

Extract neighborhood around entity:

  • N-hop traversal

  • Collect nodes and edges

  • Export for visualization

2. Path Finding

Find shortest path between entities:

  • Breadth-first search

  • Limited depth

  • Return path as array

3. Community Detection

Find clusters of related entities:

  • Co-occurrence analysis

  • Connected components

  • Group by relationships

4. Centrality Metrics

Rank entities by importance:

  • Degree centrality (connection count)

  • Betweenness centrality (bridge entities)

  • PageRank-style scoring

5. Temporal Patterns

Analyze graph changes over time:

  • First/last entity mentions

  • Relationship formation timeline

  • Entity lifecycle tracking


Common Patterns

Ego Network: Extract all entities connected to one entity Star Schema: Find entities of type B connected to entity A Triangle Closure: Find mutual connections (A-B, B-C, A-C) Weak Links: Find rarely co-occurring entities Strong Links: Find frequently co-occurring entities


Developer Hints

  • Cache content queries to avoid repeated API calls

  • Limit graph traversal depth (max 3 hops)

  • Use pagination for large result sets

  • Parallelize independent queries

  • Export to graph visualization tools (D3.js, Cytoscape)


Last updated

Was this helpful?