Data
Load, inspect, change and compare RDF data with rudof_lib. Property graph data, SPARQL endpoints and service descriptions are also data sources.
RDF data
#![allow(unused)]
fn main() {
use rudof_lib::{Rudof, RudofConfig};
use rudof_lib::formats::{
InputSpec, DataFormat, DataReaderMode, ResultDataFormat, NodeInspectionMode
};
use std::str::FromStr;
let mut rudof = Rudof::new(RudofConfig::default());
let rdf_data_input = vec![InputSpec::from_str(
r#"
prefix ex: <http://example.org/> .
ex:alice a ex:Person ;
ex:age 30 .
"#
).unwrap()];
// Load RDF data into Rudof's state
rudof.load_data()
.with_data(&rdf_data_input)
.with_data_format(&DataFormat::Turtle)
.with_reader_mode(&DataReaderMode::Lax)
.with_merge(false)
.execute()
.unwrap();
// Serialize the loaded data to standard output
rudof.serialize_data(&mut std::io::stdout())
.with_result_data_format(&ResultDataFormat::NTriples)
.execute()
.unwrap();
// Serialize the information of the node "ex:alice" to standard output
let node = "ex:alice";
let predicates = vec!["ex:age".to_string()];
rudof.show_node_info(&node, &mut std::io::stdout())
.with_show_node_mode(&NodeInspectionMode::Outgoing)
.with_predicates(&predicates)
.with_depth(1)
.with_show_colors(false)
.execute()
.unwrap();
// Reset data state
rudof.reset_data().execute();
}
Node neighborhood
show_node_info renders the neighborhood of a node as an ASCII tree. node_neighborhood gives the same traversal as a lazy iterator of NeighborArc values. It gives the structure instead of the text.
The builder accepts the same options as show_node_info: predicates, inspection mode, depth and IRI normalization. The NodeNeighborhood result yields one Result<NeighborArc> per visited arc, in depth-first order, for each node that the node selector matches. Each NeighborArc has these fields:
root: the matched node where the traversal started.direction:ArcDirection::Outgoing(the node is the subject) orArcDirection::Incoming(the node is the object).depth: the distance fromroot, starting at 1.node,predicate,neighbor: the arc.is_last: true for the last arc among the siblings ofnode. The tree renderer uses it to draw the branch corners.
The iterator borrows the loaded graph. You cannot change the Rudof instance while the iterator exists.
#![allow(unused)]
fn main() {
use rudof_lib::{Rudof, RudofConfig};
use rudof_lib::formats::{InputSpec, IriNormalizationMode, NodeInspectionMode};
use rudof_lib::types::{ArcDirection, NeighborArc};
use std::str::FromStr;
let mut rudof = Rudof::new(RudofConfig::default());
let rdf_data_input = vec![InputSpec::from_str(
r#"
prefix ex: <http://example.org/>
ex:alice ex:knows ex:bob ;
ex:age 30 .
ex:bob ex:knows ex:carol .
ex:dave ex:knows ex:alice .
"#
).unwrap()];
// Load RDF data into Rudof's state
rudof.load_data().with_data(&rdf_data_input).execute().unwrap();
// Traverse the neighborhood of "ex:alice" instead of rendering it
let predicates = vec!["ex:knows".to_string()];
let neighborhood = rudof.node_neighborhood("ex:alice")
.with_mode(&NodeInspectionMode::Both)
.with_predicates(&predicates)
.with_depth(2)
.with_iri_mode(IriNormalizationMode::Lax)
.execute()
.unwrap();
for arc in neighborhood {
let NeighborArc { depth, direction, node, predicate, neighbor, .. } = arc.unwrap();
let arrow = match direction {
ArcDirection::Outgoing => "-->",
ArcDirection::Incoming => "<--",
};
println!("{:indent$}{node} {arrow} {predicate} {arrow} {neighbor}", "", indent = (depth - 1) * 2);
}
// Prints:
// http://example.org/alice --> http://example.org/knows --> http://example.org/bob
// http://example.org/bob --> http://example.org/knows --> http://example.org/carol
// http://example.org/alice <-- http://example.org/knows <-- http://example.org/dave
}
Triples
add_triple, remove_triple and triples work on the loaded graph one triple at a time. Use them to build a graph in code, or to add the triples that a validation report says are missing.
Terms are text in RDF 1.2 Turtle syntax, so you do not build RDF terms by hand. A term can be:
- An IRI (
<http://example.org/alice>) or a prefixed name (ex:alice). - A blank node label (
_:b1). - A literal (
"Alice","Alice"@en,"Shalom"@he--rtl,23,"23"^^xsd:integer). - A triple term (
<<( ex:alice ex:name "Alice" )>>), which can contain another triple term.
Rules for terms:
- Prefixed names use the prefixes of the loaded data and the default prefixes of the session. An unknown alias is an error.
- A term must be a single term. Text for several triples is refused, for example a reified triple (
<< ex:a ex:b ex:c >>), a blank node property list or a collection. - A triple term can only be an object, as RDF 1.2 requires.
- An IRI inside a triple term must be in angle brackets or prefixed, also in the lax IRI mode.
- A relative IRI (
<alice>, or the datatype in"23"^^<integer>) is resolved against the base IRI of the session:base_iriin the configuration, or else the current directory. If no base is available (for example on WebAssembly without a configured base), a relative IRI is an error. node_neighborhoodresolves its node and predicates in the same way. Its node can also be a node selector ({FOCUS ex:knows _},SPARQL "…").
triples takes a pattern. An unset position matches any term, so a builder with no position set walks the whole graph. Like node_neighborhood, it borrows the loaded data, so you cannot change the data while you walk the triples.
Each result is an oxrdf::Triple, the same type that the term parser produces. Its text (Display, or to_string() on each term) is in N-Triples form: absolute IRIs in angle brackets, literals with their datatype as an absolute IRI, blank node labels, and triple terms as <<( … )>>. You can pass that text back to add_triple, remove_triple and the patterns without changes.
Only the in-memory graph can change. A SPARQL endpoint, the QLever backend and data federated with endpoints are read-only. triples works on all of them, but a pattern with no set position pulls the whole graph from a remote backend.
#![allow(unused)]
fn main() {
use rudof_lib::{Rudof, RudofConfig};
use rudof_lib::formats::InputSpec;
use std::str::FromStr;
let mut rudof = Rudof::new(RudofConfig::default());
let rdf_data_input = vec![InputSpec::from_str(
r#"
prefix ex: <http://example.org/>
ex:alice ex:name "Alice" .
"#
).unwrap()];
rudof.load_data().with_data(&rdf_data_input).execute().unwrap();
// Change the graph in place
rudof.add_triple("ex:alice", "ex:knows", "ex:bob").execute().unwrap();
rudof.add_triple("ex:bob", "ex:name", "\"Bob\"").execute().unwrap();
rudof.remove_triple("ex:alice", "ex:name", "\"Alice\"").execute().unwrap();
// Walk the triples matching a pattern (here: everything ex:bob is the subject of)
for triple in rudof.triples().with_subject("ex:bob").execute().unwrap() {
println!("{triple}");
}
// Prints:
// <http://example.org/bob> <http://example.org/name> "Bob" .
}
Staging
begin_staging, commit_staging, rollback_staging and staging_depth make a group of changes to the loaded data provisional. You stage the changes and test them, for example with a validation or a query. Then you keep the changes or restore the graph.
staging()returns a guard. If the guard is dropped before a commit, for example after an early return or an error, the frame rolls back.add_triplesandremove_triplesapply a whole delta in one operation. They parse all the triples before they write any, so a batch with a term that does not parse changes nothing.- Frames can nest. A commit of a nested frame passes its changes to the enclosing frame, so a rollback of the outer frame also undoes the inner work.
Only the data is staged. The loaded schemas, shapemaps, prefixes and configuration stay loaded after a rollback. This includes a SHACL schema read from the data graph (load_shacl_schema with no source): a rollback restores the shape triples in the graph, but not the compiled schema. In this case, rudof logs a warning.
A rollback clears the results computed from the discarded data: the SHACL and ShEx validation results, the query results and the loaded SPARQL query.
Staging needs data that can change. A frame does not open on read-only data: a SPARQL endpoint, the QLever backend or endpoint-federated data (DataError::ReadOnlyData). It also does not open on property graphs or on an empty session (DataError::NoRdfDataLoaded). A commit or rollback without an open frame fails with DataError::NoStagingFrame.
For a large graph, stage triple deltas, keep load_data and dereference outside the frame, and do not nest frames that load data. The rudof_lib README explains the memory cost of staging.
#![allow(unused)]
fn main() {
use rudof_lib::{Rudof, RudofConfig};
use rudof_lib::formats::InputSpec;
use std::str::FromStr;
let mut rudof = Rudof::new(RudofConfig::default());
let rdf_data_input = vec![InputSpec::from_str(
r#"
prefix ex: <http://example.org/>
ex:alice ex:name "Alice" .
"#
).unwrap()];
rudof.load_data().with_data(&rdf_data_input).execute().unwrap();
// The guard holds the frame open and derefs to the session.
let mut tx = rudof.staging().execute().unwrap();
tx.add_triples(&[("ex:bob", "ex:name", "\"Bob\""), ("ex:alice", "ex:knows", "ex:bob")])
.execute()
.unwrap();
// Check whatever has to hold, reading the results before the frame is closed.
let staged = tx.triples().execute().unwrap().count();
if staged == 3 {
tx.commit().unwrap();
} else {
tx.rollback().unwrap();
}
// Dropping the guard without either rolls the frame back.
assert_eq!(rudof.triples().execute().unwrap().count(), 3);
}
Without the guard, open and close the frame yourself:
#![allow(unused)]
fn main() {
use rudof_lib::{Rudof, RudofConfig};
use rudof_lib::formats::InputSpec;
use std::str::FromStr;
let mut rudof = Rudof::new(RudofConfig::default());
let rdf_data_input = vec![InputSpec::from_str(
r#"
prefix ex: <http://example.org/>
ex:alice ex:name "Alice" ; ex:knows ex:bob .
"#
).unwrap()];
rudof.load_data().with_data(&rdf_data_input).execute().unwrap();
// Open a frame. `execute` returns the new staging depth.
let depth = rudof.begin_staging().execute().unwrap();
assert_eq!(depth, 1);
// Remove several triples in one operation
rudof.remove_triples(&[("ex:alice", "ex:knows", "ex:bob")]).execute().unwrap();
assert_eq!(rudof.staging_depth().execute(), 1);
// Undo the change, or call `commit_staging` to keep it
rudof.rollback_staging().execute().unwrap();
assert_eq!(rudof.triples().execute().unwrap().count(), 2);
}
HTML data
DataFormat::Html reads HTML pages.
Rudof extracts the RDF of the microdata, the RDFa and the JSON-LD <script> elements in each page.
The conversion of microdata follows the W3C Microdata to RDF specification.
The conversion of RDFa follows RDFa Core 1.1 and HTML+RDFa 1.1.
The extraction of JSON-LD follows the HTML content algorithms of JSON-LD 1.1.
Then you can validate, query and serialize this data in the same way as other RDF data.
#![allow(unused)]
fn main() {
use rudof_lib::{Rudof, RudofConfig};
use rudof_lib::formats::{DataFormat, InputSpec, ResultDataFormat};
use std::str::FromStr;
let mut rudof = Rudof::new(RudofConfig::default());
let html_input = vec![InputSpec::from_str(
r##"<div itemscope itemid="#alice" itemtype="http://schema.org/Person">
<span itemprop="name">Alice</span>
</div>"##,
).unwrap()];
// Load the RDF of the microdata in the page into Rudof's state
rudof.load_data()
.with_data(&html_input)
.with_data_format(&DataFormat::Html)
.with_base("http://example.org/people")
.execute()
.unwrap();
// Serialize the loaded data to standard output
rudof.serialize_data(&mut std::io::stdout())
.with_result_data_format(&ResultDataFormat::NTriples)
.execute()
.unwrap();
}
The output is as follows. The order of the triples can change.
<http://example.org/people#alice> <http://schema.org/name> "Alice" .
<http://example.org/people#alice> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.org/Person> .
The base IRI resolves the relative URLs of the page, such as itemid="#alice".
If you do not set a base IRI, rudof uses the base IRI of the configuration.
If the configuration has no base IRI, rudof uses the current directory.
By default, rudof reads the microdata, the RDFa and the JSON-LD of a page, and merges them in one graph.
with_html_extraction selects the RDF to read in one load: HtmlExtraction::Microdata, HtmlExtraction::Rdfa, HtmlExtraction::JsonLd or HtmlExtraction::Any.
#![allow(unused)]
fn main() {
use rudof_lib::{Rudof, RudofConfig};
use rudof_lib::formats::{DataFormat, HtmlExtraction, InputSpec};
use std::str::FromStr;
let mut rudof = Rudof::new(RudofConfig::default());
let html_input = vec![InputSpec::from_str(
r#"<div itemscope itemid="http://example.org/alice"><span itemprop="http://schema.org/name">Alice</span></div>
<p about="http://example.org/bob" property="http://schema.org/name">Bob</p>"#,
).unwrap()];
// Load only the RDFa of the page
rudof.load_data()
.with_data(&html_input)
.with_data_format(&DataFormat::Html)
.with_html_extraction(&HtmlExtraction::Rdfa)
.execute()
.unwrap();
}
The loaded data has only the triple of Bob:
<http://example.org/bob> <http://schema.org/name> "Bob" .
To set the default for a session, set html_extraction in the [rdf] section of the configuration.
To add the triples of a page to your own graph, use the rudof_microdata, rudof_rdfa and rudof_jsonld crates.
Their parse_into methods write into any graph that implements the BuildRDF trait.
Property graph data
#![allow(unused)]
fn main() {
use rudof_lib::{Rudof, RudofConfig};
use rudof_lib::formats::{InputSpec, DataFormat, DataReaderMode, ResultDataFormat};
use std::str::FromStr;
let mut rudof = Rudof::new(RudofConfig::default());
let pg_data_input = vec![InputSpec::from_str(
r#"
(alice {Person} [ name: "Alice", age: 23, aliases: "Ally" ])
(bob {Person} [ name: "Robert", aliases: ["Bob", "Bobby"] ])
"#,
).unwrap()];
// Load Property Graph data into Rudof's state (without merging)
rudof.load_data()
.with_data(&pg_data_input)
.with_data_format(&DataFormat::Pg)
.execute()
.unwrap();
// Serialize the loaded data to standard output
rudof.serialize_data(&mut std::io::stdout()).execute().unwrap();
}
SPARQL endpoints
#![allow(unused)]
fn main() {
use rudof_lib::{Rudof, RudofConfig};
let mut rudof = Rudof::new(RudofConfig::default());
// Lists the registered SPARQL endpoints
let endpoints = rudof.list_endpoints().execute()?;
for (name, url) in endpoints {
println!("{}, {}", name, url);
}
// Focus SPARQL endpoint
let endpoint = "http://example.org/sparql";
rudof.load_data()
.with_endpoint(&endpoint)
.execute()
.unwrap();
}
Service descriptions
#![allow(unused)]
fn main() {
use rudof_lib::{Rudof, RudofConfig};
use rudof_lib::formats::{
InputSpec, DataFormat, DataReaderMode, ResultServiceFormat
};
use std::str::FromStr;
let mut rudof = Rudof::new(RudofConfig::default());
let service_description_input = InputSpec::from_str(
r#"
prefix sd: <http://www.w3.org/ns/sparql-service-description#> .
prefix ent: <http://www.w3.org/ns/entailment/> .
<http://example.org/sparql> a sd:Service ;
sd:endpoint <http://example.org/sparql> ;
sd:supportedLanguage sd:SPARQL11Query ;
sd:defaultEntailmentRegime ent:Simple .
"#
).unwrap();
// Load a Service Description into Rudof's state
let base = "http://example.org/";
rudof.load_service_description(&service_description_input)
.with_data_format(&DataFormat::Turtle)
.with_reader_mode(&DataReaderMode::Strict)
.with_base(&base)
.execute()
.unwrap();
// Serialize the loaded service description to standard output
rudof.serialize_service_description(&mut std::io::stdout())
.with_result_service_format(&ResultServiceFormat::Json)
.execute()
.unwrap();
}
Prefixes, dereference and statistics
#![allow(unused)]
fn main() {
use rudof_lib::{DataStats, Rudof, RudofConfig};
use rudof_lib::formats::InputSpec;
use std::str::FromStr;
let mut rudof = Rudof::new(RudofConfig::default());
let rdf_data_input = vec![InputSpec::from_str(
r#"
prefix ex: <http://example.org/>
ex:alice ex:name "Alice" .
"#
).unwrap()];
rudof.load_data().with_data(&rdf_data_input).execute().unwrap();
// Manage the prefixes of the session
rudof.add_prefix("schema", "https://schema.org/").execute().unwrap();
rudof.copy_prefix("schema", "s").execute().unwrap();
rudof.rename_prefix("s", "sdo").execute().unwrap();
rudof.remove_prefix("sdo").execute().unwrap();
let prefixmap = rudof.prefixes().execute();
println!("{prefixmap}");
// Count the loaded triples (or the nodes and edges of property graph data)
if let Some(DataStats::Rdf { triples }) = rudof.data_stats() {
println!("{triples} triples");
}
// Download the RDF document behind an IRI and merge it with the loaded data
rudof.dereference("http://www.w3.org/1999/02/22-rdf-syntax-ns")
.with_merge(true)
.execute()
.unwrap();
}
Data comparison
compare_data compares two RDF graphs, and compare_loaded_data compares the loaded data with another graph. execute returns the relation between the graphs, and execute_diff returns the triples that are different.
#![allow(unused)]
fn main() {
use rudof_lib::{Rudof, RudofConfig};
use rudof_lib::formats::{DataFormat, InputSpec};
use rudof_lib::types::{GraphRelation, SubgraphMode};
use std::str::FromStr;
let rudof = Rudof::new(RudofConfig::default());
let data1 = InputSpec::from_str(r#"<http://example.org/a> <http://example.org/p> _:x ."#).unwrap();
let data2 = InputSpec::from_str(r#"<http://example.org/a> <http://example.org/p> _:y ."#).unwrap();
let relation = rudof.compare_data(&data1, &data2)
.with_format(&DataFormat::Turtle)
.with_mode(&SubgraphMode::Injective)
.execute()
.unwrap();
assert!(matches!(relation, GraphRelation::Isomorphic));
// The triples that only one of the graphs has
let diff = rudof.compare_data(&data1, &data2)
.with_format(&DataFormat::Turtle)
.execute_diff()
.unwrap();
}