Neo4j Database¶
Neo4j is a labeled property graph database queried with Cypher. CIM models are imported into it from CIM XML with the neosemantics (n10s) RDF plugin.
CIMantic Graphs provides the Neo4jConnection class for reading CIM models from Neo4j and uploading them to it. It runs the same graph creation and expansion methods as the SPARQL connections, with Cypher queries.
Installation and Setup¶
Python Dependencies¶
Neo4jConnection needs the neo4j driver, from the neo4j extra:
Local Instance (docker compose)¶
The repository's docker-compose.yml runs Neo4j 5.26 Community with the n10s plugin, user neo4j and password test1234. From a CIM-Graph checkout:
docker compose up -d --wait neo4j
uv run python tests/seed_databases.py neo4j # loads tests/test_models/ieee13.xml
The Bolt URL is neo4j://localhost:7687 and the Neo4j Browser is at http://localhost:7474. The container has no volume, so docker compose down discards the data.
Importing CIM XML¶
The Cypher queries expect class labels and property names without namespace prefixes (Feeder, Terminal.ConductingEquipment). The seed script imports CIM XML with n10s this way:
Environment Configuration¶
A connection reads its settings from CIMG_* environment variables when it is created (see Environment Variables). CIMG_USERNAME and CIMG_PASSWORD have no defaults. For the docker compose instance:
import os
os.environ['CIMG_CIM_PROFILE'] = 'cimhub_2023'
os.environ['CIMG_URL'] = 'neo4j://localhost:7687'
os.environ['CIMG_DATABASE'] = 'neo4j'
os.environ['CIMG_USERNAME'] = 'neo4j'
os.environ['CIMG_PASSWORD'] = 'test1234'
os.environ['CIMG_IEC61970_552'] = '552-NEW'
import cimprofiles.cim17.cimhub_2023 as cim
Creating a Connection¶
from cimgraph.databases import Neo4jConnection
db = Neo4jConnection()
The driver connects on the first query. Neo4jConnection uses the async Neo4j driver, which runs its batched queries concurrently, on the connection's own event loop in a background thread. Its methods are synchronous and also work where an event loop is already running, as in Jupyter, without nest-asyncio.
Usage Examples¶
Example 1: Retrieving an Object by mRID¶
feeder = db.get_object(mRID="49AD8E07-3BF9-A4E2-CB8F-C3722F837B62")
feeder.pprint()
{
"@id": "49ad8e07-3bf9-a4e2-cb8f-c3722f837b62",
"@type": "Feeder"
}
Example 2: Loading a Feeder Model¶
from cimgraph.models import FeederModel
network = FeederModel(container=feeder, connection=db)
print(f"Loaded {len(network.graph[cim.ACLineSegment])} line segments")
Loaded 11 line segments
Example 3: Expanding the Graph¶
get_all_edges() adds the attributes and associated objects of every object of a class. Unit values are CIMUnit objects in SI base units; convert them with .to():
network.get_all_edges(cim.ACLineSegment)
line = network.first(cim.ACLineSegment)
print(f"Line {line.name}: length {line.length.to('m')} m ({line.length.to('ft'):.0f} ft)")
Line 645646: length 91.44 m (300 ft)
Example 4: Querying an Association¶
The Neo4j driver logs a warning from the server for every get_from_triple() query (removed from the output below): the query looks for both a property and a relationship named after the predicate, and one of them does not exist.
substation = db.get_from_triple(subject=feeder, predicate='Feeder.NormalEnergizingSubstation')
print(f"Substation: {substation}")
Substation: [{"@id": "6c62c905-6fc7-653d-9f1e-1340f974a587", "@type": "Substation"}]
Example 5: Executing a Custom Cypher Query¶
execute() runs a read-only query and returns one dict per record:
query_text = '''
MATCH (feeder:Feeder)
RETURN feeder.`IdentifiedObject.name` AS name, feeder.uri AS uri
'''
db.execute(query_text)
[{'name': 'ieee13nodeckt',
'uri': 'urn:uuid:49AD8E07-3BF9-A4E2-CB8F-C3722F837B62'}]
Example 6: Debugging Cypher Queries¶
# The Cypher query that get_all_edges(cim.Breaker) runs for relationships (first batch of 100 objects)
print(db.get_edges_query(network.graph, cim.Breaker))
MATCH (n:Breaker) WHERE n.uri IN ["urn:uuid:52DE9189-20DC-4C73-BDEE-E960FE1F9493"] OPTIONAL MATCH (n) - [r] - (m) RETURN DISTINCT n.uri as identifier, type(r) as attribute, REPLACE(m.uri, "urn:uuid:", "") as edge_id, labels(m)[1] as edge_class
Disconnecting¶
disconnect() closes the driver and stops the event loop. It is safe to call when not connected.
db.disconnect()
Neo4j-Specific Methods¶
| Method | Description |
|---|---|
execute(query_message) |
Runs a read-only Cypher query and returns one dict per record |
execute_with_params(query_message, **params) |
Runs a Cypher query that writes, with $param placeholders bound to params |
upload(graph, batch_size=100) |
Serializes the objects to RDF/XML and imports them with n10s.rdf.import.inline; needs n10s initialized as above |
async_execute(query_message) |
Async form of execute(); await it only on the connection's own event loop |
Source: cimgraph/databases/neo4j/neo4j.py
<style>
['pre { line-height: 125%; }\ntd.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\nspan.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\ntd.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\nspan.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\n.highlight-ipynb .hll { background-color: var(--jp-cell-editor-active-background) }\n.highlight-ipynb { background: var(--jp-cell-editor-background); color: var(--jp-mirror-editor-variable-color) }\n.highlight-ipynb .c { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment */\n.highlight-ipynb .err { color: var(--jp-mirror-editor-error-color) } /* Error */\n.highlight-ipynb .k { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword */\n.highlight-ipynb .o { color: var(--jp-mirror-editor-operator-color); font-weight: bold } /* Operator */\n.highlight-ipynb .p { color: var(--jp-mirror-editor-punctuation-color) } /* Punctuation */\n.highlight-ipynb .ch { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Hashbang */\n.highlight-ipynb .cm { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Multiline */\n.highlight-ipynb .cp { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Preproc */\n.highlight-ipynb .cpf { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.PreprocFile */\n.highlight-ipynb .c1 { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Single */\n.highlight-ipynb .cs { color: var(--jp-mirror-editor-comment-color); font-style: italic } /* Comment.Special */\n.highlight-ipynb .kc { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Constant */\n.highlight-ipynb .kd { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Declaration */\n.highlight-ipynb .kn { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Namespace */\n.highlight-ipynb .kp { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Pseudo */\n.highlight-ipynb .kr { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Reserved */\n.highlight-ipynb .kt { color: var(--jp-mirror-editor-keyword-color); font-weight: bold } /* Keyword.Type */\n.highlight-ipynb .m { color: var(--jp-mirror-editor-number-color) } /* Literal.Number */\n.highlight-ipynb .s { color: var(--jp-mirror-editor-string-color) } /* Literal.String */\n.highlight-ipynb .ow { color: var(--jp-mirror-editor-operator-color); font-weight: bold } /* Operator.Word */\n.highlight-ipynb .pm { color: var(--jp-mirror-editor-punctuation-color) } /* Punctuation.Marker */\n.highlight-ipynb .w { color: var(--jp-mirror-editor-variable-color) } /* Text.Whitespace */\n.highlight-ipynb .mb { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Bin */\n.highlight-ipynb .mf { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Float */\n.highlight-ipynb .mh { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Hex */\n.highlight-ipynb .mi { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Integer */\n.highlight-ipynb .mo { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Oct */\n.highlight-ipynb .sa { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Affix */\n.highlight-ipynb .sb { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Backtick */\n.highlight-ipynb .sc { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Char */\n.highlight-ipynb .dl { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Delimiter */\n.highlight-ipynb .sd { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Doc */\n.highlight-ipynb .s2 { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Double */\n.highlight-ipynb .se { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Escape */\n.highlight-ipynb .sh { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Heredoc */\n.highlight-ipynb .si { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Interpol */\n.highlight-ipynb .sx { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Other */\n.highlight-ipynb .sr { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Regex */\n.highlight-ipynb .s1 { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Single */\n.highlight-ipynb .ss { color: var(--jp-mirror-editor-string-color) } /* Literal.String.Symbol */\n.highlight-ipynb .il { color: var(--jp-mirror-editor-number-color) } /* Literal.Number.Integer.Long */']
</style>