RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3...

32
RDFSharp - Start playing with RDF! Reference Guide (0.6.10-LTS)

Transcript of RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3...

Page 1: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

RDFSharp - Start playing with RDF!

Reference Guide (0.6.10-LTS)

Page 2: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

2

Introduction ........................................................................................................................... 3

History of the project .................................................................................................................................................. 3

Technical requirements ............................................................................................................................................... 3

Working with RDF models ..................................................................................................... 4

Creating resources, literals and triples ...................................................................................................................... 4

Creating, manipulating and exchanging graphs ...................................................................................................... 5

Working with namespaces, datatypes and vocabularies ........................................................................................ 9

Working with containers and collections ................................................................................................................ 14

The problem of reification ........................................................................................................................................ 16

Working with RDF stores .................................................................................................... 17

Tracking provenance of RDF data with contexts and quadruples ....................................................................... 17

Creating and manipulating stores............................................................................................................................ 18

Backing stores on SQL engines ................................................................................................................................ 21

Creating and manipulating federations .................................................................................................................. 23

Working with SPARQL queries ........................................................................................... 24

Basics of Mirella Query Engine: variable, pattern, pattern group ....................................................................... 24

Basics of Mirella Query Engine: filter, modifier ..................................................................................................... 26

Creating and executing Select queries .................................................................................................................... 29

Creating and executing Ask queries ........................................................................................................................ 30

Creating and executing Construct queries ............................................................................................................. 31

Creating and executing Describe queries ............................................................................................................... 32

Page 3: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

3

INTRODUCTION

HISTORY OF THE PROJECT

RDFSharp is a lightweight C# framework which can be used to quickly draft Windows

and Web applications capable of modeling, storing and querying RDF data. The project

was launched on Codeplex on 15th June 2012 with the goal of providing the .NET

community with an entry point for start playing with RDF and Semantic Web concepts.

The library is distributed under Apache 2.0 license, with open source codebase available

at the following Codeplex SVN repository: https://rdfsharp.svn.codeplex.com/svn

Starting from release 0.6.10.4, binary NuGet packages are available for download!

Just search for "RDFSharp" via the NuGet plugin of Visual Studio and you’ll be able to

get the selected library assemblies in your project references ☺

TECHNICAL REQUIREMENTS

The reference platform of the project is Microsoft Visual Studio 2010: the solution ships

with Debug/Release build configurations targeting .NET Framework 3.5 SP1 or 4.0.

The main assembly is named RDFSharp.dll and exposes "RDFSharp.Model",

"RDFSharp.Store" and "RDFSharp.Query" namespaces. Additional plugin assemblies allow

the storage of RDF data on the following SQL database engines:

Firebird RDFSharp.RDFFirebirdStore.dll + FirebirdSql.Data.FirebirdClient.dll

MySQL RDFSharp.RDFMySQLStore.dll + MySql.Data.dll

SQLite RDFSharp.RDFSQLiteStore.dll + System.Data.SQLite.dll

SQL Server RDFSharp.RDFSQLServerStore.dll

Important: RDFSharp.dll is a neutral "AnyCPU" assembly, but in order to work with

SQLite, which is a mixed-mode platform-dependant assembly, it is built by referencing

the System.Data.SQLite.dll corresponding to the detected platform ("x86" or "x64"). Be

aware of this when you develop or deploy RDFSharp applications backing on SQLite,

otherwise you may encounter runtime exceptions (e.g.: "BadImageFormatException").

Page 4: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

4

WORKING WITH RDF MODELS

CREATING RESOURCES, LITERALS AND TRIPLES

A resource is an URI-named concept, modeled as instance of RDFResource:

// CREATE RESOURCE FROM STRING RDFResource donaldduck = new RDFResource("http://www.waltdisney.com/donald_duck"); // CREATE RESOURCE FROM URI RDFResource goofygoof = new RDFResource(new Uri("http://www.waltdisney.com/goofy_goof")); // CREATE BLANK RESOURCE RDFResource disney_group = new RDFResource();

The "IsBlank" property is a flag informing about nature of the resource: a blank resource

carries an automatically generated Guid-based Uri starting with "bnode:" prefix.

A literal is a textual piece of information, modeled as instance of RDFPlainLiteral or

RDFTypedLiteral, depending on the nature of represented data:

// CREATE PLAIN LITERAL // "Donald Duck" RDFPlainLiteral donaldduck_name = new RDFPlainLiteral("Donald Duck"); // CREATE PLAIN LITERAL WITH LANGUAGE TAG // "Donald Duck"@en-US RDFPlainLiteral donaldduck_name_enus = new RDFPlainLiteral("Donald Duck", "en-US"); // CREATE TYPED LITERAL // "85"^^xsd:integer RDFTypedLiteral mickeymouse_age = new RDFTypedLiteral("85", RDFDatatypeRegister. GetByPrefixAndDatatype("xsd", "integer"));

A triple is an assertion about a resource, modeled as instance of RDFTriple:

// CREATE TRIPLES // "Mickey Mouse is 85 years old" RDFTriple mickeymouse_is85yr = new RDFTriple( new RDFResource("http://www.waltdisney.com/mickey_mouse"), new RDFResource("http://xmlns.com/foaf/0.1/age"), mickeymouse_age); // "Donald Duck has English-US name "Donald Duck"" RDFTriple donaldduck_name_enus = new RDFTriple( donaldduck, new RDFResource("http://xmlns.com/foaf/0.1/name"), donaldduck_name_enus);

It is made up of a "Subject" part (the resource being described), a "Predicate" part (the

resource being the verb of description) and an "Object" part (the resource or the literal

being the knowledge described about the subject). Depending on the nature of the

object, a triple assumes a SPO or SPL flavor represented by the "TripleFlavor" property.

Important: when creating a triple, validation against presence of a blank resource in the

predicate position occurs, throwing a RDFModelException in case of detection.

Page 5: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

5

CREATING, MANIPULATING AND EXCHANGING GRAPHS

A graph is an URI-named collection of triples, modeled as instance of RDFGraph:

// CREATE EMPTY GRAPH RDFGraph waltdisney = new RDFGraph(); // CREATE GRAPH FROM A LIST OF TRIPLES List<RDFTriple> triples = new List<RDFTriple>({mickeymouse_is85yr, donaldduck_name_enus}); RDFGraph waltdisney_filled = new RDFGraph(triples);

The "Context" property is an URI for declaring the Web provenance of the graph data:

// SET CONTEXT OF A GRAPH waltdisney.Context = new Uri("http://waltdisney.com/");

If not specified, it assumes the value of the "DefaultNamespace" static property of the

RDFNamespaceRegister class (which will be discussed in the next paragraphs).

A graph can be easily transformed into an ADO.NET datatable with "Subject-Predicate-

Object" columns through the ToDataTable method, but can also be obtained back

through the static RDFGraph.FromDataTable method:

// GET A DATATABLE FROM A GRAPH DataTable waltdisney_table = waltdisney.ToDataTable(); // GET A GRAPH FROM A DATATABLE RDFGraph waltdisney_new = RDFGraph.FromDataTable(waltdisney_table);

RDFGraph is compatible with IEnumerable<RDFTriple>:

