## Structured schemas help language models query large knowledge graphs without retraining

URL: https://theprimary.com/ai-tech/2026-11-27/exygen-knowledge-graphs-sparql
Published: 2026-11-27T20:17:35.911Z
Updated: 2026-11-27T20:17:36.361Z
Category: AI-Tech

Supplying formal structural definitions and small samples at prompt time allows generalist models to query massive databases accurately while avoiding costly neural retraining.

Massive knowledge graphs store humanity's scientific observations, cultural catalogues, and research citations in intricate webs of interconnected nodes and relations. For a researcher seeking an answer, extracting facts from these databases usually requires writing queries in SPARQL, a precise, rigid query language designed for graph data. A human must know the exact formal property labels, data types, and structural connections inside the graph to retrieve even basic information. While modern artificial intelligence systems can speak in natural human prose, getting a standard large language model to translate everyday questions into flawless SPARQL queries typically requires intensive, graph-specific training that breaks whenever the underlying structure changes.

Bridging this gap matters because scientific knowledge graphs contain billions of verifiable facts that could inform discoveries, yet they remain largely locked behind computational hurdles and specialized query interfaces. When researchers attempt to adapt language models to these databases, they face a double barrier. Fine-tuning a neural network on a single repository is expensive, fragile, and fails to generalize to other databases that assign different numerical identifiers to properties. Conversely, scanning massive databases containing billions of connections to create structural documentation for language models overwhelms database servers, causing queries to stall or time out before returning a result.

To turn everyday questions into exact database queries, a computational system must navigate a strict causal sequence. First, the system must inspect the database to extract structural rules detailing which properties connect to which conceptual categories. Second, it must condense these complex statistical summaries into concise, human-readable templates that define allowable relationships. Third, when a user asks a question, an automated retrieval mechanism must select the specific structural templates, sample database facts, and query examples that match the topic. Finally, the language model uses these focused architectural guides to write an exact query that matches the database structure on the first attempt.

In a preprint posted on the arXiv server, Harshdeep Singh, Yurui Zhu, Giovanni Colavizza, and Matteo Romanello at Odoma Ltd. report a framework named EXYGEN, short for the EXplore Your Graphs ENgine. The framework demonstrates that off-the-shelf language models, provided only with automatically generated schema definitions and small retrieved graph samples, can query complex academic databases without requiring any specialized model fine-tuning. On a benchmark grounded in scientific literature, their top-performing pipeline reached an execution accuracy of 0.419, measured as the proportion of generated queries that returned the exact correct database result, while bypassing the task-specific fine-tuning typical of domain-adapted models.

## Why do standard language models struggle to write graph queries?

General language models fail at writing database queries because they cannot guess the arbitrary internal identifiers and rigid structural rules that govern specialized knowledge collections. When a language model hallucinates an answer in conversation, it weaves plausible-sounding words together. When it hallucinates an identifier inside a SPARQL query, the entire database request fails immediately, returning a syntax error or a blank response. Prior research cited by the authors, conducted by Mecharnia and d'Aquin, demonstrated this brittleness by training Llama models on academic datasets: the best fine-tuned system achieved a Macro F1 score of 60.68 percent on the DBpedia collection, but plummeted to 13.36 percent on Wikidata, where entities and relations are represented by non-intuitive, alphanumeric codes that pretraining data rarely explains.

To resolve this identifier bottleneck without retraining billions of neural weights for every new repository, Singh and colleagues designed EXYGEN to supply structural constraints directly into the prompt context at query time. The system relies on two standardized Linked Data formats: the Vocabulary of Interlinked Datasets, known as VoID, which documents high-level dataset statistics such as class and predicate distributions, and Shape Expressions, or ShEx, a formal schema language that translates raw statistics into clean, human-readable structural definitions specifying expected properties, allowed value types, and cardinality constraints. When provided with these Shape Expressions, an off-the-shelf model receives the precise boundaries of the database schema alongside the user's conversational query.

