Search code examples
graphsparqlrdf4j

SPARQL Create Graph if does not exist already


I am trying to formulate a SPARQL query that will create a new graph with ID if does not already exist. If it does exist, the query should return "Graph Exist".

I am using RDF4J with SPARQL queries.

PREFIX  app:  <http://www.example.com/ont#>

CREATE GRAPH <http://www.example.com/ont#books>;
SELECT{
    ASK WHERE { GRAPH <http://www.example.com/ont#books> { ?s ?p ?o } }
    str("Graph exists!").

}

It is not accepting SELECT because of the CREATE GRAPH


Solution

  • You can not combine an update and a query in this fashion. Semicolon-separated SPARQL operation sequences can only contain update operations.

    Also, a CREATE GRAPH operation will itself return an error if the graph already exists. Simply execute:

    CREATE GRAPH <http://www.example.com/ont#books>
    

    If the graph already exists, the operation will return an error.

    Finally: most RDF4J database implementations do not record empty graphs. This means that the CREATE GRAPH operation is, for the most part, a no-operation: it gives an error if the graph you're trying to create already exists (that is, there are statements that use that named graph), and otherwise it just returns an OK and doesn't actually do anything.

    To actually create a named graph in RDF4J you have to add statements to it, e.g.:

     INSERT DATA { GRAPH <http://www.example.com/ont#books> { <ex:s1> <ex:p1> <ex:o1> } }
    

    If you want to do a check that the graph doesn't exist before you insert (so that it doesn't add to an existing graph accidentally), you can use an update sequence like so:

     CREATE GRAPH <http://www.example.com/ont#books> ;
     INSERT DATA { GRAPH <http://www.example.com/ont#books> { <ex:s1> <ex:p1> <ex:o1> } }
    

    If the graph already exists, the CREATE will fail and the rest of the sequence will be aborted.