Queries against RDF.ex

Let's say we have an RDF.ex graph like this:

graph = RDF.Turtle.read_string! """
  @prefix foaf:  <http://xmlns.com/foaf/0.1/> .
  
  _:a  foaf:name   "Johnny Lee Outlaw" .
  _:a  foaf:mbox   <mailto:jlow@example.com> .
  _:b  foaf:name   "Peter Goodguy" .
  _:b  foaf:mbox   <mailto:peter@example.org> .
  _:c  foaf:mbox   <mailto:carol@example.org> .
  """

We can execute the following SPARQL query:

query = """
  PREFIX foaf:   <http://xmlns.com/foaf/0.1/>
  SELECT ?name ?mbox
  WHERE
    { ?x foaf:name ?name .
      ?x foaf:mbox ?mbox }
  """

like this:

SPARQL.execute_query(graph, query)

This will return a SPARQL.Query.Result struct which contains the results under the results field as a list of maps with the bindings of the solutions.

%SPARQL.Query.Result{
  results: [
    %{"mbox" => ~I<mailto:peter@example.org>, "name" => ~L"Peter Goodguy"},
    %{"mbox" => ~I<mailto:jlow@example.com>, "name" => ~L"Johnny Lee Outlaw"}
  ],
  variables: ["name", "mbox"]
}

The list of results for a single variable can be fetched with the SPARQL.Query.Result.get/2 function.

SPARQL.execute_query(graph, query) 
|> SPARQL.Query.Result.get(:mbox)

If SPARQL.execute_query/2 is used to execute a CONSTRUCT query, it will return an RDF.Graph:

iex> SPARQL.execute_query graph, """
...>  PREFIX foaf:   <http://xmlns.com/foaf/0.1/>
...>  PREFIX schema: <http://schema.org/>
...>  CONSTRUCT   
...>    { ?x schema:name ?name ;
...>         schema:email ?mbox }
...>  WHERE
...>    { ?x foaf:name ?name ;
...>         foaf:mbox ?mbox }
...>  """
#RDF.Graph{name: nil
     ~B<b0>
         ~I<http://schema.org/email>
             ~I<mailto:peter@example.org>
         ~I<http://schema.org/name>
             ~L"Peter Goodguy" 
     ~B<b1>
         ~I<http://schema.org/email>
             ~I<mailto:jlow@example.com>
         ~I<http://schema.org/name>
             ~L"Johnny Lee Outlaw"}

The SPARQL.execute_query/2 function converts a given query string implicitly to a SPARQL.Query struct. If you intend to execute the query multiple times it's better to do this step on your own with the SPARQL.query/1 function and pass the interpreted query directly to SPARQL.execute_query/2, in order to not parse the query on every execution.

query = SPARQL.query """
  PREFIX foaf: <http://xmlns.com/foaf/0.1/>
  SELECT ?name ?mbox
  WHERE
    { ?x foaf:name ?name .
      ?x foaf:mbox ?mbox }
  """

SPARQL.execute_query(graph, query)