Skip to content

cmem_client.repositories.graphs¤

Repository for managing named graphs in Corporate Memory.

Provides GraphRepository class for managing RDF named graphs with operations for deletion and import. Supports multiple RDF formats (Turtle, RDF/XML, JSON-LD, N-Triples) with automatic file type detection.

Examples:

List the graphs of a deployment and look one up:

>>> from cmem_client.client import Client
>>> client = Client.from_env()
>>> for iri in client.graphs:
...     print(iri, client.graphs[iri].writeable)

Import a Turtle file into a graph, export it again and delete it:

>>> from pathlib import Path
>>> from cmem_client.repositories.graphs import GraphExportConfig, GraphImportConfig
>>> from cmem_client.repositories.protocols.import_item import ImportConflictPolicy
>>> client.graphs.import_item(
...     path=Path("vocabulary.ttl"),
...     key="https://example.org/vocab/",
...     on_conflict=ImportConflictPolicy.REPLACE,
...     configuration=GraphImportConfig(register_as_vocabulary=True),
... )
>>> client.graphs.export_item(
...     key="https://example.org/vocab/",
...     path=Path("export.ttl"),
...     configuration=GraphExportConfig(resolve_owl_imports=True),
... )
>>> client.graphs.delete_item("https://example.org/vocab/")

Detect the serialization of a file before importing it:

>>> client.graphs.guess_file_type(path=Path("vocabulary.ttl")).mime_type

Classes:

Attributes:

GET_ONTOLOGY_IRI_QUERY¤

GET_ONTOLOGY_IRI_QUERY = '\nPREFIX owl: <http://www.w3.org/2002/07/owl#>\nSELECT DISTINCT ?iri\nWHERE {\n    ?iri a owl:Ontology;\n}\n'

GET_PREFIX_DECLARATION¤

GET_PREFIX_DECLARATION = '\nPREFIX owl: <http://www.w3.org/2002/07/owl#>\nPREFIX vann: <http://purl.org/vocab/vann/>\nSELECT DISTINCT ?prefix ?namespace\nWHERE {{\n    <{ontology_iri}> a owl:Ontology;\n        vann:preferredNamespacePrefix ?prefix;\n        vann:preferredNamespaceUri ?namespace.\n}}\n'

GraphDeleteConfig¤

Bases: DeleteConfig

Graph Delete Configuration.

Attributes:

  • model_config

GraphExportConfig¤

Bases: ExportConfig

Graph Export Configuration.

Attributes:

  • serialization (GraphFileSerialization | None) – RDF serialization to request for the export. If None, the server default is used. Export fails if the given format does not support export.
  • resolve_owl_imports (bool) – If True, resolve owl:imports and include the imported graphs in the export. Sent as owlImportsResolution.

model_config¤

model_config = ConfigDict(extra='allow', populate_by_name=True)

resolve_owl_imports¤

resolve_owl_imports: bool = False

serialization¤

serialization: GraphFileSerialization | None = None

GraphFileSerialization¤

Bases: Model

Supported graph format description

Attributes:

  • mime_type (str) – MIME type of the serialization, sent as Content-Type on import and as Accept on export.
  • file_extensions (list[str]) – File extensions mapped to this serialization, used by guess_file_type() to detect the format of a path.
  • encoding (str | None) – Content encoding of the file, sent as Content-Encoding on import when set.
  • known_not_supporters (list[str]) – Store types known not to support this serialization, matched against the type reported by the graph store. The client does not enforce this; the test suite uses it to skip combinations a store cannot handle.
  • export_supported (bool) – Whether graphs can be exported in this serialization.
  • import_supported (bool) – Whether graphs can be imported from this serialization.

encoding¤

encoding: str | None = None

export_supported¤

export_supported: bool = True

file_extensions¤

file_extensions: list[str]

import_supported¤

import_supported: bool = True

known_not_supporters¤

known_not_supporters: list[str] = Field(default_factory=list)

mime_type¤

mime_type: str

model_config¤

model_config = ConfigDict(extra='allow', populate_by_name=True)

GraphImportConfig¤

Bases: ImportConfig

Graph Import Configuration.

Attributes:

  • register_as_vocabulary (bool) – If True, register the imported graph as a vocabulary.
  • serialization (GraphFileSerialization | None) – RDF serialization of the imported file. If None, it is guessed from the file extension via guess_file_type().
  • namespace_prefix (str | None) – Vocabulary namespace prefix, used as a fallback when the file carries no vann metadata. Requires register_as_vocabulary=True and must be set together with namespace_uri.
  • namespace_uri (str | None) – Vocabulary namespace URI, used as a fallback when the file carries no vann metadata. Requires register_as_vocabulary=True and must be set together with namespace_prefix.

model_config¤

model_config = ConfigDict(extra='allow', populate_by_name=True)

namespace_prefix¤

namespace_prefix: str | None = None

namespace_uri¤

namespace_uri: str | None = None

register_as_vocabulary¤

register_as_vocabulary: bool = False

serialization¤

serialization: GraphFileSerialization | None = None

use_archive_handler¤

use_archive_handler: bool = True

GraphsRepository¤

Bases: PlainListRepository, DeleteItemProtocol, ImportItemProtocol, ExportItemProtocol

Repository for graphs.

This repository manages named graphs which are described with the Graph model. Supports both regular graphs and vocabularies through the register_as_vocabulary flag.

Attributes:

  • formats (dict[str, GraphFileSerialization]) – Registry of the supported RDF serializations, keyed by format name such as turtle or json-ld. Read by guess_file_type() and available to callers which need to pick a serialization explicitly.

