Return a nested data structure from a SPARQL query

前端 未结 3 854
不知归路
不知归路 2021-02-15 16:22

If I have a graph with this kind of structure:

@prefix  :        .
@prefix  rdf:     .
         


        
3条回答
  •  独厮守ぢ
    2021-02-15 17:22

    You're conflating the query result itself (essentially an abstract table structure) with the syntax in which that result is written (in your case, a customized nested JSON structure).

    Don't try to do tricks with group concatenation in this case. Just do this query:

    SELECT ?given ?family ?friend_given ?friend_family
    WHERE {
      ?person foaf:givenName ?given ;
              foaf:familyName ?family .
      ?person :knows ?friend .
      ?friend foaf:givenName ?friend_given ;
              foaf:familyName ?friend_family .
    }
    GROUP BY ?family ?given
    

    Which results in a result like this:

    given  family  friend_given friend_family
    -------------------------------------------- 
    Alice  Lidell  Bob          Doe
    Alice  Lidell  Hwa          Choi
    

    And then let a custom streaming result writer write the result to the nested syntax format you require. Given that the query groups by name, the writer can safely assume that subsequent rows with the same given and family names "belong together".

    Alternatively, use a CONSTRUCT query instead of a SELECT, and post-process the retrieved RDF graph (which accurately represents the tree structure you're after).

提交回复
热议问题