Matteo Romanello, a researcher at Odoma Ltd. and corresponding author of the preprint, told Primary that these formal definitions give neural networks the vocabulary boundaries they otherwise lack. Explaining why this structural context prevents errors, Romanello said: "ShEx provides an LLM with information about the correct vocabulary (classes, properties and namespaces) used in the target knowledge graphs. ShEx provides a structured representation of how ontology classes relate to one another via properties, the constrains applying to the values a given property can take, etc. All this helps the model to write semantically correct SPARQL queries."

Evaluating this pipeline on the SciQA benchmark, which consists of 2,565 natural language question and SPARQL query pairs based on the Open Research Knowledge Graph, the authors examined how different pieces of contextual guidance altered query generation. The benchmark splits into 1,795 training pairs, 257 validation pairs, and 513 test pairs, incorporating both human-crafted and automated inquiries across scholarly literature. The authors found that providing ShEx schemas alongside retrieved data triples and example query pairs yielded an execution exact-match score of 0.419 on the 513 test questions, proving that external structural context can stand in place of costly task-specific fine-tuning.

The experiments also revealed that superficial linguistic metrics can conceal underlying functional failures. Lexical metrics like string-level F1 scores correlated poorly with whether an executed SPARQL query actually retrieved the correct facts from the database, because a query can match human vocabulary closely while misplacing a single structural bracket that breaks execution. Furthermore, the authors observed that larger general-purpose language models outperformed smaller models fine-tuned specifically for programming code once given sufficient schema context, showing that broad reasoning capabilities benefit more from structured constraints than specialized syntax training does.

Asked what syntax defect caused this disconnect between textual similarity and functional execution, Harshdeep Singh, lead author of the study, explained that small prefix declarations routinely tripped the models up. Singh said: "The most frequent flaw was in the prefix declarations. A prefix statement defines a short alias for a full namespace URI, letting you write something like \"orkgc:Dataset\" instead of the entire <http://orkg.org/orkg/class/Dataset> throughout the query. Queries would often score high on lexical match because the triple patterns, variables, and keywords were essentially correct, but they failed at execution because the prefix statements were either missing, incompletely declared, or mapped to the wrong URIs."

Asked what benchmark condition would demonstrate that code-specialized systems truly surpass generalist architectures, Romanello pointed to lenient evaluation standards that forgive minor formatting variations. Romanello told Primary: "In particular, the Execution-based Exact Match Relaxed. By looking at the benchmark results for this metric for code-specialized models (see Table 1 in the paper), we can see that the gap with large general-purpose models is still quite wide."

## How can servers extract structural rules from billions of facts?

Extracting structural rules from massive collections requires moving away from exhaustive database scans toward representative graph sampling. Generating standardized VoID metadata descriptions traditionally relies on running extensive aggregation queries across live SPARQL endpoints, computing partition counts, instance tallies, and cross-dataset Cartesian joins. On massive databases, these aggregate queries consistently time out. The authors point to external research by Hasnain and colleagues evaluating 618 public endpoints: while straightforward enumeration queries succeeded on up to 94 percent of operational endpoints, aggregation queries calculating triple counts succeeded on as few as 25 percent, frequently running into fixed server cutoffs such as 40,000-row response caps.

To overcome this computational roadblock, the authors developed a predicate-coverage-aware parallel graph sampling strategy within the EXYGEN API. The sampling algorithm preserves the structural diversity of the underlying network while drastically shrinking the total volume of data that server scripts must calculate. The system targets knowledge graphs of massive scale, evaluating its performance across three repositories: the OpenCitations Meta database containing 4.94 billion triples, the GESIS social science knowledge graph with 97.52 million triples, and a frozen dump of the Open Research Knowledge Graph comprising 1.13 million triples.

The structural characteristics of these three databases differ substantially. OpenCitations Meta and GESIS represent large bibliographic graphs with comparatively flat relational structures, storing repetitive metadata such as publication titles, persistent identifiers, authors, and venues. In contrast, the Open Research Knowledge Graph captures complex scholarly claims, methodological comparisons, and fine-grained scientific contributions, resulting in a dense ontology with an exceptionally wide variety of unique predicate combinations relative to its triple count.

