Skip to content

cmem_client.repositories.queries¤

Repository for managing queries from the Corporate Memory query catalog.

Provides QueriesRepository class for accessing queries stored in RDF catalog graphs. Queries are fetched using the query catalog REST API.

Examples:

Browse the catalog and fetch a single query:

>>> from cmem_client.client import Client
>>> client = Client.from_env()
>>> for url in client.queries:
...     print(url, client.queries[url].label)
>>> client.queries.get("https://ns.eccenca.com/data/queries/my-query")

Run a SPARQL query without storing it in the catalog:

>>> client.queries.execute_query("SELECT ?s WHERE { ?s ?p ?o } LIMIT 10")

See the individual methods for executing, explaining and cancelling queries.

Classes:

QueriesCreateConfig¤

Bases: CreateConfig

Configuration for creating queries.

Attributes:

  • catalog_graph (str | None) – URI of the query catalog graph to operate on. If None, the catalog graph configured on the repository is used.

catalog_graph¤

catalog_graph: str | None = None

model_config¤

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

QueriesDeleteConfig¤

Bases: DeleteConfig

Configuration for deleting queries.

Attributes:

  • catalog_graph (str | None) – URI of the query catalog graph to operate on. If None, the catalog graph configured on the repository is used.

catalog_graph¤

catalog_graph: str | None = None

model_config¤

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

QueriesExportConfig¤

Bases: ExportConfig

Configuration for exporting queries.

Attributes:

  • model_config

QueriesRepository¤

QueriesRepository(client, catalog_graph=None)

Bases: Repository, CreateItemProtocol, DeleteItemProtocol, ExportItemProtocol, UpdateItemProtocol

Repository for query catalog queries.

This repository manages queries stored in Corporate Memory RDF catalog graphs. Queries are described using the SHACL UI vocabulary and accessed via the query catalog REST API endpoint.

The repository provides full CRUD operations (create, read, update, delete) for catalog queries. For executing, explaining, or managing running queries, use the appropriate service components.

Attributes:

  • DEFAULT_CATALOG_GRAPH (str) – Catalog graph used when neither the constructor nor an operation configuration names one. Taken from Query.DEFAULT_NS.

Functions:

  • cancel_query – Cancel a running query.
  • create_item – Create (add) a new item to the repository
  • delete_all – Delete all items from the repository
  • delete_item – Delete an item from the repository
  • execute_query – Execute a SPARQL query and return results.
  • explain_query – Get the logical plan explanation for a SPARQL query.
  • export_item – Export an item from the repository to a file path.
  • fetch_data – Fetch queries from the catalog graph using the REST API.
  • get – Get a query by its identifier.
  • get_query_status – Get status of running and recently completed queries.
  • items – Get the items of the repository
  • keys – Get the keys of the repository
  • raise_modification_error – Raise an exception if needed
  • update_item – Update an existing item in the repository.
  • values – Get the values of the repository

Parameters:

  • client (Client) – The Corporate Memory client instance.
  • catalog_graph (str | None) – URI of the catalog graph. If None, uses default catalog graph.

DEFAULT_CATALOG_GRAPH¤

DEFAULT_CATALOG_GRAPH: str = Query.DEFAULT_NS

cancel_query¤

cancel_query(query_id)

Cancel a running query.

Attempts to cancel a query that is currently executing. The query is identified by its execution ID (not its catalog URI).

Parameters:

  • query_id (str) – Execution ID of the query to cancel (from get_query_status).

Raises:

  • HTTPStatusError – If the cancel request fails (e.g., query not found, already completed, or insufficient permissions).

Examples:

>>> from cmem_client.client import Client
>>> client = Client.from_env()
>>> [status.id for status in client.queries.get_query_status()]

Passing one of those IDs cancels that query. That call is described rather than shown running: which queries are in flight depends on what the deployment happens to be doing, and one which finishes between listing and cancelling makes the cancel fail with a 404.

Note

This endpoint requires admin privileges in Corporate Memory. Not all queries can be cancelled depending on their execution state.

create_item¤

create_item(item, skip_if_existing=False, configuration=None)

Create (add) a new item to the repository

Parameters:

  • item (ItemType) – The item to add to the repository
  • skip_if_existing (bool) – If true, creating already existing items will be ignored
  • configuration (CreateItemConfig_contra | None) – Optional configuration

Raises:

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:

execute_query¤

execute_query(query, accept=None, owl_imports_resolution=True, base64_encoded=False, distinct=False, limit=None, offset=None, timeout=None)

Execute a SPARQL query and return results.

Executes a SPARQL query (SELECT, ASK, DESCRIBE, CONSTRUCT) or update operation (INSERT, DELETE, etc.) and returns the raw response.

