Skip to content
OntologyL_Cypher 2.0: Unified Chain Language for Ontology Orchestration

OntologyL_Cypher 2.0: Unified Chain Language for Ontology Orchestration

OntologyL_Cypher 2.0 is a domain-specific chain language that unifies ontology object manipulation, business data retrieval, spatiotemporal reasoning, OWL constraint validation, inference chaining, and write-back actions into a single readable, executable, and auditable expression, integrating with relational and graph databases while providing deterministic execution and LLM-friendly syntax.

AI Large-Model Wave and Transformation Guide
AI Large-Model Wave and Transformation Guide
AI Large-Model Wave and Transformation Guide

Overview

OntologyL_Cypher 2.0 (OLC) is the dedicated graph-object chain language of the OntoL-Manage project. It acts as a coordination layer in the ontology world, unifying what to query, which path to traverse, what data to fetch, how to judge by spatiotemporal and OWL rules, where to write results, and why the conclusion holds — all in one chainable expression.

Boundary and Source of Truth

The article serves as an overview of the "World-Class Dynamic Ontology Coordination Language" and does not invent a second syntax. The single sources of truth for each aspect are:

Syntax specification: business/ontoL_languages_dsl/README.md Method registry (names, arity, terminal states, condition availability): method_registry.py Chain-head, method-chain, parameter parsing: core/chain_parser.py Chain evaluation and execution dispatch: execute.py Condition decidability validation: condition_validator.py Cypher mapping: cypher-mapping.md Unified language execution contract:

language-execution-contract.md

What It Is: Four-Layer Architecture

OLC compresses four capabilities into a single chain:

Ontology Semantic Layer : Responsible for entities, feature ontologies, relations, shared parameters, self parameters. Not responsible for deciding which node the reasoner runs first.

Language Layer : Responsible for chain head, selectors, method chain, JSON parameters, AND/OR. Not responsible for directly concatenating Cypher/SQL.

Execution Layer : Responsible for Cypher pushdown, Python evaluation, external data sources, MCP, write-back. Not responsible for rewriting business conclusions.

Governance Layer : Responsible for condition/execution boundaries, fail-fast, Chinese semantics, per-method trace, replica isolation. Not responsible for skipping approval or writing to the formal graph.

It explicitly does not : decide reasoning order (still driven by the reasoner), mechanically translate every method to Cypher (only safe pushdown), replace Text2SQL fallback, or allow data fetching, graph writes, or side effects in condition fields.

Nine Unified Roles

Unified query + reasoning expression : Node/relation filtering, traversal, aggregation, plus temporal, spatial, OWL constraints, and chain reasoning — business rules no longer scattered across SQL, Python, frontend, and verbal agreements.

Unified data fetch + write-back entry : First-level entities use db_sim, db_query, func, mcp for base data; chain tail write_param() publishes to ontoL_action_param; downstream feature/behavior ontologies read shared parameters via param() and write self fields via write_params_self().

Unified temporal + spatial judgment : 13 Allen temporal relations, timeSpan(...) interval construction, date_add / date_diff / duration date arithmetic, geometry(...) / intersects(...) / within(...) / distance(...) spatial predicates — all first-class methods, no extra temporal ontology or GIS scripts needed.

Unified OWL constraint validation : 17 OWL 2 RL read-only constraint methods covering identity, class, relation axioms, cardinality, and property chains. They decide on demand, do not materialize closures, do not write the graph, and can serve directly as terminal boolean methods in condition fields.

Unified chain-value relay : path(...) performs blocking pathfinding; path_value(...) collects field values hop-by-hop along the path and attaches the value array to a target parameter for subsequent get() / db_sim() use. Intermediate chain values no longer rely on application-layer temporary variables.

Unified controlled syntax for LLMs : The in-product LLM generates only default OntologyL_Cypher 2.0: one chain syntax, uniform {"#args": [...]}, embedded read-only functions written as {"#call": ..., "#args": [...]}. The method registry auto-generates the method list; out-of-scope methods, parameter-count mismatches, and calls after a terminal state are intercepted by contract tests.

Unified explainability + auditability : Every expression returns DSLResult(val, msg, current); msg is a Chinese semantic summary for humans and LLMs; meta["trace"] is a per-method record for audit and replay. The result is not a mere boolean but "value + reason + process".

Unified formal graph + sandbox replica execution : The same expression uses identical semantics on the formal graph and on replicas; replicas read/write only within the same ontoL_copy_version, never stitch paths across replicas, never write back to the formal graph. Assembly, re-reasoning, re-cloning, and instance querying all reuse this boundary.

Unified multi-database + multi-graph + multi-language access : Relational sources, graph databases, ontology standard languages, Cypher debug entry, and external interfaces all converge on the same return contract and fail-fast rules. The business layer never needs to branch on "MySQL vs PostgreSQL" or "Memgraph vs Neo4j".

Advantages: Compatibility Matrix and Deterministic Design

The article presents a compatibility matrix showing integrated capabilities:

Relational DB : SQLite 3, MySQL/MariaDB, PostgreSQL, Oracle — unified via db_sim / db_query + unified SQL dialect layer + bind_named_parameters() — no business branch needed.

Graph DB : Memgraph (default), Neo4j (dual-graph mode) — unified via GraphGlot + n / r / next_n / path — no business branch needed.

Ontology & Reasoning Standards : RDFS, OWL2, SWRL, SHACL — unified via 5 import-compile prefixes + other_languages/*_converter.py — only import-compile layer.

Graph Query Language : openCypher — unified via ontoL_cypher: debug entry — no business branch needed.

External Interfaces : Registered dynamic interfaces, MCP tools — unified via func(...) / mcp(...) — no business branch needed.

Spatiotemporal : Allen 13 relations, DE-9IM — unified via timeXxx(...) / geometry(...) / intersects(...) — no business branch needed.

OWL Constraints : OWL 2 RL 17 read-only methods — unified via has_key / functional / all_values_from etc. — no business branch needed.

Relational Databases: Pluggable, Dialect-Isolated

External data source drivers cover SQLite 3, MySQL/MariaDB, PostgreSQL, Oracle. db_sim(...) fetches by data-source code, table name, and JSON condition; db_query(...) executes read-only SQL with double-quoted outer strings, single-quoted internal strings, and named parameters :field.

Dialect conversion, identifier quoting, placeholder binding, and row limits all go through business/tool/sql_dialect.py (using sqlglot); drivers call bind_named_parameters() before execution.

Business modules, routers, drivers, and pages must not directly import sqlglot or build MySQL/PostgreSQL/Oracle branches.

Doris is an optional data-migration target only when explicitly enabled; it does not participate in approval, asset writes, default query paths, or graph reasoning.

Graph Databases: Same Language, Different Dialects

Default single-graph mode uses Memgraph; formal graph and sandbox replicas share the same Memgraph instance.

When GRAPH_DB_ENABLED=true and NEO4J_URI is set, dual-graph mode activates: formal graph on Neo4j, sandbox fixed on Memgraph.

Database switching, constraint DDL, date functions, lock timestamps are handled by infrastructure/graph/graphglot/; new code uses get_graph_glot().

Business layer and execution compilers must not directly judge Memgraph/Neo4j brands. n(#ID) matches by ontoL_snowflake_id / ontoL_source_id / ontoL_reldb_id, never compiles to Neo4j internal id(n).

Reasoning Languages & Ontology Standards: Import, Validate, Execute Separated

Runtime retains 5 import-compile prefixes: ontoL_rdfs:, ontoL_owl2:, ontoL_swrl:, ontoL_sh:, ontoL_cypher:.

RDFS/OWL2/SWRL/SHACL prefixes used for standard ontology import compilation and debugging; ontoL_cypher: for direct Cypher debug execution.

These 5 prefixes are not LLM generation entry points; reasoning rules are written in default OntologyL_Cypher 2.0.

Prefixes ontoL_rule:, ontoL_func:, ontoL_mcp:, ontoL_allen:, ontoL_geo: are deleted; appearance triggers immediate fail-fast.

OWL 2 RL constraints, Allen temporal, DE-9IM spatial are read-only methods: no closure materialization, no graph writes, no reasoning-order changes.

Cross-Language Consistency: Single Result Contract

All language entries return DSLResult(val, msg, current); failure always yields val=False with a Chinese reason. Null, empty collections, exceptions, and unknown languages all fail-fast. Cypher pushdown affects only execution path, not return value, Chinese semantics, or reasoning order.

LLM-Friendly: One Syntax, Low Ambiguity

Parameters uniform {"#args": [...]} — no bare parameters.

Embedded functions uniform {"#call": "method", "#args": [...]} — text-form nesting fails at parse time.

JSON strings must use double quotes; bare $field, ${...}, ${} removed.

Method registry, execution dispatch, prompts, and contract tests share a single source, avoiding "prompt allows but executor lacks".

Condition fields accept only decidable true/false expressions; models cannot mix "data-fetch actions" into preconditions.

Explainable, Auditable, Replayable

val

takes only the final data value from the chain tail. msg summarizes actions, fetched fields, affected nodes, blocking reasons, and interface errors across the whole chain. meta["trace"] records per-method index/method/args/result/ok/msg/error; arrays preview max 3 items, objects retain only key names and field counts to avoid logging full data rows.

AND/OR atoms additionally carry expression to pinpoint which atomic condition failed.

Deterministic Execution: Fail-Fast, No Guessing

null

/ undefined = failure; [] = success but no data — the two are not interchangeable.

Singleton data stays [obj], never degrades to a bare object between chain links. sum/avg/max/min return False + Chinese reason when no valid numeric values. .any() / .all() / .none() fail-fast on empty arrays.

Write methods encountering an array but unable to determine a unique target explicitly error; silent first-row selection is forbidden.

Missing fields, illegal times, illegal WKT, path ambiguity, missing explicit relations all fail-fast; "no match" is never disguised as a business conclusion.

Security Boundaries: Read Is Read, Write Is Write

set

/ remove / detach / empty allowed only in ontoL_execution.

Condition fields disallow bare properties, bare traversals, external programs, or external symbolic-language prefixes. write_param() incrementally writes only to the owning first-level entity's ontoL_action_param; write_params_self() writes only to the current node's ontoL_self_param and serves as a fission precondition.

Write-back excludes ontoL_* system fields and _ -prefixed internal markers.

Formal graph and replicas strictly isolated; replica reasoning only mutates the replica.

Performance: Push Down When Possible, Compute Locally Otherwise

Pushdown candidates: n / r entry selection, exact-field get, selector comparisons, filter, limit, order_by, count, sum, avg, max, min, distinct_count, group_by, distinct, collect, unwind, next_n / next_r / prev_n / prev_r.

Python-side evaluation: JSONPath sub-paths, .from_json(), upstream JSON re-filtering/grouping/aggregation, nested parameters and composite conditions not safely expressible in Cypher.

No caching; real-time queries for large-scale graph-object filtering, aggregation, and ontology reasoning.

Extensibility: Registration Is Contract

Currently 102 methods registered across 13 semantic categories.

New methods must include executor implementation and pass tests/test_dsl_method_contract.py verifying "registration implies implementation, prompts do not exceed registry".

Method documentation regenerated from registry by scripts/render_dsl_method_docs.py to prevent doc-code drift.

Language Overview

Three Chain Heads

Chain heads are written directly as function names; when n / r are omitted, they default to the current object. Forbidden: e(...), reasonObj, .attr(...).

Chain Semantics

Each step consumes JSON and produces 0..n JSON values.

Previous step's result is the sole input to the next step; functions written and executed left-to-right.

Any step returning False halts the chain; subsequent methods do not execute.

Function calls are dot-chained; parameters cannot contain text-form nested calls — use JSON-embedded functions or rewrite as dot chains.

Unified JSON Parameters

Rule: {"#args": [...]} expands in method-declaration order; parameter count still validated by method contract.

Embedded functions allow only #call and #args; cannot invoke write methods.

JSON strings use double quotes only; dynamic values use embedded get / get_self, not bare $field.

SQL text outer layer double-quoted, internal string values single-quoted; do not wrap SQL in single-quoted outer strings.

Selectors

Selector syntax examples: n(building) — query nodes by entity code. n(#690) — query by ontoL_snowflake_id / ontoL_source_id / ontoL_reldb_id; exact hit returns single object. n(#101, #102) — multi-ID query. n([floor_count>18]) — filter by field code. n(building[building_status=in_service]) — entity code + field condition (AND). n() — all nodes; subsequent .filter(...) for filtering. n(<Order>, {"name": "order_001"}) — create node; properties as standard JSON double-quoted. r(*) — all relationships. r(R_CONTAINS) — query by relation code (maps to ontoL_relType). r(#456) — query relationship by primary key. r([ontoL_confidence>0.8]) — filter by relationship property.

Selector operators: = / == (equals), != (not equals), > / < / >= / <= (numeric/comparable), ^= (prefix), $= (suffix), *= (substring), ~= (list contains), bare property name (existence). Locators (entity code, field code, relation code) use codes; only values and literals use business values. Chinese name, display names, labels, and ontoL_ontoType are not locators.

Four Data States

null / undefined : Failure — error, exception, upstream block, or expression undecidable. Chain terminates; msg states reason; must not be treated as "no data".

[] : Success — no error, but no values found. Normal fetch chain returns empty array; does not fabricate a row.

[obj] : Success — single JSON object (array length 1). Field access returns singleton value; write-back consumes this object.

[obj, obj, ...] : Success — multiple data (array length > 1). .filter(...) / .sum(...) / .count() etc. process as arrays.

AND / OR

AND/OR are not part of the behavior-function method chain; they are outer-layer split-and-merge. Only the outermost layer is split; parentheses and JSON dictionary interiors are not split.

Condition vs Execution

ontoL_precondition : Allowed — comparison expressions, boolean methods, OWL/spatiotemporal terminal boolean methods. Disallowed — bare properties, bare traversals, data fetch, writes, external programs, external symbolic-language prefixes.

ontoL_execution : Allowed — data fetch, aggregation, judgment, write, fission, path reasoning. Disallowed — expressions not deterministically reproducible by the reasoner. ontoL_precondition is a mandatory trigger constraint, remedial, usually left empty; if filled, must be decidable true/false. path(...) in conditions performs only read-only query or boolean judgment, no additional reasoning; in execution it is a blocking sub-reasoning branch.

Return Values

Corresponding graph fields: ontoL_precondition, ontoL_precondition_log, ontoL_precondition_val for nodes and relations; ontoL_execution, ontoL_execution_log, ontoL_execution_val for nodes and relations.

Method System: 13 Categories, 102 Methods

Full parameters, terminal states, condition availability, and per-method descriptions are authoritative in the auto-generated tables of README.md . The table below is a classification index only.

Read, Judge, Convert ( read ) — 19 methods: abs, coalesce, contains, default, ends_with, from_json, get, get_self, has, is_null, length, matches, param, param_self, round, starts_with, to_date, to_number, to_string Graph Traversal & Pathfinding ( traverse ) — 8 methods: exists_path, next_n, next_r, path, path_value, prev_n, prev_r, reachable Row Filtering & Result Control ( filter ) — 7 methods: all, any, filter, is_not, limit, none, order_by Aggregation & Collection ( aggregate ) — 16 methods: avg, avg_self, collect, count, count_self, distinct, distinct_count, distinct_count_self, group_by, max, max_self, min, min_self, sum, sum_self, unwind Date Calculation ( date ) — 5 methods: date_add, date_diff, days_since, days_until, duration Temporal Relations ( temporal ) — 14 methods: timeSpan + timeBefore, timeMeets, timeOverlap, timeStarts, timeBetween, timeFinishes, timeEquals, timeFinishedBy, timeContains, timeStartedBy, timeOverlappedBy, timeMetBy, timeAfter Spatial Operations ( spatial ) — 4 methods: geometry, intersects, within, distance OWL Constraints ( owl ) — 17 methods: all_values_from, different_from, disjoint_with, equivalent_class, functional, has_key, in_class, inverse_functional, inverse_of, not_of_type, of_type, property_chain, property_chain_to, qualified_cardinality, same_as, some_values_from, transitive Data Fetch ( data ) — 2 methods: db_sim, db_query Write & Action ( write ) — 8 methods: detach, empty, pass_action_params, pass_self_params, remove, set, write_param, write_params_self External Calls ( external ) — 2 methods: func, mcp Comparison Ops ( compare ) — 0 methods: only for formula catalog display; no executable registered methods

Literals ( literal ) — 0 methods: only for formula catalog display; no executable registered methods

High-Frequency Methods Quick Reference

get

(1 param): Read shared parameter ontoL_action_param of owning first-level entity; missing field fails fast, no fallback to self field. get_self (1 param): Read current chain object's own field or JSONPath sub-path; missing fails fast, no fallback to shared parameter. param (0-64 params): Read shared parameters by ontoL_description input declaration; 0 args returns all declared fields. param_self (0-64 params): Read current node's ontoL_self_param by same input declaration. next_n / prev_n (1-2 params): Traverse outgoing/incoming edges to downstream/upstream nodes; optional relation code and edge property filter. path (1-2 params): Blocking sub-reasoning branch; 1 arg shortest path, 2 args relation priority, -[R]-> strong binding. path_value (1-3 params): Collect field values hop-by-hop along path; 3rd arg attaches value array to target parameter. filter (1 param): Filter current chain values (single object or array) only; does not re-query graph DB. count / sum / avg / max / min (0-2 params): Aggregate current chain values or shared parameters; fail fast if no valid numeric values. group_by (1-8 params): Group by one or more field codes. db_sim (3-4 params): Fetch by data-source code, table name, and JSON condition. db_query (4-5 params): Execute read-only SQL by data-source code; named parameters :field. write_param (0-64 params): Chain-tail incremental write to owning first-level entity's ontoL_action_param. write_params_self (0-64 params): Chain-tail incremental write to current node's ontoL_self_param; serves as fission precondition. timeSpan (2 params): Assemble start and end into a time interval. geometry (1 param): Parse WKT, bbox, GeoJSON, or field into geometry object. has_key (1-8 params): OWL key uniqueness judgment. functional / inverse_functional (1 param): OWL functionality / inverse functionality judgment.

Examples

6.1 Current Object Condition

Read first-level entity shared parameter, perform numeric or text judgment. Condition field stops at comparison expression or boolean method.

6.2 Global Retrieval Then Filter

Use n() to fetch all nodes, then chain .filter(...) on the current list. filter does not re-query the graph DB; global retrieval must start with n() / r().

6.3 Relation Filtering and Counting

Fetch edges by relation code, filter by edge properties, then count. Relation code maps to ontoL_relType.

6.4 Dynamic Shared Parameter → External Relational DB → Write Back

param()

reads first-level entity shared parameter; db_sim() queries external relational DB using that parameter; write_param() increments result back to same entity's ontoL_action_param. Unlisted existing keys are preserved.

6.5 Read-Only Fetch, Filter, Then Write Self

Fetch functions only return data rows, no implicit write-back; chain-tail write_params_self() writes declared fields to current node's ontoL_self_param and acts as fission precondition.

6.6 Path Aggregation

Current node is implicit start; floor->room traverses segment by segment by entity code; aggregation covers all terminal instances hit by the path. Fails fast if no path found or multiple equal-length shortest paths exist.

6.7 Path Value Collection for Subsequent Fetch

Current node implicit start (e.g., building); path_value() collects 测点编码 along floor → room, attaches value array to point_codes; subsequent get() reads and passes to db_sim(). Path nodes without the field are skipped; if all nodes lack it, returns False with Chinese reason.

6.8 Allen Temporal Interval Judgment

Compose two business fields into a validity interval; judge whether it contains the query window using timeBetween / timeContains with product closed-interval semantics; dates written to day precision, interval end covers 23:59:59.

6.9 Spatial Intersection Judgment

Parse WKT into geometry; judge intersection with work area via DE-9IM intersects. Illegal WKT, missing field, or unsupported geometry type fails fast.

6.10 OWL Constraint Judgment

Encode key uniqueness, functionality, universal constraints in a single rule. OWL methods read current graph or replica only; no closure materialization, no graph writes, no import-approval changes; exceed transitive closure or property-chain scan limits → fail fast.

6.11 Read-Only SQL Query

Execute read-only SQL by data-source code; 3rd parameter JSON supplies :status value; SQL internal strings single-quoted, outer double-quoted; dialect and placeholders handled by unified SQL dialect layer.

Common Errors

Wrong : filter({"#args": ["[status=ready]"]}) used as global retrieval. Correct : n().filter({"#args": ["[status=ready]"]}). Reason : filter only filters current chain values.

Wrong : get({"#args": ["rows"]}).filter(...). Correct : get({"#args": ["rows"]}).from_json().filter(...). Reason : JSON text must be expanded first.

Wrong : Condition only get({"#args": ["qty"]}). Correct : get({"#args": ["qty"]}) > 0 or has({"#args": ["qty"]}). Reason : Condition must be decidable true/false.

Wrong : param_self() to read shared parameter. Correct : param(). Reason : param_self() reads only current node's ontoL_self_param.

Wrong : sum(path(...), field). Correct : path(path).sum({"#args": ["field"]}). Reason : Inner function must execute first, then outer.

Wrong : n(#ID) understood as DB internal ID. Correct : Interpret as ontoL_snowflake_id / ontoL_source_id / ontoL_reldb_id. Reason : Business primary key is not Neo4j internal ID.

Wrong : path(..., {"dry_run": true}). Correct : path(path). Reason : Third parameter deleted; appearance triggers fail-fast.

Wrong : ontoL_allen: / ontoL_geo: prefixes. Correct : timeXxx(...) / geometry(...) / intersects(...). Reason : Old prefixes deleted.

Applicability

Preconditions and execution formulas for entity ontologies and relation ontologies.

Data fetch, calculation, judgment, action, aggregation for feature/behavior ontologies.

Dynamic shared parameter publishing and consumption between first-level entities and downstream feature/behavior ontologies.

Temporal intervals, spatial intersection, OWL 2 RL constraints, pathfinding, and path value collection.

Unified rule expression in automatic workshops, sandbox rehearsals, scenario dialogues, and reasoners.

Controlled, verifiable, replayable generation target for in-product LLMs.

Conclusion

The value of the "World-Class Dynamic Ontology Coordination Language" lies not merely in inventing a syntax, but in folding the hardest dynamic-ontology concerns into a single, iterable execution surface:

Relational DB fetch differences → db_sim / db_query + unified SQL dialect layer.

Graph DB dialect differences → GraphGlot.

Ontology standard language import differences → 5 import-compile prefixes.

Temporal, spatial, OWL judgment differences → first-class behavior-function methods.

LLM generation ambiguities → unified JSON parameters, method registry, contract tests.

Reasoning black-box opacity → msg + trace + Chinese failure reasons.

Formal graph vs. sandbox isolation → ontoL_copy_version + read-only pathfinding boundaries.

One chain that can query, compute, judge, fetch, write back, and explain "why" — that is the positioning of OntologyL_Cypher 2.0 as a dynamic ontology coordination language.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DSLgraph databaserelational databasedeterministic executionspatiotemporal reasoningOntologyL_Cypherontology orchestrationOWL constraints
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.