Monday, October 11, 2010

Querying via a ClientModel

The .NET API available in the Semantics Platform allows an application to query one or more sources of data in a federated fashion using SPARQL. The data sources can be local in-memory graphs or remote graphs hosted on another server. The ClientModel class provides the primary interface for executing SPARQL queries.

In this posting I will go through a simple example of how to use a ClientModel to query the contents of two RDF files.

I will start by constructing two in-memory GraphDataSource objects. Each data source will be filled with the contents of a local RDF file.

GraphDataSource dataGraph = new GraphDataSource();

using (StreamReader r = new StreamReader("c:\\data.nt"))
    dataGraph.Read<NTriplesReader>();

GraphDataSource ontologyGraph = new GraphDataSource();

using (StreamReader r = new StreamReader("c:\\ontology.nt"))
    ontologyGraph.Read<NTriplesReader>();

Next I construct the ClientModel object and add both of the graph object to the DataSources collection. Each data source added to a ClientModel must have a unique URI to identify it.

ClientModel model = new ClientModel();

model.DataSources["http://example.org/data"] = dataGraph;
model.DataSources["http://example.org/ontology"] = ontologyGraph;

As a convenience, I will define some namespaces on the ClientModel to make my SPARQL queries easier to write.

model.ParserOptions.Namespaces["rdf"] = NS.Rdf;
model.ParserOptions.Namespaces["rdfs"] = NS.Rdfs;
model.ParserOptions.Namespaces["x"] = "http://example.org/";

To execute the SPARQL query I simply call the Query method with a valid SPARQL query string. Note because I defined the namespaces on the ClientModel object I do not need to include them in the query using PREFIX statements.

Table results = model.Query(@"
    select ?label 
    from x:data 
    from x:ontology
    where {
        ?s rdf:type ?type; rdfs:label ?label.
        ?type rdfs:subClassOf x:Thing.
    }");

Finally I write the results of the query to the console window by iterating over the rows in the result table.

foreach (TableRow row in results.GetRows())
    Console.WriteLine(row[0].Value);