Aries On The Cusp
Aries On The Cusp

Reputation: 419

Sparql to combine list into 1 row's results

I've looked at GROUP_CONCAT, but it doesn't do what I want.

Lets say I have this data:

_:autos325 rdf:first "john";
           rdf:rest _:autos326.
_:autos326 rdf:first "d";
           rdf:rest _:autos327.
_:autos327 rdf:first "rockefeller";
           rdf:rest rdf:nil.
<http://foo.com/ABC> <http://prop/name> _:autos325

If I use this SPARQL to read back out the name:

SELECT  *  WHERE { <http://foo.com/ABC> <http://prop/name> ?o .
                    ?o rdf:rest*/rdf:first ?foo . }

I get the name back, but each part of the name is given as a separate row in the results

If I use GROUP_CONCAT, it works until you use a variable as the subject. I can't omit ?s from the GROUP BY or I get a syntax error

select ?s  (group_concat(distinct ?foo;separator=", ") as ?names)
WHERE { ?s <http://prop/name> ?o .
                        ?o rdf:rest*/rdf:first ?foo . }
GROUP BY ?s ?foo

How can I concatenate the ?foo results so the entire name is stuffed into one row instead of spread across three result rows ?

Upvotes: 2

Views: 1408

Answers (2)

Aries On The Cusp
Aries On The Cusp

Reputation: 419

I fixed it with a simple case but not with complex queries, since I have to start including other variables in the GROUP BY. The correct way was to GROUP BY the subject then use GROUP_CONCAT.

Yes, I'm a newbie to SPARQL :-)

SELECT ?s  (GROUP_CONCAT(DISTINCT ?foo;separator=", ") AS ?names)
WHERE { ?s <http://prop/name> ?o .
        ?o rdf:rest*/rdf:first ?foo . }
GROUP BY ?s 

Upvotes: 1

Jeen Broekstra
Jeen Broekstra

Reputation: 22042

The problem is that you are grouping on ?foo. Change it to:

GROUP BY ?s

and it should work.

Aggregating operators (such as COUNT, GROUP_CONCAT, etc) always operate on groups of solutions. The groups are defined by the GROUP BY clause (if not present, the entire solution counts as a one big group). So having GROUP BY ?s basically says: "concatenate the names per value of ?s". But if you also add ?foo to the GROUP BY you're effectively saying: "concatenate the names per combination of values of ?s and ?foo". This of course then results in a separate row for each value of ?foo again, and effectively nothing gets concatenated.

Upvotes: 2

Related Questions