Parameters:

  • query (str | Query) – SPARQL query string or Query object to execute.
  • accept (str | None) – Accept header for response format. If None, uses default based on query type (text/csv for SELECT, text/turtle for DESCRIBE, etc.).
  • owl_imports_resolution (bool) – Enable owl:imports resolution (default: True). When enabled, graphs that import other graphs via owl:imports will

be queried as merged overall-graphs.

  • base64_encoded (bool) – Enable base64 encoding of query parameter (default: False). Useful when aggressive firewalls block SPARQL queries.
  • distinct (bool) – Override SELECT query to make result set DISTINCT (default: False).
  • limit (int | None) – Override or set LIMIT in SELECT query.
  • offset (int | None) – Override or set OFFSET in SELECT query.
  • timeout (int | None) – Max execution time in milliseconds.

Returns:

  • str – Raw query results as string in the requested format.

Raises:

  • HTTPStatusError – If the query execution fails.
  • ValueError – If query text is invalid or placeholders are unfilled.

Examples:

>>> from cmem_client.client import Client
>>> client = Client.from_env()
>>> results = client.queries.execute_query("SELECT * WHERE { ?s ?p ?o } LIMIT 10")
>>> print(results)
Note

For parameterized queries with placeholders, use Query object with fill_placeholders() first, or use get() to fetch from catalog.

explain_query¤

explain_query(query)

Get the logical plan explanation for a SPARQL query.

Calls the query catalog API to get the logical plan for a given SPARQL query, which provides information about query optimization, execution order, and estimated complexity.

The logical plan includes:

  • Optimization groups and their evaluation order
  • Collection sizes and complexity estimates
  • Unique subject and object counts
  • Estimated number of iterations

Parameters:

  • query (str | Query) – The SPARQL query string or Query object to explain.

Returns:

  • LogicalPlan – A LogicalPlan object containing the formatted query execution plan.

Raises:

  • HTTPStatusError – If the API request fails due to HTTP errors.
  • RequestError – If the API request fails due to network errors.

Examples:

>>> from cmem_client.client import Client
>>> client = Client.from_env()
>>> plan = client.queries.explain_query("SELECT * WHERE { ?s ?p ?o }")
>>> print(plan.plan)
Note

This operation analyzes the query structure and provides an execution plan without actually executing the query against data.

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:

fetch_data¤

fetch_data(catalog_graph=None, lang_pref='en')

Fetch queries from the catalog graph using the REST API.

Parameters:

  • catalog_graph (str | None) – URI of the catalog graph. If None, uses the graph specified during initialization.
  • lang_pref (str) – Language preference for labels (default: “en”).

Raises:

  • HTTPStatusError – If fetching the catalog fails.

get¤

get(key, default=None, catalog_graph=None)

Get a query by its identifier.

Supports multiple identifier formats:

Note: File paths are not supported. For file-based queries, create a Query object directly by reading the file content.

Parameters:

  • key (str) – Query identifier (full URI or short URI).
  • default (Query | None) – Value to return if the query is not found.
  • catalog_graph (str | None) – URI of the catalog graph. If None, uses the graph specified during initialization.

Returns:

  • Query | None – The Query object if found, otherwise the default value.

get_query_status¤

get_query_status()

Get status of running and recently completed queries.

Retrieves information about currently executing and recently finished queries, including timing data, user information, and trace IDs.

Returns:

  • list[QueryStatus] – List of QueryStatus objects for active/recent queries.

Raises:

  • HTTPStatusError – If the status request fails.

Examples:

>>> from cmem_client.client import Client
>>> client = Client.from_env()
>>> statuses = client.queries.get_query_status()
>>> for status in statuses:
...     print(f"{status.id}: {status.status}")
Note

This endpoint requires admin privileges in Corporate Memory.

items¤

items()

Get the items of the repository

keys¤

keys()

Get the keys of the repository

logger¤

logger: logging.Logger

Gets the client logger

raise_modification_error¤

raise_modification_error(response)

Raise an exception if needed

update_item¤

update_item(item, configuration=None)

Update an existing item in the repository.

Parameters:

  • item (ItemType) – The item to update in the repository.
  • configuration (UpdateItemConfig_contra | None) – Optional configuration for the update operation.

Raises:

values¤

values()

Get the values of the repository

QueriesUpdateConfig¤

Bases: UpdateConfig

Configuration for updating queries.

Attributes:

  • catalog_graph (str | None) – URI of the query catalog graph to operate on. If None, the catalog graph configured on the repository is used.

catalog_graph¤

catalog_graph: str | None = None

model_config¤

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

Comments