AGSparqlSetWithVariables.java

package com.franz.agbase.examples;

import com.franz.agbase.AllegroGraphException;
import com.franz.agbase.AllegroGraph;
import com.franz.agbase.AllegroGraphConnection;
import com.franz.agbase.BlankNode;
import com.franz.agbase.LiteralNode;
import com.franz.agbase.SPARQLQuery;
import com.franz.agbase.ValueSetIterator;


public class AGSparqlSetWithVariables {

    /**
     * Demonstrates how to bind variables in a SPARQL query.
     * 
     * @param args unused
     * @throws AllegroGraphException 
     */
    public static void main(String[] args) throws AllegroGraphException {
        
        // Connect to server, which must already be running.
        AllegroGraphConnection ags = new AllegroGraphConnection();
        try {
            ags.enable();
        } catch (Exception e) {
            throw new AllegroGraphException("Server connection problem", e);
        }
        
        // Create fresh triple-store for this example.
        AllegroGraph ts = ags.renew("sparql", AGPaths.TRIPLE_STORES);
                
        // Register any namespaces
        ts.registerNamespace("ex", "http://example.org/");
        
        // Define blank nodes
        BlankNode a = (BlankNode)ts.createBNode("_:a");
        BlankNode b = (BlankNode)ts.createBNode("_:b");
        
        // Add some data to the store
        LiteralNode aliceName = ts.createLiteral("Alice");
        ts.addStatement(a,"!ex:employeeName", aliceName);
        ts.addStatement(a,"!ex:employeeId",ts.createLiteral(12345));
        ts.addStatement(b,"!ex:employeeName",ts.createLiteral("Bob"));
        ts.addStatement(b,"!ex:employeeId",ts.createLiteral(67890));

        String query =
        "PREFIX ex: <http://example.org/> " +
        "SELECT ?s ?o " +
        "WHERE  { ?s ex:employeeName ?o }";
        
        // Query the store and show the results
        SPARQLQuery sq = new SPARQLQuery();
        sq.setTripleStore(ts);
        sq.setQuery(query);
        ValueSetIterator it = sq.select();
        AGUtils.showResults(it);

        // Bind the variable ?o and reissue the query
        Object[] varvals = new Object[2];
        varvals[0] = "o";
        varvals[1] = aliceName;
        sq.setWithVariables(ts, varvals);
        it = sq.select();
        AGUtils.showResults(it);
        
        // Close the triple store and disconnect from the server.
        ts.closeTripleStore();
        ags.disable();
    }

}

Up | Next

Copyright © 2014 Franz Inc., All Rights Reserved | Privacy Statement
Delicious Google Buzz Twitter Google+