// ITERATE TRIPLES OF A GRAPH WITH FOREACH foreach (RDFTriple t in waltdisney) { Console.Writeline("Triple: " + t); Console.Writeline(" Subject: " + t.Subject); Console.Writeline(" Predicate: " + t.Predicate); Console.Writeline(" Object: " + t.Object); } // ITERATE TRIPLES OF A GRAPH WITH ENUMERATOR var triplesEnum = waltdisney.TriplesEnumerator; while (triplesEnum.MoveNext()) { Console.Writeline("Triple: " + triplesEnum.Current); Console.Writeline(" Subject: " + triplesEnum.Current.Subject); Console.Writeline(" Predicate: " + triplesEnum.Current.Predicate); Console.Writeline(" Object: " + triplesEnum.Current.Object); }

The "TriplesCount" property represents the number of triples contained in the graph:

// GET COUNT OF TRIPLES CONTAINED IN A GRAPH Int64 triplesCount = waltdisney.TriplesCount;

Page 6: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

6

There are several ways to manage the collection of triples of a graph:

INSERT AddTriple

Adds the given triple. waltdisney.AddTriple(mickeymouse_is85yr);

DELETE

RemoveTriple

Removes the given triple. waltdisney.RemoveTriple(donaldduck_name_enus);

RemoveTriplesBySubject

Removes the triples having the

given resource as "Subject".

waltdisney.RemoveTriplesBySubject(donaldduck);

RemoveTriplesByPredicate

Removes the triples having the

given resource as "Predicate".

waltdisney.RemoveTriplesByPredicate(new

RDFResource("http://xmlns.com/foaf/0.1/age"));

RemoveTriplesByObject

Removes the triples having the

given resource as "Object".

waltdisney.RemoveTriplesByObject(goofygoof);

RemoveTriplesByLiteral

Removes the triples having the

given literal as "Object".

waltdisney.RemoveTriplesByLiteral(

mickeymouse_age);

ClearTriples

Empties the graph. waltdisney.ClearTriples();

SEARCH

ContainsTriple

Checks if the given triple exists

in the graph, returning

True/False.

Boolean checkTriple =

waltdisney.ContainsTriple(mickeymouse_is85yr);

SelectTriplesBySubject

Returns a graph containing the

triples having the given

resource as "Subject".

RDFGraph triples_by_subject =

waltdisney.SelectTriplesBySubject(donaldduck);

Page 7: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

7

SelectTriplesByPredicate

Returns a graph containing the

triples having the given

resource as "Predicate".

RDFGraph triples_by_predicate =

