3

I have a triple store with RDF triples and I want to export the data to a table where columns represent the predicates. For example, if I have the following triples

:s1 :p1 "v11"
:s1 :p2 "v12"
:s2 :p2 "v22"
:s2 :p3 "v23"

I want it to be as follows

----|  p1    | p2  | p3
s1  |  v11   | v12 | (null)
s2  | (null) | v22 | v23

This might seems a little odd, as in most cases we need to export the other way but here I want to feed this data into a data mining software.

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Mostafa abdo
  • 456
  • 1
  • 7
  • 18

1 Answers1

3

USE OPTIONAL

If you know the predicates in advance, you can wrap each predicate in OPTIONAL to get all predicates in the same row for all subjects - even if some are missing. Here is an example:

SELECT ?name ?birth ?death
WHERE {
?person foaf:name ?name .
?person dbo:birthPlace :Berlin .
OPTIONAL { ?person dbo:birthDate ?birth . }
OPTIONAL { ?person dbo:deathDate ?death .}
}
ORDER BY ?name
LIMIT 1000

I keep my original answer for reference:

Use UNION (creates separate rows for each predicate)

If you know the predicates in advance, you can use UNION to get all predicates for all subjects - even if some are missing. Here is an example:

SELECT ?name ?birth ?field
WHERE {
?person foaf:name ?name .
?person dbo:birthPlace :Berlin .
{
?person dbo:birthDate ?birth .
} UNION {
?person dbo:field ?field .
}}
ORDER BY ?name
LIMIT 100
René
  • 178
  • 6
  • Thanks @René, but in your example I see that each value has a separate row (e.g. "Agnete Bræstrup"), and I was thinking of a way to export the whole graph. And yes, I don't have multiple values for each predicate. – Mostafa abdo Dec 23 '16 at 19:47
  • @Mostafaabdo I updated my answer with a solution which keeps everything in one row. – René Dec 23 '16 at 20:14
  • All credits for @René, and here it is a 'modified' version to export all predicates (of course to be use with 'limited' graph). get all predicates `SELECT DISTINCT ?p WHERE { ?s ?p ?o }` Export them to excel and use concat function to assemble query as in the original answer. – Mostafa abdo Dec 23 '16 at 21:57