When applied to OpenCitations Meta and GESIS, the parallel sampling technique maintained high predicate coverage while reducing metadata generation processing time by over 80 times compared to exhaustive calculations, keeping triple losses minimal. However, Romanello clarified in commentary to Primary that attributing an identical 80-fold reduction across both databases blurs important operational differences between the repositories. Romanello noted that the 80-fold speedup was measured specifically on the GESIS collection, where sampling compressed processing time from roughly 19 minutes down to under 14 seconds on a sample covering 0.42 percent of its 97 million triples.

On OpenCitations Meta, the operational gains proved substantially larger than an 80-fold increase. Full-graph extraction on the live endpoint consumed 64 minutes, whereas sampling collapsed the calculation to 11 seconds on a subset covering less than 0.01 percent of its 4-billion-triple graph, requiring only 331 queries instead of the 604 calls demanded by an exhaustive scan. On the Open Research Knowledge Graph, the sampling strategy proved even more essential: the intricate, highly populated ontology rendered full-graph schema extraction completely infeasible due to server limits, making selective graph sampling the only viable operational pathway to produce usable structural metadata.

Yet the sampling algorithm faces its own clear boundary conditions when exploring graphs with unusual topologies. Singh explained that the technique can fail when critical relationship paths sit outside densely connected central nodes. Singh said: "The sampling algorithm's failure mode is long-tail predicate distributions where rare predicates are structurally essential but topologically isolated from high-degree hubs. In such graphs, essential relationship predicates connecting distinct communities appear in a vanishingly small fraction of triples but carry disproportionate structural weight. Random walks with degree-based neighbor selection naturally gravitate toward hub nodes and their dense neighborhoods, systematically bypassing the mid-degree connector nodes that bridge structurally distinct sub-communities."

## What the framework leaves unresolved

These findings show the strength of schema-guided prompts, but the current results represent an experimental demonstration rather than a universal query engine. The performance figures reflect evaluations conducted on a single benchmark, the scholarly SciQA dataset, which may not capture the idiosyncrasies of medical records, industrial supply chain networks, or noisy crowdsourced databases. While achieving an execution exact match of 0.419 without model training represents notable progress, more than half of the generated queries still failed to retrieve the exact intended database records.

The authors acknowledge this evaluation boundary directly. Romanello told Primary that the team remains cautious about extrapolating these benchmark results to other scientific disciplines: "I'd caution readers about the fact that it still remains to be verified and proved how well our framework could perform question answering over KGs in other domains. A related ongoing effort in which we are involved looks at constructing exactly such a type of benchmark for the social sciences and humanities."

The system also continues to lean on curated example question-query pairs provided in the contextual prompt. Generating or harvesting these paired examples manually requires human labor, partially offsetting the operational convenience gained by bypassing model fine-tuning. The underlying paper is an unrefereed preprint that has been posted online and presented at a workshop but has not yet completed formal journal peer review. Furthermore, the structural sampling method assumes that rare entity types follow structural patterns similar to sampled nodes, an assumption that could overlook obscure edge cases in fragmented knowledge repositories.

## Where conversational database querying goes next

Closing the remaining accuracy gap without falling back on full-scale model fine-tuning will require systems that can autonomously generate their own training materials and correct their own errors. Singh and colleagues propose investigating synthetic exemplar generation, where language models produce their own hypothetical question-query pairs from extracted schemas to eliminate reliance on human-annotated examples. Another promising direction involves incorporating execution feedback into the generation loop, allowing an automated agent to inspect the database engine's error messages and rewrite invalid SPARQL syntax iteratively until a valid result emerges.

If these schema-retrieval techniques generalize across other enterprise and scholarly databases, institutional data repositories could deploy natural language interfaces without maintaining fleets of specialized neural networks. Rather than retraining a multi-billion-parameter model whenever a database schema updates, engineers could simply run automated sampling routines to refresh the Shape Expressions, keeping conversational access aligned with evolving human knowledge.
