简体   繁体   中英

SPARQL using union with a dataset

The challenge set is to use the UNION keyword with the following datasets and return a list of grandads.

RELDB1 holds 2 useful tables:

The fatherOf table has this data:

Table fatherof:
('Chuck', 'Paul'),
('Chuck', 'Bonnie'),
('Jerry', 'George'),
('Jerry', 'Mary'),
('Chuck', 'Olivia'),
('Paul', 'Joan'),
('George', 'John'),
('George', 'Carole'),
('Ringo', 'Yoko'),
('Ringo', 'Peter')

and the table Person has:

Table person:
('Sara', 64, 'f'),
('Nancy', 68, 'f'),
('Mary', 27, 'f'),
('Olivia', 37, 'f'),
('Bonnie', 35, 'f'),
('Carole', 7, 'f'),
('Yoko', 6, 'f'),
('Joan', 9, 'f'),
('Chuck', 67, 'm'),
('Jerry', 65, 'm'),
('Paul', 30, 'm'),
('George', 25, 'm'),
('Ringo', 39, 'm'),
('John', 8, 'm'),
('Peter', 11, 'm')

I tried this query:

>SELECT ?x ?y ?z  
>WHERE {{?x rdf:type ex:Person}  
>UNION  
>{?x ex:fatherOf ?y . ?y ex:fatherOf ?z}}  
>ORDER BY (?x)

The output was everyone in the Person table and then also the son and grandchild for Chuck (Paul, Joan) and Jerry (George, John and George and Carole). I tried removing ?y ?z. The query returned a list of the person table!

How can I modify the query so that the UNION remains but I get only grandparents. Any guidance would be appreciated.

You are trying to return every person who is a grandfather. In your question you show that you are only returning paternal grandparents ...

A grandfather has children who has children who has children.

                                        Grandfather
                              Son                    Daughter
                        Son       Daughter       Son        Daughter

The union part come into play because you are going to return the following:

  1. ?z father of ?a
  2. ?a mother of ?b
  3. ?a father of ?b

     ?z ?a ?a ?b ?b ?b ?b

You need a union on the mother and father of ?b as you are combining the results of multiple triple patterns. I won't provide you with the query for this as this is classwork, however, this should help you arrive at the answer using what you have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM