Querying a Topic Map using SPARQL

Top  Previous  Next

This is not a full guide to writing SPARQL but shows how to invoke SPARQL queries from the .NET client. For more information about SPARQL in Web3 please refer to Querying with SPARQL

Given the following SPARQL query that gets the employer and age of all people.

 

PREFIX ont: <http://www.networkedplanet.com/business-ontology/types/>

SELECT ?person ?age ?employer WHERE {

  ?person ont:employer ?employer ;

           ont:age      ?age

}

 

The query can be executed from the client in the following way:

 

      /// <summary>

      /// Runs a simple SPARQL query against a topic map

      /// </summary>

      /// <param name="tmUri">The web address of the topic map to be queried</param>

      /// <returns>The SPARQL query results document</returns>

      private static XDocument RunSparqlQuery(Uri tmUri)

       {

          const string query =

                  @"PREFIX ont: <" + SchemaConstants.SchemaBase + @">

                   SELECT ?person ?age ?employer WHERE {

                       ?person ont:employer ?employer ;

                         ont:age      ?age

                   }";

          var client = new TopicMapServiceClient();

          var tm = client.GetTopicMap(tmUri);

          return tm.QueryTopicMap(query);

       }

 

Processing Results

 

The result returned by the QueryTopicMap method is an XML document in accordance with the SPARQL Protocol standard :

 

<sparql xmlns="http://www.w3.org/2005/sparql-results#">

  <head>

    <variable name="person" />

    <variable name="age" />

    <variable name="employer" />

  </head>

  <results>

    <result>

      <binding name="person">

        <uri>http://localhost/web3/topicmaps/452405e0-58c5-4067-89d3-fb51c72f48da/topics/d90c1a6f-abd8-4c9e-b151-0b7a99807c48</uri>

      </binding>

      <binding name="age">

        <literal datatype="http://www.w3.org/2001/XMLSchema#int">23</literal>

      </binding>

      <binding name="employer">

        <uri>http://localhost/web3/topicmaps/452405e0-58c5-4067-89d3-fb51c72f48da/topics/92d67cc8-dafa-4da0-9452-31c510fcaa8f</uri>

      </binding>

    </result>

  </results>

</sparql>

 

You can choose either to work directly with this XML (for example using LINQ to XML or XPath queries to extract data); or convert the XML document into a DataTable. The class NetworkedPlanet.Web3.Platform.Common.SparqlResultsReader provides methods for performing this conversion.

The following example shows using the SparqlResultsReader class to return a query result as a DataTable:

 

      private static DataTable QueryTopicMap(Uri tmUri, string sparqlQuery)

       {

          var client = new TopicMapServiceClient();

          var tm = client.GetTopicMap(tmUri);

          var xmlResults = tm.QueryTopicMap(sparqlQuery);

          var resultsReader = new SparqlResultsReader(xmlResults);

          return resultsReader.CreateDataTable();

       }