I have an RDF file and I need to extract some information from it and write it to a file. I understood how it basically works, but I'm stuck with this:
String queryString = "select ?person ?children where { ?person ?hasChildren ?children}";
TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
TupleQueryResult result = tupleQuery.evaluate();
while (result.hasNext()) {
BindingSet bindingSet = result.next();
Value p1 = bindingSet.getValue("person");
Value p2 = bindingSet.getValue("child");
println(p1 + " has children " + p2 +"");
}
result.close();
The output I get is like this:
http://example.org/people/person1 has children http://example.org/people/child1
http://example.org/people/person1 has children http://example.org/people/child2
I don't see how to list all the persons with their objects in this format:
person1 has children child1 and child2
How can this be done?
You may find this answer, which describes SPARQL's
group_concat
, useful:In SPARQL, when you have a result set of query solutions, you can
group
on one or more of the variables, merging solutions that have these variables in common. For instance, consider the dataIf you run the following query on it
you get results like this:
Iterating through the results as you have in your question would produce the type of output that you're currently getting. What we'd like to do is to actually get results like:
and that's exactly what
group_by
lets us do. A query like this:produces (notice that the variable in the result is
?children
, not?child
, because we've usedgroup_concat(...) as ?children
to create the new variable?children
):If you use a query like this and iterate through the results, printing them as you have, you'll get output like you want. If you do want to strip the leading
http://example.org/people/
off from the persons and children, you'll need a bit more string processing. For instance, using STRAFTER to remove thehttp://example.org/people/
prefix, you can use a query like this:to get results like:
which, when you do your printing, will give you results like