waltdisney.SelectTriplesByPredicate(new

RDFResource("http://xmlns.com/foaf/0.1/name");

SelectTriplesByObject

Returns a graph containing the

triples having the given

resource as "Object".

RDFGraph triples_by_object =

waltdisney.SelectTriplesByObject(goofygoof);

SelectTriplesByLiteral

Returns a graph containing the

triples having the given literal

as "Object".

RDFGraph triples_by_literal =

waltdisney.SelectTriplesByLiteral(

mickeymouse_age);

SET

IntersectWith

Returns a graph containing the

triples found both in this graph

and in the given one.

RDFGraph intersection_triples =

waltdisney.IntersectWith(waltdisney_filled);

UnionWith

Returns a graph containing the

triples of this graph and the

given one.

RDFGraph union_triples =

waltdisney.UnionWith(waltdisney_filled);

DifferenceWith

Returns a graph containing the

triples of this graph which are

not found in the given one.

RDFGraph difference_triples =

waltdisney.DifferenceWith(waltdisney_filled);

Page 8: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

8

Graph operations are fluent, so they can be composed to achieve more complex tasks:

// COMPOSE MULTIPLE SELECTIONS RDFGraph triples_by_subject_and_predicate = waltdisney.SelectTriplesBySubject(donaldduck) .SelectTriplesByPredicate(new RDFResource("http://xmlns.com/foaf/0.1/name")); // ADVANCED SET ALGEBRAS RDFGraph intersection_then_union = waltdisney.IntersectWith(waltdisney_filled) .UnionWith(another_graph);

The content of a graph can be read from or saved to a RDF file with the RDFSerializer

class, which supports the following official W3C serialization formats:

Format Read Write

NTRIPLES YES YES

// READ NTRIPLES FILE RDFGraph graph = RDFSerializer.ReadRDF( RDFModelEnums.RDFSyntaxes.NTriples, "C:\\file.nt"); // WRITE NTRIPLES FILE RDFSerializer.WriteRDF( RDFModelEnums.RDFSyntaxes.NTriples, graph, "C:\\newfile.nt");

TRIX YES YES

// READ TRIX FILE RDFGraph graph = RDFSerializer.ReadRDF( RDFModelEnums.RDFSyntaxes.TriX, "C:\\file.trix"); // WRITE TRIX FILE RDFSerializer.WriteRDF( RDFModelEnums.RDFSyntaxes.TriX, graph, "C:\\newfile.trix");

TURTLE NO YES

// WRITE TURTLE FILE RDFSerializer.WriteRDF( RDFModelEnums.RDFSyntaxes.Turtle, graph, "C:\\newfile.ttl");

RDF/XML YES * YES

// READ XML FILE RDFGraph graph = RDFSerializer.ReadRDF( RDFModelEnums.RDFSyntaxes.RdfXml, "C:\\file.rdf"); // WRITE XML FILE RDFSerializer.WriteRDF( RDFModelEnums.RDFSyntaxes.RdfXml, graph, "C:\\newfile.rdf");

* RDF/XML reader does not support the messy and controversial RDF striped syntax,

so nested resource descriptions (apart containers and collections) are ignored. For this

reason, please ensure your input RDF/XML file has canonical resource descriptions:

<rdf:Description rdf:about="http://www.waltdisney.com/donald_duck">

<foaf:name xml:lang="en-US">Donald Duck</foaf:name>

<rdf:type rdf:about="http://www.waltdisney.com/character" />

</rdf:Description>

Page 9: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

9

WORKING WITH NAMESPACES, DATATYPES AND VOCABULARIES

A namespace is an URI with an associated mnemonic prefix, modeled as instance of

RDFNamespace. It can be used to speed up the creation of resources and also for

shortcutting URIs when serializing RDF data into a W3C format like RDF/XML or Turtle:

// CREATE NAMESPACE RDFNamespace waltdisney_ns = new RDFNamespace("wd", "http://www.waltdisney.com/"); // USE NAMESPACE IN RESOURCE CREATION RDFResource duckburg = new RDFResource(waltdisney_ns + "duckburg"); RDFResource mouseton = new RDFResource(waltdisney_ns + "mouseton");

Several namespaces are supported by default:

DBPEDIA http://dbpedia.org/

DC http://purl.org/dc/elements/1.1/

FOAF http://xmlns.com/foaf/0.1/

GEO http://www.w3.org/2003/01/geo/wgs84_pos#

OG http://ogp.me/ns#

OWL http://www.w3.org/2002/07/owl#

RDF http://www.w3.org/1999/02/22-rdf-syntax-ns#

RDFS http://www.w3.org/2000/01/rdf-schema#

SKOS http://www.w3.org/2004/02/skos/core#

XML http://www.w3.org/XML/1998/namespace#

XSD http://www.w3.org/2001/XMLSchema#

Page 10: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

10

Namespaces are collected in a special class named RDFNamespaceRegister, which

represents a singleton in-memory register for storing the most common namespaces.

There are several ways to manage the collection of namespaces of this register:

INSERT

AddNamespace

Adds the given

namespace.

RDFNamespaceRegister.AddNamespace(waltdisney_ns);

DELETE

RemoveNamespace

Removes the given

namespace, but only if it’s

not the actual default

namespace.

RDFNamespaceRegister.RemoveNamespace(waltdisney_ns);

SEARCH

ContainsNamespace

Checks if the register

contains an entry with the

given prefix or namespace.

Boolean namespace_found = RDFNamespaceRegister.ContainsNamespace(waltdisney_ns);

GetByNamespace

Retrieves a namespace by

seeking presence of its

URI. Returns null in case

not found.

RDFNamespace retrieved_namespace = RDFNamespaceRegister.GetByNamespace( "http://dbpedia.org");

GetByPrefix

Retrieves a namespace by

seeking presence of its

prefix. Returns null in case

not found.

RDFNamespace retrieved_namespace = RDFNamespaceRegister.GetByPrefix("dbpedia");

Page 11: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

11

The namespace register has a static property called "DefaultNamespace" which

represents the namespace adopted for graphs not specifying their "Context" property:

// GET DEFAULT NAMESPACE RDFNamespace nSpace = RDFNamespaceRegister.DefaultNamespace; // SET DEFAULT NAMESPACE RDFNamespaceRegister.SetDefaultNamespace(waltdisney_ns); //new graphs will default to this context

RDFNamespaceRegister is compatible with IEnumerable<RDFNamespace>:

// ITERATE NAMESPACES OF REGISTER WITH FOREACH foreach (RDFNamespace ns in RDFNamespaceRegister.Instance) { Console.Writeline("Prefix: " + ns.Prefix); Console.Writeline("Namespace: " + ns.Namespace); } // ITERATE NAMESPACES OF REGISTER WITH ENUMERATOR var nspacesEnum = RDFNamespaceRegister.NamespacesEnumerator; while (nspacesEnum.MoveNext()) { Console.Writeline("Prefix: " + nspacesEnum.Current.Prefix); Console.Writeline("Namespace: " + nspacesEnum.Current.Namespace); }

Each of the predefined namespaces supported by the library has a corresponding

vocabulary in the RDFVocabulary helper class, which can be used as a grammatical

assistant for simplifying the composition of triples needing usage of standard terms:

// CREATE TRIPLES WITH VOCABULARY FACILITIES // "Goofy Goof is 82 years old" RDFTriple goofygoof_is82yr = new RDFTriple( goofygoof, RDFVocabulary.FOAF.AGE, new RDFPlainLiteral("82") ); // "Donald Duck knows Goofy Goof" RDFTriple donaldduck_knows_goofygoof = new RDFTriple( donaldduck, RDFVocabulary.FOAF.KNOWS, goofygoof );

Page 12: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

12

A datatype represents an extension of the namespace concept and it is used to tie

values of a literal to a certain semantic category, modeled as instance of RDFDatatype:

// CREATE DATATYPE RDFDatatype waltdisney_city = new RDFDatatype("wd", "http://www.waltdisney.com/", "city", RDFModelEnums.RDFDatatypeCategory.String); RDFDatatype uk_pound = new RDFDatatype("ukp", "http://worldmoneys.com/uk#", "pound", RDFModelEnums.RDFDatatypeCategory.Numeric); // USE DATATYPE IN LITERAL CREATION // "duckburg"^^<http://www.waltdisney.com/city> RDFTypedLiteral duckburg_city = new RDFTypedLiteral("duckburg", waltdisney_city); // "112.95"^^<http://www.worldmoneys.com/uk#pound> RDFTypedLiteral fly_price = new RDFTypedLiteral("112.95", uk_pound);

RDFSharp defines 5 categories against which the value of a typed literal is strictly

validated during creation, throwing a RDFModelException in case of validation failure:

BOOLEAN Requires literal data to be a valid BOOLEAN (True / False)

NUMERIC Requires literal data to be a valid NUMBER (XSD datatypes are further

validated against specific Numeric subcases)

DATETIME Requires literal data to be a valid DATE (XSD datatypes are further

validated against specific Date subcases)

TIMESPAN Requires literal data to be a valid DURATION (XSD datatypes are

further validated against specific Duration subcases)

STRING Requires literal data to be a valid STRING (XSD datatypes are further

validated against specific String subcases)

This way, typed literals have always a consistent value against their declared category.

XSD datatypes have been standardized by W3C: most of the times, rather than creating

a new datatype from scratch, you will choose XSD ones more suitable to your purposes:

// CREATE TYPED LITERALS RDFTypedLiteral one_int = new RDFTypedLiteral("1", RDFDatatypeRegister.GetByPrefixAndDatatype("xsd", "int")); RDFTypedLiteral one_float = new RDFTypedLiteral("1.00", RDFDatatypeRegister.GetByPrefixAndDatatype("xsd", "float")); RDFTypedLiteral today = new RDFTypedLiteral("2014-07-06", RDFDatatypeRegister.GetByPrefixAndDatatype("xsd", "date"));

Page 13: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

13

Datatypes are collected in a special class named RDFDatatypeRegister, which

represents a singleton in-memory register for storing the most common datatypes.

There are several ways to manage the collection of datatypes of this register:

INSERT

AddDatatype

Adds the given datatype. RDFDatatypeRegister.AddDatatype(uk_pound);

DELETE

RemoveDatatype

Removes the given datatype. RDFDatatypeRegister.RemoveDatatype(uk_pound);

SEARCH

ContainsDatatype

Checks if the register contains

an entry with the given prefix

(or namespace) and datatype.

Boolean datatype_found = RDFDatatypeRegister.ContainsDatatype(uk_pound);

GetByNamespaceAndDatatype

Retrieves a datatype by seeking

presence of its namespace and

datatype. Returns null in case

not found.

RDFDatatype retrieved_datatype = RDFDatatypeRegister.GetByNamespaceAndDatatype( "http://worldmoneys.com/uk#", "pound");

GetByPrefixAndDatatype

Retrieves a datatype by seeking

presence of its prefix and

datatype. Returns null in case

not found.

RDFDatatype retrieved_datatype = RDFDatatypeRegister.GetByPrefixAndDatatype( "ukp", "pound");

RDFDatatypeRegister is compatible with IEnumerable<RDFDatatype>:

// ITERATE DATATYPES OF REGISTER WITH FOREACH foreach (RDFDatatype dt in RDFDatatypeRegister.Instance) { Console.Writeline("Prefix: " + dt.Prefix); Console.Writeline("Namespace: " + dt.Namespace); Console.Writeline("Datatype: " + dt.Datatype); Console.Writeline("Category: " + dt.Category); }

Page 14: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

14

WORKING WITH CONTAINERS AND COLLECTIONS

The RDF specification provides 2 ways for modeling a group of homogeneous items

into a single entity, demanding the choice to a subtle semantic distinction:

Container

It is modeled as instance of RDFContainer;

Given list of items may be incomplete: a container is semantically

opened to the possibility of further elements being part of it;

The "ContainerType" property indicates the nature of the container:

� Alt: unordered list, no duplicates allowed; � Bag: unordered list, duplicates allowed; � Seq: ordered list, duplicates allowed;

The "ItemType" property indicates the nature of the container items;

// CREATE CONTAINER RDFContainer beatles_cont = new RDFContainer( RDFModelEnums.RDFContainerTypes.Bag, RDFModelEnums.RDFItemTypes.Resource ); // CREATE CONTAINER FROM A LIST OF ITEMS ArrayList beatles_components = new ArrayList(); beatles_components.Add(new RDFResource("http://beatles.com/ringo_starr")); beatles_components.Add(new RDFResource("http://beatles.com/john_lennon")); RDFContainer beatles_cont_filled = new RDFContainer( RDFModelEnums.RDFContainerTypes.Bag, RDFModelEnums.RDFItemTypes.Resource, beatles_components );

Collection

It is modeled as instance of RDFCollection;

Given list of items may not be incomplete: a collection is semantically

closed to the possibility of further elements being part of it;

The "ItemType" property indicates the nature of the collection items;

// CREATE COLLECTION RDFCollection beatles_coll = new RDFCollection( RDFModelEnums.RDFItemTypes.Resource ); // CREATE COLLECTION FROM A LIST OF ITEMS ArrayList beatles_components = new ArrayList(); beatles_components.Add(new RDFResource("http://beatles.com/ringo_starr")); beatles_components.Add(new RDFResource("http://beatles.com/john_lennon")); beatles_components.Add(new RDFResource("http://beatles.com/paul_mc_cartney")); beatles_components.Add(new RDFResource("http://beatles.com/george_harrison")); RDFCollection beatles_coll_filled = new RDFCollection( RDFModelEnums.RDFItemTypes.Resource, beatles_components );

Important: items must respect the type specified by the "ItemType" property, so they

must be all resources or all literals otherwise a RDFModelException will be thrown.

Page 15: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

15

RDFContainer and RDFCollection are compatible with IEnumerable:

// ITERATE ITEMS OF A CONTAINER WITH FOREACH foreach (Object item in beatles_cont) { Console.Writeline("Container Item: " + item); } // ITERATE ITEMS OF A COLLECTION WITH FOREACH foreach (Object item in beatles_coll) { Console.Writeline("Collection Item: " + item); }

There are several ways to manage the collection of items of a container or collection:

INSERT AddItem

Adds the given item.

beatles_cont.AddItem(ringo_starr");

beatles_coll.AddItem(ringo_starr);

DELETE

RemoveItem

Removes the given item.

beatles_cont.RemoveItem(ringo_starr);

beatles_coll.RemoveItem(ringo_starr);

ClearItems

Empties the container / collection.

beatles_cont.ClearItems();

beatles_coll.ClearItems();

Containers and collections can be directly added to a graph. This represents the fastest

and most convenient modeling use case:

// ADD CONTAINER TO GRAPH waltdisney.AddContainer(beatles_cont); // ADD COLLECTION TO GRAPH waltdisney.AddCollection(beatles_coll);

Page 16: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

16

THE PROBLEM OF REIFICATION

Reification in the RDF model is the assertion of knowledge about existing knowledge

and is mainly used for giving credits or specifying provenance of a triple.

It is implemented in a way that makes use of a "ReificationSubject" blank resource acting

as representative of the triple; then, 4 standard statements are created with that

subject to explode the triple into its elementary components; finally, the asserted

knowledge can be linked to the triple by using its representative as object.

"Walt Disney says that Donald Duck represents its funniest character”

Subject Predicate Object

bnode:ee56… rdf:type rdf:Statement

bnode:ee56… rdf:subject wd:donald_duck

bnode:ee56… rdf:predicate ex:verb_represent

bnode:ee56… rdf:object ex:funniest_character

wd:waltdisney ex:verb_say bnode:ee56…

With RDFSharp it is possible to reify triples, quadruples, containers and collections:

// REIFY TRIPLE AND MERGE IT INTO A GRAPH RDFGraph reifGraph = goofygoof_is82yr.ReifyTriple(); waltdisney = waltdisney.UnionWith(reifGraph); // ASSERT SOMETHING ABOUT REIFIED TRIPLE waltdisney.AddTriple(new RDFTriple( new RDFResource("http://www.wikipedia.com/"), new RDFResource("http://example.org/verb_state"), goofygoof_is82yr.ReificationSubject )); // REIFY CONTAINER existingGraph.AddContainer(beatles_cont); existingGraph.AddTriple(new RDFTriple( new RDFResource("http://www.thebeatles.com/"), RDFVocabulary.FOAF.GROUP, beatles_cont.ReificationSubject )); // REIFY COLLECTION existingGraph.AddCollection(beatles_coll); existingGraph.AddTriple(new RDFTriple( new RDFResource("http://www.thebeatles.com/"), RDFVocabulary.FOAF.GROUP, beatles_coll.ReificationSubject ));

Page 17: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

17

WORKING WITH RDF STORES

TRACKING PROVENANCE OF RDF DATA WITH CONTEXTS AND QUADRUPLES

When working with RDF data, the information is usually made up of graphs dislocated

in the worldwide "Linked Data" network. Such a huge amount of available data requires

a structured way to track provenance of statements, because the same triple may

probably exist into multiple graphs.

In the depicted scenario, the solution provided by RDFSharp is to extend the traditional

"Subject-Predicate-Object" triple structure with an additional URI-based dimension called

"Context", modeled as instance of RDFContext:

// CREATE CONTEXT FROM STRING RDFContext wdisney_ctx = new RDFContext("http://www.waltdisney.com/"); // CREATE CONTEXT FROM URI RDFContext wdisney_ctx_uri = new RDFContext(new Uri("http://www.waltdisney.com/")); // CREATE DEFAULT CONTEXT RDFContext wdisney_ctx_default = new RDFContext();

This way a triple enriched with context becomes a quadruple, assuming a

"Context-Subject-Predicate-Object" structure modeled as instance of RDFQuadruple:

// CREATE QUADRUPLES // "From Wikipedia.com: Mickey Mouse is 85 years old" RDFQuadruple wk_mickeymouse_is85yr = new RDFQuadruple( new RDFContext("http://www.wikipedia.com/"), new RDFResource("http://www.waltdisney.com/mickey_mouse"), new RDFResource("http://xmlns.com/foaf/0.1/age"), mickeymouse_age ); // "From WaltDisney.com: Mickey Mouse is 85 years old" RDFQuadruple wd_mickeymouse_is85yr = new RDFQuadruple( wdisney_ctx, new RDFResource("http://www.waltdisney.com/mickey_mouse"), new RDFResource("http://xmlns.com/foaf/0.1/age"), mickeymouse_age ); // "From Wikipedia.com: Donald Duck has English-US name "Donald Duck"" RDFQuadruple wk_donald_duck_name_enus = new RDFQuadruple( new RDFContext("http://www.wikipedia.com/"), donaldduck, new RDFResource("http://xmlns.com/foaf/0.1/name"), donaldduck_name_enus );

Important: when creating a quadruple, validation against presence of a blank resource

in the predicate position occurs, throwing a RDFStoreException in case of detection.

Page 18: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

18

CREATING AND MANIPULATING STORES

Thinking of a store as a natural extension of a graph obtained by introducing the

context awareness of triples, we can straightforwardly define a store as a collection of

quadruples, modeled as concrete implementation of the abstract RDFStore class.

There are several ways to manage the collection of quadruples of a store:

INSERT

AddQuadruple

Adds the given quadruple.

wdStore.AddQuadruple(

wk_mickeymouse_is85yr);

MergeGraph

Adds the triples of the given graph, which

are transformed into quadruples having

the context of the graph.

wdStore.MergeGraph(waltdisney);

DELETE

RemoveQuadruple

Removes the given quadruple.

wdStore.RemoveQuadruple(

wk_mickeymouse_is85yr);

RemoveQuadruplesByContext

Removes the quadruples having the given

context as "Context".

wdStore.RemoveQuadruplesByContext(

wdisney_ctx);

RemoveQuadruplesBySubject

Removes the quadruples having the given

resource as "Subject".

wdStore.RemoveQuadruplesBySubject(

donaldduck);

RemoveQuadruplesByPredicate

Removes the quadruples having the given

resource as "Predicate".

wdStore.RemoveQuadruplesByPredicate

(RDFVocabulary.FOAF.NAME);

RemoveQuadruplesByObject

Removes the quadruples having the given

resource as "Object".

wdStore.RemoveQuadruplesByObject(

goofygoof);

RemoveQuadruplesByLiteral

Removes the quadruples having the given

literal as "Object".

wdStore.RemoveQuadruplesByLiteral(

mickeymouse_age);

Page 19: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

19

ClearQuadruples

Empties the store. wdStore.ClearQuadruples();

SEARCH

ContainsQuadruple

Checks if the given quadruple exists in the

store, returning True/False.

Boolean checkQuadruple =

wdStore.ContainsQuadruple(

wk_mickeymouse_is85yr);

SelectAllQuadruples

Returns a store containing all the

quadruples.

RDFStore all_quadruples =

wdStore.SelectAllQuadruples();

SelectQuadruplesByContext

Returns a store containing the quadruples

having the given context as "Context".

RDFStore quadruples_by_context =

wdStore.SelectQuadruplesByContext(

wdisney_ctx);

SelectQuadruplesBySubject

Returns a store containing the quadruples

having the given resource as "Subject".

RDFStore quadruples_by_subject =

wdStore.SelectQuadruplesBySubject(

donaldduck);

SelectQuadruplesByPredicate

Returns a store containing the quadruples

having the given resource as "Predicate".

RDFStore quadruples_by_predicate =

wdStore.SelectQuadruplesByPredicate

(RDFVocabulary.FOAF.NAME);

SelectQuadruplesByObject

Returns a store containing the quadruples

having the given resource as "Object".

RDFStore quadruples_by_object =

wdStore.SelectQuadruplesByObject(

goofygoof);

SelectQuadruplesByLiteral

Returns a store containing the quadruples

having the given literal as "Object".

RDFStore quadruples_by_literal =

wdStore.SelectQuadruplesByLiteral(

mickeymouse_age);

Page 20: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

20

RDFSharp provides an in-memory RDF store engine implementation which behaves likes

a graph, modeled as instance of RDFMemoryStore:

// CREATE EMPTY MEMORY STORE RDFMemoryStore wdStore = new RDFMemoryStore(); // CREATE MEMORY STORE FROM A LIST OF QUADRUPLES List<RDFQuadruple> quadruples = new List<RDFQuadruple>( {wk_mickeymouse_is85yr, wk_mickeymouse_is85yr, wk_donaldduck_name_enus }); RDFMemoryStore wdStoreFilled = new RDFMemoryStore(quadruples);

A memory store can be easily transformed into an ADO.NET datatable with "Context-

Subject-Predicate-Object" columns through the ToDataTable method, but can also be

obtained back through the static RDFMemoryStore.FromDataTable method:

// GET A DATATABLE FROM A MEMORY STORE DataTable wdStore_table = wdStore.ToDataTable(); // GET A MEMORY STORE FROM A DATATABLE RDFMemoryStore wdStore_new = RDFMemoryStore.FromDataTable(wdStore_table);

RDFMemoryStore is compatible with the IEnumerable<RDFQuadruple>:

// ITERATE TRIPLES OF A MEMORY STORE WITH FOREACH foreach (RDFQuadruple q in wdStore) { Console.Writeline("Quadruple: " + q); Console.Writeline(" Context: " + q.Context); Console.Writeline(" Subject: " + q.Subject); Console.Writeline(" Predicate: " + q.Predicate); Console.Writeline(" Object: " + q.Object); }

Memory stores can be combined through set operations, like graphs:

SET

IntersectWith

Returns a store containing the quadruples which

are found both in this store and in the given one.

RDFStore intersection_store =

wdStore.IntersectWith(store);

UnionWith

Returns a store containing the quadruples of this

store and the given one.

RDFStore union_store =

wdStore.UnionWith(store);

DifferenceWith

Returns a store containing the quadruples of this

store which are not found in the given one.

RDFStore difference_store =

wdStore.DifferenceWith(store);

Page 21: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

21

BACKING STORES ON SQL ENGINES

While there are no restrictions to the number of quadruples which can be contained in a

memory store, apart the physical memory limits of the machine, it is reasonable to think

about a more scalable approach for persisting growing amounts of RDF data.

RDFSharp provides 4 SQL-based RDF store engine implementations by wrapping each

vendor-specific .NET driver around a little facade assembly exposed under the

"RDFSharp.Store" namespace. This way it is sufficient to reference the desired assembly

for automatically gaining support for backing RDF data on the selected underlying

technology (Firebird, MySQL, SQLite, SQL Server).

The SQL schema has been designed for unobtrusive integration into existing databases,

exploiting the internal high-performance INT64 hashing engine codenamed "Greta". A

table called "Quadruples" is created with the following flattened structure:

QuadrupleID PRIMARY KEY, INT64, INDEXED, NOT NULL

TripleFlavor INT32, INDEXED, NOT NULL

Context VARCHAR(1000), NOT NULL

ContextID INT64, INDEXED, NOT NULL

Subject VARCHAR(1000), NOT NULL

SubjectID INT64, INDEXED, NOT NULL

Predicate VARCHAR(1000), NOT NULL

PredicateID INT64, INDEXED, NOT NULL

Object VARCHAR(5000), NOT NULL

ObjectID INT64, INDEXED, NOT NULL

Page 22: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

22

SQLite RDF store implementation is available through the RDFSQLiteStore class. A

SQLite database consists of a file with a conventional ".db" extension which must be

available in the filesystem of the running application. If the given path does not exist,

the library will automatically create a new file by cloning an internal template database.

If the "Quadruples" table is not detected in the database during preliminary connection

checks, the library will automatically create it by executing an internal script. No

authentication is needed to connect to SQLite database.

// CREATE SQLITE STORE var sqlite = new RDFSQLiteStore("C:\\directory\\waltdisney.db");

Firebird RDF store implementation is available through the RDFFirebirdStore class. A

Firebird database consists of a file with a conventional ".fdb" extension which must be

available in the filesystem of the running application. An instance of Firebird must be up

and running at the specified address. If the given path does not exist, the library will

automatically create a new file by cloning an internal template database. If the

"Quadruples" table is not detected in the database during preliminary connection

checks, the library will automatically create it by executing an internal script.

Authentication uses the default "SYSDBA" user and "masterkey" password.

// CREATE FIREBIRD STORE ON LOCAL INSTANCE var firebird = new RDFFirebirdStore("C:\\directory\\waltdisney.fdb"); //Seeks local instance // CREATE FIREBIRD STORE ON REMOTE INSTANCE var firebird = new RDFFirebirdStore("\\firebird_instance", "F:\\shared\\waltdisney.fdb");

SQL Server RDF store implementation is available through the RDFSQLServerStore

class. An instance of SQL Server must be up and running at the specified address and

the given database must exist on it. If the "Quadruples" table is not detected in the

database during preliminary connection checks, the library will automatically create it

by executing an internal script. Authentication uses "Windows Integrated Security", so

you should ensure to have required permission accesses to the indicated database.

// CREATE SQLSERVER STORE ON LOCAL SQLEXPRESS INSTANCE var sqlServer = new RDFSQLServerStore("waltdisney");//Seeks local "SQLEXPRESS" instance // CREATE SQLSERVER STORE ON REMOTE INSTANCE var sqlServer = new RDFSQLServerStore("\\sqlserver_instance", "waltdisney");

MySQL RDF store implementation is available through the RDFMySQLStore class. An

instance of MySQL must be up and running at the specified address and the given

database must exist on it. If the "Quadruples" table is not detected in the database

during preliminary connection checks, the library will automatically create it by

executing an internal script. Authentication uses the given username and password.

// CREATE MYSQL STORE ON LOCAL INSTANCE var mysql = new RDFMySQLStore("waltdisney", "root", "root"); //Seeks local instance // CREATE MYSQL STORE ON REMOTE INSTANCE var mysql = new RDFMySQLStore("\\mysql_instance", "waltdisney", "root", "root");

Page 23: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

23

CREATING AND MANIPULATING FEDERATIONS

A federation is a collection of stores, modeled as instance of RDFFederation:

// CREATE EMPTY FEDERATION RDFFederation fed = new RDFFederation(); // CREATE FEDERATION FROM A LIST OF STORES List<RDFStore> stores = new List<RDFStore>({waltDisneyStore, waltDisneyStoreFilled}); RDFFederation fedFilled = new RDFFederation(stores);

RDFFederation is compatible with the IEnumerable<RDFStore>:

// ITERATE STORES OF A FEDERATION foreach (RDFStore s in fed) { Console.Writeline("Store: " + s); Console.Writeline(" Type: " + s.StoreType); }

There are several ways to manage the collection of stores of a federation:

INSERT AddStore

Adds the given store. fed.AddStore(wdStore);

DELETE

RemoveStore

Removes the given store. fed.RemoveStore(wdStore);

ClearStores

Empties the federation. fed.ClearStores();

The power of federations is their ability to hide underlying stores by exposing them as a

tightly integrated virtual store, on which it is possible to execute SPARQL queries:

Page 24: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

24

WORKING WITH SPARQL QUERIES

BASICS OF MIRELLA QUERY ENGINE: VARIABLE, PATTERN, PATTERN GROUP

RDFSharp provides a fluent SPARQL engine, codenamed "Mirella", which allows creation

and execution of queries over graphs, stores and federations. It has been designed on

top of the following basic concepts: variables, patterns and pattern groups.

A variable is a placeholder for query results, modeled as instance of RDFVariable:

// CREATE VARIABLE RDFVariable x = new RDFVariable("x", true); // ?X RDFVariable y = new RDFVariable("y", true); // ?Y RDFVariable n = new RDFVariable("n", false); // ?N (don’t show in SELECT results)

The flag in the constructor represents the projection operator, which is only considered

by SPARQL Select queries, and indicates presence of the variable column in the results.

A pattern is a triple which can include variables, modeled as instance of RDFPattern:

// CREATE PATTERNS RDFResource dogOf = new RDFResource(RDFVocabulary.DC.BASE_URI + "dogOf"); RDFPattern y_dogOf_x = new RDFPattern(y, dogOf, x); // TRIPLE PATTERN RDFPattern n_y_dogOf_x = new RDFPattern(n, y, dogOf, x); // QUADRUPLE PATTERN

It can also represent a quadruple, if the context information is provided. Elements

which can be part of a pattern are resources, literals, contexts and variables: these are

concrete implementations of the abstract RDFPatternMember class.

A pattern group is a collection of patterns, modeled as instance of RDFPatternGroup:

// CREATE EMPTY PATTERN GROUP RDFPatternGroup pg1 = new RDFPatternGroup("PG1"); // CREATE PATTERN GROUP FROM A LIST OF PATTERNS List<RDFPattern> patterns = new List<RDFPattern>(){ y_dogOf_x }; RDFPatternGroup pg2 = new RDFPatternGroup("PG2", patterns);

Within a query, each pattern group is identified by its "PatternGroupName" property.

Patterns can be added to a pattern group through the AddPattern method:

// ADD PATTERNS TO PATTERN GROUP pg1.AddPattern(y_dogOf_x);

Pattern groups can be added to a query through the AddPatternGroup method:

// ADD PATTERN GROUPS TO QUERY query.AddPatternGroup(pg1);

Page 25: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

25

When a pattern is evaluated, the query engine produces a table having the detected

variables as columns: the pattern acts as a scanner which passes over the triples by

checking if they satisfy the represented condition, then every time that matching data is

found it creates a new row and fills in-place variables. The algorithm is iterated until all

the patterns contained in the pattern group have been processed.

The intermediate pattern tables are then merged into a unique pattern group table:

default strategy is INNER-JOIN, or PRODUCT-JOIN in case no common columns found,

but special operators may be locally applied on patterns to induce a different approach:

Optional

LEFT-OUTER-JOIN will be used to

keep unbound values generated

by join failures.

y_dogOf_x.Optional();

UnionWithNext UNION will be used to preserve all

generated solutions. y_dogOf_x.UnionWithNext();

When the pattern group table has been produced, the filters contained in the pattern

group are subsequently applied, restricting available solutions.

The algorithm is then replicated on remaining pattern groups, until all corresponding

tables have been produced: at this stage of query evaluation, the same considerations

done for pattern joins are also suitable for pattern group joins (merge strategy and

special local operators) until a unique query results table is produced.

At last, the modifiers contained in the query are applied on the results table, inducing

eventual data sorts or cardinality operations. Depending on the type of modeled query,

there may be further specific elaborations in order to produce the final query result.

Page 26: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

26

BASICS OF MIRELLA QUERY ENGINE: FILTER, MODIFIER

Filters are elementary mechanisms which can be used to keep only rows which satisfy a

given condition, modeled as concrete implementations of the abstract RDFFilter class.

At the moment, RDFSharp provides support for 13 built-in SPARQL filters:

Modeling Class Description

RDFBooleanAndFilter

Keeps rows which

satisfy both provided

filters.

RDFBooleanAndFilter andFilter = new

RDFBooleanAndFilter(leftFilter,

rightFilter);

RDFBooleanNotFilter

Keeps rows which do

not satisfy provided

filter.

RDFBooleanNotFilter notFilter = new

RDFBooleanNotFilter(filter);

RDFBooleanOrFilter

Keeps rows which

satisfy at least one of

provided filters.

RDFBooleanOrFilter orFilter = new

RDFBooleanOrFilter(leftFilter,

rightFilter);

RDFBoundFilter

Keeps rows which

have a not null value

in provided column.

RDFBoundFilter boundFilter = new

RDFBoundFilter(variable);

RDFComparisonFilter

Keeps rows which

satisfy given type of

comparison between

provided RDF terms.

RDFComparisonFilter compFilter = new

RDFComparisonFilter(comparisonFlavor,

leftTerm, rightTerm);

RDFDatatypeFilter

Keeps rows which

have typed literal of

given datatype in

provided column.

RDFDatatypeFilter dtypeFilter = new

RDFDatatypeFilter(variable,

RDFDatatypeRegister.GetByPrefixAndDatatyp

e("xsd", "integer"));

RDFIsBlankFilter

Keeps rows which

have blank resource

in provided column.

RDFIsBlankFilter blankFilter = new

RDFIsBlankFilter(variable);

Page 27: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

27

RDFIsLiteralFilter

Keeps rows which

have literal in

provided column.

RDFIsLiteralFilter literalFilter = new

RDFIsLiteralFilter(variable);

RDFIsNumericFilter

Keeps rows which

have literal with

numeric value in

provided column.

RDFIsNumericFilter numericFilter = new

RDFIsNumericFilter(variable);

RDFIsUriFilter

Keeps rows which

have resource in

provided column.

RDFIsUriFilter uriFilter = new

RDFIsUriFilter(variable);

RDFLangMatchesFilter

Keeps rows which

have plain literal with

given language tag in

provided column.

RDFLangMatchesFilter langmatchesFilter =

new RDFLangMatchesFilter(variable,

languageTag);

RDFRegexFilter

Keeps rows which

have value satisfying

given regular

expression in

provided column.

RDFRegexFilter regexFilter = new

RDFRegexFilter(variable, regEx);

RDFSameTermFilter

Keeps rows which

have value equal to

given RDF term in

provided column.

RDFSameTermFilter sametermFilter = new

RDFSameTermFilter(variable, term);

Filters can be added (and scoped to) a pattern group through the AddFilter method:

// ADD FILTERS TO PATTERN GROUP pg1.AddFilter(new RDFSameTermFilter(x, donaldduck)); pg1.AddFilter(new RDFLangMatchesFilter(n, "it-IT")); pg1.AddFilter(new RDFComparisonFilter( RDFQueryEnums. RDFComparisonFlavors. LessThan, y, new RDFPlainLiteral("25"))); // ?Y < "25"

Page 28: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

28

Modifiers are elementary mechanisms which can be used to alter cardinality and order

of results, modeled as concrete implementations of the abstract RDFModifier class.

At the moment, RDFSharp provides support for 4 built-in SPARQL modifiers:

Modeling Class Description

RDFDistinctModifier

Eliminates duplicate rows.

Only one distinct modifier

is accepted in a query.

RDFDistinctModifier distModifier =

new RDFDistinctModifier();

RDFOrderByModifier

Sorts rows on provided

column. Multiple orderby

modifiers can be accepted

in a query.

RDFOrderByModifier orderbyModifier =

new RDFOrderByModifier(variable, orderType);

RDFLimitModifier

Keeps provided number of

rows. If 0 is specified, no

rows are kept. Only one

limit modifier is accepted

in a query.

RDFLimitModifier limitModifier = new

RDFLimitModifier(limit);

RDFOffsetModifier

Keeps rows starting from

provided position. If it is

greater than number of

available rows, no rows

are kept. Only one offset

modifier is accepted in a

query.

RDFOffsetModifier offsetModifier = new RDFOffsetModifier(offset);

Modifiers can be added to a query through the AddModifier method:

// ADD MODIFIERS TO QUERY query.AddModifier(new RDFOrderByModifier(x, RDFQueryEnums.RDFOrderByFlavors.DESC)); query.AddModifier(new RDFOrderByModifier(n, RDFQueryEnums.RDFOrderByFlavors.ASC)); query.AddModifier(new RDFDistinctModifier()); query.AddModifier(new RDFLimitModifier(100)); query.AddModifier(new RDFOffsetModifier(25));

Page 29: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

29

CREATING AND EXECUTING SELECT QUERIES

SPARQL "Select" query type is modeled as instance of RDFSelectQuery:

// CREATE SELECT QUERY RDFSelectQuery selectQuery = new RDFSelectQuery();

This is the only SPARQL query type which supports the projection operator on results.

It is possible to apply a "Select" query on graphs, stores or federations, producing

results in form of tabular data modeled as instance of RDFSelectQueryResult:

// APPLY SELECT QUERY TO GRAPH RDFSelectQueryResult selectQueryResult = selectQuery.ApplyToGraph(graph); // APPLY SELECT QUERY TO STORE RDFSelectQueryResult selectQueryResult = selectQuery.ApplyToStore(store); // APPLY SELECT QUERY TO FEDERATION RDFSelectQueryResult selectQueryResult = selectQuery.ApplyToFederation(federation);

The "SelectResults" property is an ADO.NET datatable storing result variable bindings.

Let’s model a simple SPARQL "Select" query:

PREFIX dc: <http://purl.org/dc/elements/1.1/> . PREFIX foaf: <http://xmlns.com/foaf/0.1/> . SELECT ?Y ?X ?N WHERE { #PG1 { ?Y dc:dogOf ?X . OPTIONAL { ?X foaf:name ?N } . ?X foaf:knows ?H . FILTER ( REGEX(STR(?N), "Mouse", "i") ) . } } ORDER BY DESC(?Y) LIMIT 5 // Create Variables RDFVariable x = new RDFVariable("x", true); RDFVariable y = new RDFVariable("y", true); RDFVariable n = new RDFVariable("n", true); RDFVariable h = new RDFVariable("h", false); // do not show this variable in SELECT results // Fluently compose Select Query RDFSelectQuery q = new RDFSelectQuery() .AddPatternGroup(new RDFPatternGroup("PG1") .AddPattern(new RDFPattern(y, dogOf, x)) .AddPattern(new RDFPattern(x, name, n).Optional()) .AddPattern(new RDFPattern(x, knows, h)) .AddFilter(new RDFRegexFilter(n, new Regex(@"Mouse", RegexOptions.IgnoreCase)))) .AddModifier(new RDFOrderByModifier(y, RDFQueryEnums.RDFOrderByFlavors.DESC)) .AddModifier(new RDFLimitModifier(5)); // Apply Select Query RDFSelectQueryResult selectResult = q.ApplyToGraph(waltdisney);

Page 30: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

30

CREATING AND EXECUTING ASK QUERIES

SPARQL "Ask" query type is modeled as instance of RDFAskQuery:

// CREATE ASK QUERY RDFAskQuery askQuery = new RDFAskQuery();

This is the only SPARQL query type which does not accept modifiers.

It is possible to apply an "Ask" query on graphs, stores or federations, producing results

in form of Boolean data modeled as instance of RDFAskQueryResult:

// APPLY ASK QUERY TO GRAPH RDFAskQueryResult askQueryResult = askQuery.ApplyToGraph(graph); // APPLY ASK QUERY TO STORE RDFAskQueryResult askQueryResult = askQuery.ApplyToStore(store); // APPLY ASK QUERY TO FEDERATION RDFAskQueryResult askQueryResult = askQuery.ApplyToFederation(federation);

The "AskResult" property is a Boolean storing query result.

Let’s model a simple SPARQL "Ask" query:

PREFIX dc: <http://purl.org/dc/elements/1.1/> . PREFIX foaf: <http://xmlns.com/foaf/0.1/> . ASK WHERE { #PG1 { ?Y dc:dogOf ?X . { ?X foaf:name ?N } UNION { ?X foaf:knows ?H } ?H dc:relation ?X . FILTER (?X = <http://waltdisney.com/donald_duck> ) . } }

// Create Variables RDFVariable x = new RDFVariable("x", true); // Projection Flag is irrelevant for Ask queries RDFVariable y = new RDFVariable("y", true); RDFVariable n = new RDFVariable("n", true); RDFVariable h = new RDFVariable("h", false); // Fluently compose Ask Query RDFAskQuery q = new RDFAskQuery() .AddPatternGroup(new RDFPatternGroup("PG1") .AddPattern(new RDFPattern(y, dogOf, x)) .AddPattern(new RDFPattern(x, name, n).UnionWithNext()) .AddPattern(new RDFPattern(x, knows, h)) .AddPattern(new RDFPattern(h, RDFVocabulary.DC.RELATION, x)) .AddFilter(new RDFComparisonFilter(RDFQueryEnums.RDFComparisonFlavors.EqualTo, x, donaldduck))))); // Apply Ask Query RDFAskQueryResult askResult = q.ApplyToGraph(waltdisney);

Page 31: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

31

CREATING AND EXECUTING CONSTRUCT QUERIES

SPARQL "Construct" query type is modeled as instance of RDFConstructQuery:

// CREATE CONSTRUCT QUERY RDFConstructQuery constructQuery = new RDFConstructQuery();

It is possible to apply a "Construct" query on graphs, stores or federations, producing

results in form of tabular data modeled as instance of RDFConstructQueryResult:

// APPLY CONSTRUCT QUERY TO GRAPH RDFConstructQueryResult constructQueryResult = constructQuery.ApplyToGraph(graph); // APPLY CONSTRUCT QUERY TO STORE RDFConstructQueryResult constructQueryResult = constructQuery.ApplyToStore(store); // APPLY CONSTRUCT QUERY TO FEDERATION RDFConstructQueryResult constructQueryResult = constructQuery.ApplyToFederation(federation);

The "ConstructResults" property is an ADO.NET datatable storing query results.

Let’s model a simple SPARQL "Construct" query:

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . PREFIX dc: <http://purl.org/dc/elements/1.1/> . PREFIX foaf: <http://xmlns.com/foaf/0.1/> . CONSTRUCT { ?Y rdf:type foaf:dog . } WHERE{ #PG1 { ?Y dc:dogOf ?X . OPTIONAL { ?X foaf:age ?N } . FILTER ( ?N >= "45.0" ) . } } LIMIT 10 // Create Variables RDFVariable x = new RDFVariable("x", true); // Projection Flag is irrelevant for Construct queries RDFVariable y = new RDFVariable("y", true); RDFVariable n = new RDFVariable("n", true); RDFVariable h = new RDFVariable("h", false); // Fluently compose Construct Query RDFConstructQuery q = new RDFConstructQuery() .AddPatternGroup(new RDFPatternGroup("PG1") .AddPattern(new RDFPattern(y, dogOf, x)) .AddPattern(new RDFPattern(x, age, n).Optional()) .AddFilter(new RDFComparisonFilter( RDFQueryEnums.RDFComparisonFlavors.GreaterOrEqualThan, n, new RDFPlainLiteral("45.0")))) .AddTemplate(new RDFPattern(y, RDFVocabulary.RDF.TYPE, dog)) .AddModifier(new RDFLimitModifier(10)); // Apply Construct Query RDFConstructQueryResult constructResult = q.ApplyToGraph(waltdisney);

Page 32: RDFSharp - Start playing with RDF!dadev.cloudapp.net/Datos Abiertos/PDF/ReferenceGuide.pdf · 3 INTRODUCTION HISTORY OF THE PROJECT RDFSharp is a lightweight C# framework which can

32

CREATING AND EXECUTING DESCRIBE QUERIES

SPARQL "Describe" query type is modeled as instance of RDFDescribeQuery:

// CREATE DESCRIBE QUERY RDFDescribeQuery describeQuery = new RDFDescribeQuery();

It is possible to apply a "Describe" query on graphs, stores or federations, producing

results in form of tabular data modeled as instance of RDFDescribeQueryResult:

// APPLY DESCRIBE QUERY TO GRAPH RDFDescribeQueryResult describeQueryResult = describeQuery.ApplyToGraph(graph); // APPLY DESCRIBE QUERY TO STORE RDFDescribeQueryResult describeQueryResult = describeQuery.ApplyToStore(store); // APPLY DESCRIBE QUERY TO FEDERATION RDFDescribeQueryResult describeQueryResult = describeQuery.ApplyToFederation(federation);

The "DescribeResults" property is an ADO.NET datatable storing query results.

Let’s model a simple SPARQL "Describe" query:

PREFIX dc: <http://purl.org/dc/elements/1.1/> . PREFIX foaf: <http://xmlns.com/foaf/0.1/> . DESCRIBE ?Y WHERE { #PG1 { ?Y dc:dogOf ?X . ?X foaf:name ?N . FILTER ( REGEX(STR(?N), "Mickey", "i") ) . } } LIMIT 20

// Create Variables RDFVariable x = new RDFVariable("x", true); // Projection Flag is irrelevant for Describe queries RDFVariable y = new RDFVariable("y", true); RDFVariable n = new RDFVariable("n", true); RDFVariable h = new RDFVariable("h", false); // Fluently compose Describe Query RDFDescribeQuery q = new RDFDescribeQuery() .AddPatternGroup(new RDFPatternGroup("PG1") .AddPattern(new RDFPattern(y, dogOf, x)) .AddPattern(new RDFPattern(x, name, n)) .AddFilter(new RDFRegexFilter(n, new Regex(@"Mickey", RegexOptions.IgnoreCase)))) .AddDescribeTerm(y) .AddModifier(new RDFLimitModifier(20)); // Apply Describe Query RDFDescribeQueryResult describeResult = q.ApplyToGraph(waltdisney);