How can I retrieve all Named Graphs URLs from a database?

How can I retrieve the URLs of all named graphs I have in a database via SPARQL and CLI? Thanks

1 Like

select distinct ?g where { graph ?g {?s ?p ?o} } should work. You can run this query through any support interface (CLI, Java API, HTTP API).

Cheers,
Pavel

Thanks, it works!

Btw - Is there a reason why this should not work?
SELECT ?s
FROM NAMED <URL_OF_GRAPH_IN_HERE>
WHERE {
?s ?p ?o
}

Yes, several. First, FROM NAMED expects an IRI. Second, FROM NAMED <urn:g> defines the named graph part of the query dataset leaving the default graph part empty (since there’s no FROM clause). At the same time your triple pattern ?s ?p ?o will be evaluated against the default graph (which is empty), and won’t match anything. Finally, you want to query for named graphs and not subjects of triples.

Cheers,
Pavel

I think there was a mistake in the answer and my “<” and “>” did not get formatted properly (I probably should have used a style. So my original query was
SELECT ?s

FROM NAMED < URL_OF_MY_GRAPH_HERE >
WHERE {
?s ?p ?o
}

This doesn’t work… Meaning it returns 0 answers and the named graph has something. However I found that if use FROM instead of FROM NAMED, it does work.

This is correct. Each triple pattern, e.g. ?s ?p ?o, is either in the default scope or in the named scope depending whether it’s in a graph .. { .. } clause. Since in your query it’s in the default scope, it’ll be evaluated against the default graph in the query dataset. You query does not have a FROM clause, but has a FROM NAMED IRI clause, so the default graph is empty and the pattern is evaluated against the empty graph.

When you change FROM NAMED to FROM, you re-define your query’s dataset to have a non-empty default graph and the empty set of named graphs. Thus your scan now returns results but any scan within graph ?g {...} would not.

See RDF Dataset in the SPARQL spec for more details, particularly for the notion of the active graph.

Cheers,
Pavel

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.