Hi. I'm Mark Wallace. In my role as a an Ontologist and Software Architect, I am continually working with new and fun semantic technologies. Be it RDF/OWL, Triple-stores, Semantic Wikis, or Text Extraction, I am learning more all the time and want to share my experiences in hopes of helping others along with these technologies. I hope post a new article every month or two, so check back in every so often to see what’s cooking!

Thursday, May 31, 2012

SPARQL query from JavaScript

There are JavaScript libraries out there for SPARQL, but it's actually quite simple to query SPARQL from JavaScript without using any special library.  Here is an example of making a SPARQL query directly from a web page using JavaScript.

<html> 
  <head> 
    <title> SPARQL JavaScript </title>
    <script>
    /**
     * Author: Mark Wallace
     *
     * This function asynchronously issues a SPARQL query to a
     * SPARQL endpoint, and invokes the callback function with the JSON 
     * Format [1] results.
     *
     * Refs:
     * [1] http://www.w3.org/TR/sparql11-results-json/
     */
    function sparqlQueryJson(queryStr, endpoint, callback, isDebug) {
      var querypart = "query=" + escape(queryStr);
    
      // Get our HTTP request object.
      var xmlhttp = null;
      if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
     } else if(window.ActiveXObject) {
       // Code for older versions of IE, like IE6 and before.
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
     } else {
       alert('Perhaps your browser does not support XMLHttpRequests?');
     }
    
     // Set up a POST with JSON result format.
     xmlhttp.open('POST', endpoint, true); // GET can have caching probs, so POST
     xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
     xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
    
     // Set up callback to get the response asynchronously.
     xmlhttp.onreadystatechange = function() {
       if(xmlhttp.readyState == 4) {
         if(xmlhttp.status == 200) {
           // Do something with the results
           if(isDebug) alert(xmlhttp.responseText);
           callback(xmlhttp.responseText);
         } else {
           // Some kind of error occurred.
           alert("Sparql query error: " + xmlhttp.status + " "
               + xmlhttp.responseText);
         }
       }
     };
     // Send the query to the endpoint.
     xmlhttp.send(querypart);
    
     // Done; now just wait for the callback to be called.
    };
    </script>
  </head>

  <body>
    <script>
      var endpoint = "http://dbpedia.org/sparql";
      var query = "select * {?s ?p ?o} limit 5" ;

      // Define a callback function to receive the SPARQL JSON result.
      function myCallback(str) {
        // Convert result to JSON
        var jsonObj = eval('(' + str + ')');

        // Build up a table of results.
        var result = " <table border='2' cellpadding='9'>" ;
        for(var i = 0; i<  jsonObj.results.bindings.length; i++) {
          result += " <tr> <td>" + jsonObj.results.bindings[i].s.value;
          result += " </td><td>" + jsonObj.results.bindings[i].p.value;
          result += " </td><td>" + jsonObj.results.bindings[i].o.value;
          result += " </td></tr>"; 
        } 
        result += "</table>" ;
        document.getElementById("results").innerHTML = result;
     }
      
     // Make the query.
     sparqlQueryJson(query, endpoint, myCallback, true);
      
    </script>

    <div id="results">
      It may take a few moments for the info to be displayed here...
      <br/><br/>
      Run me in Internet Explorer or I get Cross Domain HTTP Request errors!
    </div>
  
  </body>
</html>

 
In the head section, the code defines a function, sparqlQueryJson(), that takes a SPARQL query string, a SPARQL endpoint URL, and a function to call when the result is ready.  (The optional fourth parameter will show you the raw JSON SPARQL results in an alert window if you set it to true.)  In the body section, the code specifies the query string, endpoint, and callback function, and then calls sparqlQueryJson() to issue the request.

Put the above code in a file called sparql.htm, and give it a try in your browser!

A few things to note:
  1. Most browsers won't let you run this code because it makes a cross-domain request (calls a service on a different host than the HTML was served from).  Use IE and if/when prompted, allow the content. 
  2. I use an asynchronous XMLHttpRequest to perform the query to the SPARQL endpoint.
  3. It would be best to put the sparqlQueryJson() function in a separate file to make it reusable from multiple pages.  I put everything in one file here just to simplify the example slightly. 



Friday, February 3, 2012

What Makes a Wiki Semantic?

A wiki is a web site that allows users to create and edit pages in an easy-to-format way (not HTML). They can easily create links on those pages to other pages in the wiki (and to pages on other web sites). The wiki usually keeps history of page edits, and allows rollback of pages to previous versions. New users can usually create accounts for themselves, and therefore page edits can be tracked based on user. Wikipedia is undoubtedly the most famous example of a wiki.

But what is a semantic wiki? I believe that there are four basic features that, when taken together, transform a wiki into a semantic wiki. While there can certainly be more features than just these four in a semantic wiki, I think that it is these four that must minimally be there to make a wiki semantic.

The first feature is that pages can be typed. That is, they can be marked as representing a certain "type" of thing, e.g. a book or a person or a city or an event. (Another word for type could be "category" or "class".) This type can simply be a word that has meaning to the wiki users, e.g. "Person", "City", etc. Different wiki technologies can differ on how this type is associated with a page (e.g., it can simply be another markup element that can be added to the wiki text of a page).

The second is that page links are assigned meaning. That is, hyperlinks from one page to another can be assigned more meaning than just "this is a link to a page"; the link can be assigned a "type". E.g. a link from a page about a book to a page about the author of that book might be assigned a type "authored-by", or "has-author". Again, this link type can simply be a word that has meaning to the wiki users, e.g. "authoredBy", "located-in", etc.

The third is that data values within a page can be assigned a meaning, e.g. the number 200,000 in a page about a city could be assigned the meaning of "population". Once again, "meaning", at its simplest level, is just associating a word from some vocabulary with the value. This can be thought of as an "attribute name" that goes with the value.

Finally, all of this semantic information can be used in dynamic queries that build tables (or other content) on the page, on-the-fly, by querying the semantic information. E.g., a table could be created that lists the top ten cities in a particular country by population by embedding a query into the page. This is certainly preferable to a person having to manually keep a summary of most populous cities up to date, requiring them to periodically review the wiki for new cities in a particular country, and determining if the top ten most populous cities has changed, and hand editing the changes into a summary table. In contrast, a table built on dynamic queries will always be accurate and instantly up-to-date (given that the semantics on the city pages are accurate), even as new city pages are added or population numbers are changed over time!

In summary, the four key elements that I believe make a wiki semantic are:
  1. The ability to type pages
  2. The ability to assign meaning to links between pages
  3. The ability to assign meaning to data values within a page, and
  4. The ability to query this knowledge to dynamically generate content
While there can certainly be more features than just these four in a semantic wiki, I think that it is these four that must minimally be there to make a wiki semantic.

Followers