Create rule-based reasoning systems for knowledge graphs that derive new relationships and facts from existing data.
This skill enables comprehensive rule-based inference by defining declarative logic rules that automatically derive new knowledge, validate constraints, and apply business logic to graph data.
Derives new facts from existing patterns using IF-THEN logic.
text
IF (Person)-[WORKS_AT]->(Company)
AND (Person2)-[WORKS_AT]->(Company)
THEN (Person)-[COLLEAGUE_OF]->(Person2)
Properties: Declarative, deterministic, generates new knowledge
Creates transitive or hierarchical relationships.
text
IF (A)-[BORN_IN]->(City)
AND (City)-[LOCATED_IN]->(Country)
THEN (A)-[BORN_IN_COUNTRY]->(Country)
Use: Geographic inference, hierarchies, transitive closure
Validates data and flags violations.
text
IF (Account)-[TRANSFERRED]->(Account)
AND (Account)-[TRANSFERRED]->(Account)
AND (Account)-[TRANSFERRED]->(Account)
THEN Flag(FraudRing, confidence=0.95)
Use: Fraud detection, compliance, data validation
Computes metrics from patterns.
text
IF aggregate(count((Employee)-[WORKS_AT]->(Company)))
THEN Company.employee_count = count
Use: Analytics, metrics, summarization
Applies logic with conditions.
text
IF (Person)-[AGE]->(age)
AND age > 65
THEN (Person)-[STATUS]->(Retired)
Use: Classification, segmentation, categorization
Apply all rules to derive all possible inferences (data-driven).
text
1. Load graph data
2. Find all rule pattern matches
3. Apply THEN inferences
4. Repeat until fixpoint (no new inferences)
Best For: Complete materialization, data warehouse Complexity: May be expensive for large graphs
Query-driven inference - derive facts only when queried.
text
1. Receive query for fact (person)-[COLLEAGUE_OF]->(other)
2. Check if exists in graph
3. If not, try rules with COLLEAGUE_OF as consequence
4. Recursively check rule conditions
Best For: Lazy evaluation, query optimization Complexity: Lower memory, higher query latency
Combine forward and backward chaining.
text
Forward chain core rules → Materialized facts
Backward chain on-demand rules → Query results
Best For: Balanced performance and completeness
text
Rule Name: colleague_inference
Type: derivation
Priority: 100
Condition (IF):
MATCH (person1:Person)-[:WORKS_AT]->(company:Company)
MATCH (person2:Person)-[:WORKS_AT]->(company:Company)
WHERE person1 != person2
Inference (THEN):
CREATE (person1)-[:COLLEAGUE_OF]->(person2)
CREATE (person2)-[:COLLEAGUE_OF]->(person1)
Constraints:
Cycle Detection: true
Materialization: true
Supported patterns:
text
(n) Single node
(n:Label) Node with label
(n {prop: value}) Node with property
(n)-[r]->(m) Relationship
(n)-[r:TYPE]->(m) Typed relationship
(a)-[:TYPE*1..3]->(b) Variable-length path
(a)-[:TYPE1|:TYPE2]->(b) Multiple relationship types
text
WHERE conditions:
n.property = value
n.age > 21
NOT exists(n)-[:EXCLUDES]->(m)
size(n.tags) > 0
Aggregate conditions:
count(nodes) > 10
avg(property) < 50
sum(values) = 100
Extend relationships transitively.
text
IF (a)-[REL]->(b)
AND (b)-[REL]->(c)
THEN (a)-[REL_TRANSITIVE]->(c)
Example: Manager chains, geographic nesting
Combine multiple relationship types.
text
IF (a)-[BORN_IN]->(city)
AND (city)-[LOCATED_IN]->(country)
AND (country)-[PART_OF]->(region)
THEN (a)-[BORN_IN_REGION]->(region)
Derive properties from relationships.
text
IF (person)-[WORKS_AT]->(company)
AND aggregate(count(person)) as count
THEN company.employee_count = count
Apply rules conditionally.
text
IF (person)-[AGE]->(age)
WHERE age >= 65
THEN (person)-[LIFECYCLE_STAGE]->(Retired)
IF (person)-[AGE]->(age)
WHERE age < 25
THEN (person)-[LIFECYCLE_STAGE]->(Junior)
Flag patterns matching suspicious rules.
text
IF (account1)-[TRANSFERRED]->(account2)
AND (account2)-[TRANSFERRED]->(account3)
AND (account3)-[TRANSFERRED]->(account1)
AND NOT EXISTS (account1)-[AUTHORIZED_TRANSFER]->(account3)
THEN Flag(TransferCycle, risk_level=HIGH)
Detect rules that could cause infinite loops.
text
Rule A: IF X THEN Y
Rule B: IF Y THEN X
→ Circular dependency detected!
Create indexes on frequently matched properties.
text
Index on: Person.age, Company.name
Benefit: Faster pattern matching
Execute high-impact, low-cost rules first.
text
Rule Priority:
1. Simple derivations (low cost, high impact)
2. Complex pattern matches (high cost)
3. Constraint checks (validation)
4. Aggregations (expensive computations)
Update inferences only on data changes.
text
On Insert (person)-[WORKS_AT]->(company):
→ Check all rules with WORKS_AT pattern
→ Derive only affected consequences
→ Update materialized views
Compute and store all inferences.
text
Pros: Fast queries, explicit facts
Cons: Storage cost, update latency, staleness
Compute on-demand during queries.
text
Pros: Storage efficient, always current
Cons: Query latency, repeated computation
Materialize important inferences, compute others on-demand.
text
Pros: Balanced approach
Implementation: Tier inferences by importance
Rules with higher priority execute first.
text
Rule A (priority=100): (a)-[R]->(b) THEN (a)-[T]->(b)
Rule B (priority=50): (a)-[R]->(b) THEN (a)-[U]->(b)
→ Rule A executes first
More specific patterns override general ones.
text
General: (a)-[REL]->(b) THEN ...
Specific: (a:Person)-[REL]->(b:Person) THEN ...
→ Specific rule wins for Person nodes
Later rules override earlier ones.
text
v1: IF condition THEN inference1
v2: IF condition THEN inference2 (overrides v1)
IssueCauseSolutionInfinite loopsCircular rulesEnable cycle detection, set depth limitDuplicate inferencesMultiple matching rulesAdd constraints, use prioritiesMemory overflowToo many inferencesLazy materialization, limit scopePerformance degradationComplex patternsIndex optimization, rule reorderingConstraint violationsInvalid inferencesAdd validation, pre-check rulesStale materialized factsData changes not appliedIncremental updates, refresh triggers
✓ Define rules clearly - Use consistent patterns and naming
✓ Avoid circular dependencies - Design acyclic rule sets
✓ Test rules thoroughly - Validate inferences before materialization
✓ Use priorities wisely - Order rules by cost and impact
✓ Index strategically - Index frequently matched properties
✓ Consider materialization - Choose strategy based on query patterns
✓ Document assumptions - Clarify rule semantics and constraints
✓ Monitor performance - Track rule execution times
✓ Version rules - Allow rule evolution and rollback
✓ Validate inferred data - Check quality before use
Combine rules to build complex inference chains.
Support negative conditions (NOT EXISTS).
Generate rules from examples or patterns.
Rules that consider timestamps and time windows.
Rules with confidence scores and uncertainty.
Apply rules spanning multiple graphs or sources.
This skill integrates with:
Drools - Java rule engineProlog - Logic programmingRete - Rule matching algorithmnetworkx - Graph algorithmsregex - Pattern matchingpyparsing - Grammar parsingantlr4-python3-runtime - Parser generatorpyswip - Python-Prolog integrationowlready2 - OWL ontology reasoningrdflib - RDF/SPARQLneo4j - Neo4j driverVersion: 1.0.0