Library

Volume 2 · Knowledge Graphs

Notebook
Sign in

Section 36

Entity Extraction & Relationship Modeling

730 words · about 3 min

36.1 Entity Extraction Pipeline

Raw Data → NER → Entity Resolution → Relationship Extraction → Graph Ingestion

36.2 NER Approaches

  1. Rule-based — regex patterns, dictionaries, gazetteers. Fast and precise for known patterns (IP addresses, server names, error codes).
  2. Statistical/ML models — spaCy NER, Stanford NER, Flair. Good for standard entity types (Person, Organization, Location).
  3. LLM-based extraction — most accurate for complex, domain-specific entity types; expensive at scale. Use structured output (JSON mode / tool-use schemas) for consistency.
  4. Hybrid — rules for high-confidence patterns + LLM for ambiguous cases; the standard production approach, since it balances cost and accuracy.

Example LLM extraction prompt:

Extract all entities and relationships from the following text.
Output as JSON with this schema:
{
  "entities": [
    {"name": "...", "type": "...", "properties": {...}}
  ],
  "relationships": [
    {"source": "...", "target": "...", "type": "...", "properties": {...}}
  ]
}

Text: "The Order Service (v2.3) depends on the Payment Gateway which
connects to the Stripe API. The service is deployed on Kubernetes cluster
us-east-1 and is owned by Team Alpha."

36.3 Entity Resolution (Deduplication)

  • String similarity — Levenshtein distance, Jaro-Winkler for name matching
  • Embedding similarity — embed entity descriptions, match by cosine similarity
  • Record linkage — probabilistic matching using multiple attributes jointly
  • Canonicalization — map surface-form variations to a single canonical entity (e.g., “Cloud Platform”, “Cloud Platform Inc.” → one node)
from difflib import SequenceMatcher

class EntityResolver:
    def __init__(self, embedding_fn, similarity_threshold: float = 0.85):
        self.embedding_fn = embedding_fn
        self.threshold = similarity_threshold
        self.canonical_entities: dict[str, dict] = {}

    def resolve(self, candidate_name: str, candidate_type: str) -> str:
        """Return the canonical entity ID for a candidate mention."""
        best_match, best_score = None, 0.0
        for entity_id, entity in self.canonical_entities.items():
            if entity["type"] != candidate_type:
                continue
            string_score = SequenceMatcher(None, candidate_name.lower(),
                                            entity["name"].lower()).ratio()
            embed_score = cosine_similarity(
                self.embedding_fn(candidate_name), entity["embedding"])
            combined = 0.4 * string_score + 0.6 * embed_score
            if combined > best_score:
                best_match, best_score = entity_id, combined

        if best_score >= self.threshold:
            return best_match

        new_id = f"{candidate_type}:{len(self.canonical_entities)}"
        self.canonical_entities[new_id] = {
            "name": candidate_name, "type": candidate_type,
            "embedding": self.embedding_fn(candidate_name),
        }
        return new_id

36.4 Relationship Modeling Best Practices

Naming conventions: use verb phrases (DEPENDS_ON, OWNS, RUNS_ON, TRIGGERED_BY); direction matters (ServiceA -[DEPENDS_ON]→ ServiceB); include temporal/confidence properties ({since: "2024-01", confidence: 0.95}).

Common relationship categories for enterprise systems:

Infrastructure:  DEPLOYED_ON, RUNS_IN, CONNECTS_TO, DEPENDS_ON
Organizational:  OWNED_BY, MANAGED_BY, MEMBER_OF
Data Flow:       READS_FROM, WRITES_TO, PUBLISHES, SUBSCRIBES_TO
Incident:        TRIGGERS, CAUSED_BY, RESOLVED_BY, AFFECTED
Temporal:        PRECEDED_BY, FOLLOWED_BY, CONCURRENT_WITH

Relationship properties example:

(OrderService)-[:DEPENDS_ON {
  type: "runtime",
  criticality: "high",
  protocol: "gRPC",
  latency_p99: "45ms",
  discovered_by: "auto-discovery",
  last_verified: "2024-06-01"
}]->(PaymentGateway)

Section 36 — Interview Q&A

Q1: How do you approach entity resolution at scale (100K+ entities) without O(n²) comparisons? Blocking/candidate generation first — bucket entities by a coarse key (type + normalized first token, phonetic code, or embedding-index approximate nearest neighbor) so you only compare within small candidate sets, not the full cross-product. Within a candidate block, combine cheap string similarity (Jaro-Winkler) with embedding cosine similarity as a weighted score, auto-merge above a high-confidence threshold, and route the ambiguous middle band to a manual review queue rather than guessing.

Q2: When do you use rule-based NER vs. LLM-based extraction, and how do you combine them in production? Rule-based extraction for high-precision, well-structured patterns you already understand (IDs, error codes, known naming conventions) — it’s fast, free, and deterministic. LLM-based extraction for ambiguous, free-text, or domain-specific entity types where writing exhaustive rules isn’t tractable. In production, run rules first for anything they reliably catch (cheap, high-confidence), and only send the remainder to the LLM — this hybrid approach controls cost while retaining LLM accuracy where it’s actually needed.

Q3: Why does relationship direction and metadata matter as much as the entity extraction itself? An undirected or metadata-free relationship answers “are these connected” but not “how, how strongly, or since when” — which is usually the actual question a downstream consumer (impact analysis, root-cause tracing, compliance audit) needs answered. Direction determines traversal semantics (e.g., “what depends on X” vs. “what does X depend on” are different queries), and properties like criticality or confidence let you filter noisy or low-confidence edges out of high-stakes queries like blast-radius analysis.