how create named graphs in GraphDB?

153 Views Asked by At

how create named graphs in GraphDB?

Is it necessary to change the format de rdf file from triples to n-quads through tools (like RDFLib or Apache Jena) or is there an easier way?

2

There are 2 best solutions below

0
On

For those looking for how to create named graphs programmatically, the following worked for me:

Python:

import requests

file_path = <PATH_TO_YOUR_TTL_FILE>
graphdb_repo = <YOUR_REPO_ID>
named_graph_uri = <YOUR_NAMED_GRAPH_URI>

with open(file_path, 'rb') as f:
    file_content = f.read()
headers = {'Content-Type': 'application/x-turtle', 'Accept': 'application/json'}

upload_url = f'http://localhost:7200/repositories/{graphdb_repo}/rdf-graphs/service?graph={named_graph_uri}'
requests.post(upload_url, headers=headers, data=file_content)

Or in CURL:

curl -X POST -H "Content-Type:application/x-turtle" -H "Accept:application/json" -T "<PATH_TO_YOUR_TTL_FILE>" http://localhost:7200/repositories/<YOUR_REPO_ID>/rdf-graphs/service?graph={YOUR_NAMED_GRAPH_URI}
0
On

Not necessarily. When you do the import into GraphDB using the GraphDB workbench, it allows you to specify a named graph, as shown below.

Specifying a named graph

Programmatically you can do it as follows using RDF4J. Note that in RDF4J named graphs are referred to as contexts.

    String address = "http://localhost/"
    String repositoryName = "myRepo"
    File rdfFile = new File("some triples");

    HTTPRepository repository = new HTTPRepository(address, repositoryName);
    try (RepositoryConnection connection = repository.getConnection()) {
        connection.begin();
        connection.add(rdfFile, RDFFormat.TURTLE, "http://MyGraph,com"); 
        connection.commit();
    } catch (RepositoryException re){
        re.printStackTrace();
    }

To use RDf4J you will need to add the following dependency:

<dependency>
    <groupId>org.eclipse.rdf4j</groupId>
    <artifactId>rdf4j-client</artifactId>
    <version>4.2.3</version>
    <type>pom</type>
</dependency>