Advanced Knowledge Graph Query Patterns
User Intent
Operation
Prerequisites
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({
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({
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
2. Path Finding
3. Community Detection
4. Centrality Metrics
5. Temporal Patterns
Common Patterns
Developer Hints
Last updated