Functions:

  • byte_generator – Generate bytes from a file in chunks.
  • delete_all – Delete all items from the repository
  • delete_item – Delete an item from the repository
  • export_item – Export an item from the repository to a file path.
  • export_to_zip – Export graph to a ZIP file.
  • fetch_data – Fetch simple list from a JSON endpoint via a type adapter
  • guess_file_type – Guess the RDF serialization format from a file path for import.
  • import_item – Import an exported file to the repository
  • items – Get the items of the repository
  • keys – Get the keys of the repository
  • values – Get the values of the repository

byte_generator¤

byte_generator(file_path, chunk_size=1024)

Generate bytes from a file in chunks.

Parameters:

  • file_path (Path) – Path to the file to read
  • chunk_size (int) – Size of each chunk in bytes (default: 1024)

Yields:

  • bytes (Generator[bytes]) – Chunks of data from the file

delete_all¤

delete_all()

Delete all items from the repository

delete_item¤

delete_item(key, skip_if_missing=False, configuration=None)

Delete an item from the repository

Parameters:

  • key (str) – The key of the item to delete
  • skip_if_missing (bool) – If True, it is ignored if the deleted item even exists
  • configuration (DeleteItemConfig) – Optional configuration for deletion

Raises:

export_item¤

export_item(key, path=None, replace=False, configuration=None)

Export an item from the repository to a file path.

Parameters:

  • key (str) – The key identifying the item to export.
  • path (Path | None) – The target file path for export. If None, a path will be generated.
  • replace (bool) – Whether to replace existing files at the target path.
  • configuration (ExportItemConfig_contra | None) – Optional configuration for export behavior.

Returns:

  • Path – The actual path where the item was exported.

Raises:

export_to_zip¤

export_to_zip(key, path=None, replace=False)

Export graph to a ZIP file.

Exports a single RDF file to a ZIP archive.

Parameters:

  • key (str) – The URI/identifier of the graph to export.
  • path (Path | None) – Optional target path for the ZIP file. If None, creates a temporary file.
  • replace (bool) – Whether to overwrite an existing file at the target path.

Returns:

  • Path – Path to the created ZIP file.

Raises:

  • GraphExportError – If the file already exists and replace is False, or if the exported graph is empty.

fetch_data¤

fetch_data()

Fetch simple list from a JSON endpoint via a type adapter

Use this method to fetch data when your result set is an array of objects.

formats¤

formats: dict[str, GraphFileSerialization] = {'turtle': GraphFileSerialization(mime_type='text/turtle', file_extensions=['ttl']), 'rdf/xml': GraphFileSerialization(mime_type='application/rdf+xml', file_extensions=['rdf', 'xml']), 'json-ld': GraphFileSerialization(mime_type='application/ld+json', file_extensions=['jsonld'], known_not_supporters=['TENTRIS'], export_supported=False), 'n-triples': GraphFileSerialization(mime_type='application/n-triples', file_extensions=['nt']), 'pretty-turtle': GraphFileSerialization(mime_type='text/turtle+pretty', file_extensions=['ttl'], import_supported=False)}

guess_file_type¤

guess_file_type(path)

Guess the RDF serialization format from a file path for import.

Attempts to determine the appropriate GraphFileSerialization by examining the file’s MIME type and file extension. Supports compressed files (.gz). Only considers formats where import_supported is True.

Parameters:

  • path (Path) – Path to the RDF file to analyze.

Returns:

  • GraphFileSerialization (GraphFileSerialization) – The detected serialization format with MIME type, file extensions, and optional encoding information.

Raises:

  • ValueError – If the file type cannot be determined from the path or extension.

import_item¤

import_item(path=None, key=None, on_conflict=ImportConflictPolicy.FAIL, configuration=None)

Import an exported file to the repository

By default, automatically handles zip files, directories, and single files using ImportItem model. Can be disabled by setting use_archive_handler=False in the configuration.

Returns:

  • str – The key of the imported item.

Raises:

  • RepositoryModificationError – If the item already exists and the conflict policy is FAIL, if the import type is not allowed for this repository, if the import request failed, or if the item is not present afterwards.

items¤

items()

Get the items of the repository

keys¤

keys()

Get the keys of the repository

logger¤

logger: logging.Logger

Gets the client logger

values¤

values()

Get the values of the repository

INSERT_CATALOG_ENTRY¤

INSERT_CATALOG_ENTRY = '\nPREFIX voaf: <http://purl.org/vocommons/voaf#>\nPREFIX vann: <http://purl.org/vocab/vann/>\nPREFIX dct: <http://purl.org/dc/terms/>\nPREFIX skos: <http://www.w3.org/2004/02/skos/core#>\nWITH <{graph}>\nINSERT {{\n    <{iri}> a voaf:Vocabulary ;\n        skos:prefLabel "{label}"{language} ;\n        vann:preferredNamespacePrefix "{prefix}" ;\n        vann:preferredNamespaceUri "{namespace}" ;\n        dct:description "vocabulary imported with cmem-client" .\n}}\nWHERE {{}}\n'

VOCABULARY_CATALOG_GRAPH¤

VOCABULARY_CATALOG_GRAPH = 'https://ns.eccenca.com/example/data/vocabs/'

IRI of the (optional, legacy) vocabulary catalog graph.

Newer backends do not have this graph. The catalog entry is only written when it already exists, so importing a vocabulary never (re-)creates it.

Comments