Low-level RDF
Most programs use rudof_lib. If you need direct access to RDF graphs, use the rudof_rdf crate. It defines generic RDF traits and their implementations for in-memory graphs, SPARQL endpoints and QLever.
Traits
The traits are in rudof_rdf::rdf_core:
| Trait | Purpose |
|---|---|
Rdf | The base trait. It defines the associated types (Subject, IRI, Term, BNode, Literal, Triple) and the conversions between them. |
NeighsRDF | Reads the neighborhood of a node: incoming and outgoing arcs, the predicates of a subject, the triples with a predicate. It also follows SHACL property paths. The validators use it. |
BuildRDF | Builds RDF data: add and remove triples, manage prefixes and the base IRI, and serialize the graph. |
FocusRDF | Adds a focus node, the current position of a parser in the graph. |
QueryRDF | Runs SPARQL SELECT, CONSTRUCT and ASK queries. |
AsyncRDF | The async version of these operations, for backends that use Docker or HTTP, such as QLever. |
Implementations
The implementations are in rudof_rdf::rdf_impl:
| Type | Data source |
|---|---|
OxigraphInMemory | An in-memory graph, based on oxrdf. This is the default backend. |
OxigraphEndpoint | A remote SPARQL endpoint. |
QleverGraphContainer | A local QLever Docker container. It needs the qlever feature. |
Write your code against the traits (Rdf, NeighsRDF, BuildRDF and so on), not against a concrete type. Then it works with all the backends. The RDF backends page shows how the command line tool selects a backend.
Create a graph
#![allow(unused)]
fn main() {
use rudof_iri::iri;
use rudof_rdf::rdf_core::BuildRDF;
use rudof_rdf::rdf_impl::OxigraphInMemory;
let mut graph = OxigraphInMemory::new();
let alice = iri!("http://example.org/alice");
let knows = iri!("http://example.org/knows");
let bob = iri!("http://example.org/bob");
graph.add_triple(alice, knows, bob).unwrap();
assert_eq!(graph.len(), 1);
}
Parse RDF with combinators
rudof_rdf has parser combinators for RDF. A normal parser reads a sequence of characters. These parsers read RDF nodes in a graph. The design follows the combine library.
The parsers work on the RDF data model, not on one syntax. The same parser reads data from Turtle, RDF/XML or a SPARQL endpoint. The rudof SHACL parser uses them to build the SHACL abstract syntax from RDF.
RDFNodeParseis the base parser trait.ParserExthas the combinators, for exampleand(run one parser, then another),then,map,flat_mapandmap_property.
The example reads a PersonShape value from a node:
#![allow(unused)]
fn main() {
use rudof_rdf::rdf_core::{
FocusRDF,
parser::{
RDFParse,
rdf_node_parser::{
RDFNodeParse, // Core trait
ParserExt, // Extension trait (fluent API)
constructors::{
ObjectParser, // captures the current focus node as an Object
SingleStringPropertyParser, // reads a single string-valued property
ListParser, // traverses an RDF list (rdf:first/rdf:rest)
},
},
},
term::{Object, literal::Lang},
};
use rudof_rdf::rdf_impl::{OxigraphInMemory, ReaderMode};
use rudof_rdf::rdf_core::RDFFormat;
use rudof_iri::IriS;
// The domain type to build from the RDF graph.
#[derive(Debug, Clone)]
struct PersonShape {
id: Object,
name: String,
known_langs: Vec<Lang>,
}
/// Reads the single string value of sh:name on the current focus node.
fn parse_name<RDF: FocusRDF>() -> impl RDFNodeParse<RDF, Output = String> {
let sh_name = IriS::new_unchecked("http://www.w3.org/ns/shacl#name");
SingleStringPropertyParser::new(sh_name)
}
/// Reads sh:languageIn ( "en" "fr" ) and returns a Vec<Lang>.
fn parse_language_in<RDF: FocusRDF>() -> impl RDFNodeParse<RDF, Output = Vec<Lang>> {
let sh_language_in = IriS::new_unchecked("http://www.w3.org/ns/shacl#languageIn");
ListParser::new()
.flat_map(|terms: Vec<RDF::Term>| {
let langs: Vec<Lang> = terms.iter().flat_map(RDF::term_as_lang).collect();
Ok(langs)
})
.map_property(sh_language_in)
.map(|mut vecs: Vec<Vec<Lang>>| vecs.pop().unwrap_or_default())
}
/// Combines the field parsers into one `PersonShape` parser.
fn person_shape_parser<RDF: FocusRDF>() -> impl RDFNodeParse<RDF, Output = PersonShape> {
ObjectParser::new().then(move |id: Object| {
parse_name()
.and(parse_language_in())
.flat_map(move |(name, langs)| {
Ok(PersonShape {
id: id.clone(),
name,
known_langs: langs,
})
})
})
}
let turtle = r#"
@prefix ex: <http://example.org/> .
@prefix sh: <http://www.w3.org/ns/shacl#> .
ex:Alice
sh:name "Alice" ;
sh:languageIn ( "en" "fr" ) .
"#;
// 1. Parse a Turtle string into an in-memory RDF graph.
let graph = OxigraphInMemory::from_str(turtle, &RDFFormat::Turtle, None, &ReaderMode::default())
.expect("Failed to parse Turtle");
// 2. Wrap the graph in RDFParse, which tracks the focus node.
let mut rdf_parse = RDFParse::new(graph);
// 3. Set the focus on the node to parse.
let alice: Object = IriS::new_unchecked("http://example.org/Alice").into();
rdf_parse.rdf_mut().set_focus(&alice.clone().into());
// 4. Run the parser.
let person = person_shape_parser()
.parse_focused(rdf_parse.rdf_mut())
.expect("Parsing failed");
println!("Parsed: {:?}", person);
// Parsed: PersonShape { id: Iri {IriS { iri: NamedNode { iri: "http://example.org/Alice" } }},
// name: "Alice",
// known_langs: [Lang { lang: "en" }, Lang { lang: "fr" }] }
}
Reference
See the rudof_rdf API reference for all the traits and types. The rudof_rdf README describes the modules, the Cargo features and the backends.