package com.franz.agbase.examples;
import com.franz.agbase.*;
public class AGSparqlFilters {
/**
* Demonstrates some basics of using FILTER in SPARQL
*
* @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("dc", "http://purl.org/dc/elements/1.1/");
ts.registerNamespace("b", "http://example.org/book/");
ts.registerNamespace("ns", "http://example.org/ns#");
// Add some data to the store
ts.addStatement("!b:book1","!dc:title",ts.createLiteral("SPARQL Tutorial"));
ts.addStatement("!b:book1","!ns:price",ts.createLiteral(42));
ts.addStatement("!b:book2","!dc:title",ts.createLiteral("The Semantic Web"));
ts.addStatement("!b:book2","!ns:price",ts.createLiteral(23));
// SPARQL FILTERs restrict solutions to those for which the filter
// expression evaluates to TRUE.
String query =
"PREFIX dc: <http://purl.org/dc/elements/1.1/> " +
"SELECT ?title " +
"WHERE { ?x dc:title ?title " +
"FILTER regex(?title, '^SPARQL')" +
"}";
// Query the store and show the results
SPARQLQuery sq = new SPARQLQuery();
sq.setTripleStore(ts);
sq.setQuery(query);
AGSparqlSelect.doSparqlSelect(sq);
// Regular expression matches may be made case-insensitive
// with the "i" flag.
query =
"PREFIX dc: <http://purl.org/dc/elements/1.1/> " +
"SELECT ?title " +
"WHERE { ?x dc:title ?title " +
"FILTER regex(?title, 'web', 'i' ) " +
"}";
// Query the store and show the results
sq.setQuery(query);
AGSparqlSelect.doSparqlSelect(sq);
// By constraining the price variable, only :book2 matches
// the query because only :book2 has a price less than 30.5,
// as the filter condition requires.
query =
"PREFIX dc: <http://purl.org/dc/elements/1.1/> " +
"PREFIX ns: <http://example.org/ns#> " +
"SELECT ?title ?price " +
"WHERE { ?x ns:price ?price . " +
"FILTER (?price < 30.5) " +
"?x dc:title ?title . }";
// Query the store and show the results
sq.setQuery(query);
AGSparqlSelect.doSparqlSelect(sq);
// Close the triple store and disconnect from the server.
ts.closeTripleStore();
ags.disable();
}
}
Copyright © 2023 Franz Inc., All Rights Reserved | Privacy Statement |