-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneoGraphManager.py
More file actions
194 lines (154 loc) · 7.25 KB
/
neoGraphManager.py
File metadata and controls
194 lines (154 loc) · 7.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
from py2neo import Database, Graph, Node, Relationship, NodeMatcher, Transaction
import logging
class NeoGraphManager:
'''
A simple class to manage Neo4j object graphs
using py2neo library
'''
def __init__(self,
uri: str = "bolt://localhost:7687",
user: str = "neo4j",
password: str = "password",
logger=None):
self._graph = Graph(uri=uri, auth=(user, password))
if logger:
self._logger = logger
else:
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
self._logger = logging.getLogger('NeoGraphManager')
self._logger.addHandler(handler)
self._logger.setLevel(logging.ERROR)
###########################################################################
def createNode(self, labels: list, properties: dict, transaction=None) -> Node:
try:
if not labels or len(labels) < 1:
raise ValueError(
"labels needs to contain at least the primary node type")
node = Node(*labels, **properties)
if transaction:
transaction.create(node)
else:
# create node within an autocommit transaction
self._graph.create(node)
self._logger.info(f"Created node {labels[0]}:{properties}")
return node
except Exception as ex:
self._logger.exception(f"\nError creating node:", ex)
raise
###########################################################################
def createRelationship(self,
sourceNode: Node,
relationship: str, targetNode: Node, transaction=None) -> Relationship:
rel = None
self._logger.debug(f"Creating relationship:{relationship} ")
try:
if transaction:
rel = transaction.create(Relationship(
sourceNode, relationship, targetNode))
else:
# create relationship within an autocommit transaction
rel = self._graph.create(Relationship(
sourceNode, relationship, targetNode))
self._logger.info(
f"Created relationship:{relationship} between node#{sourceNode.identity} and node#{targetNode.identity}")
return rel
except Exception as ex:
self._logger.exception(
f"\nError creating relationship:{relationship} Error:", ex)
raise
###########################################################################
def createIndex(self, nodeLabel: str, field: str):
self._logger.debug(f"Creating index on {nodeLabel}:{field}")
try:
query = f"CREATE INDEX ON :{nodeLabel}({field})"
self._graph.run(query)
self._logger.info(f"Created index on {nodeLabel}:{field}")
except Exception as ex:
self._logger.exception(f"\nError creating index:", ex)
raise
###########################################################################
def dropIndex(self, nodeLabel: str, field: str):
self._logger.debug(f"Dropping index for {nodeLabel}:{field}")
try:
query = f"DROP INDEX ON :{nodeLabel}({field})"
self._graph.run(query)
self._logger.info(f"Dropped index for {nodeLabel}:{field}")
except Exception as ex:
self._logger.exception(f"\nError dropping index:", ex)
raise
###########################################################################
def createUniqueConstraint(self, nodeLabel: str, field: str):
self._logger.debug(
f"Creating unique constraint on {nodeLabel}:{field}")
try:
query = f"CREATE CONSTRAINT ON (n:{nodeLabel}) ASSERT n.{field} IS UNIQUE"
self._graph.run(query)
self._logger.info(
f"Created unique constraint for {nodeLabel}:{field}")
except Exception as ex:
self._logger.exception(
f"\nError creating unique constraint on {nodeLabel}:{field}:", ex)
raise
###########################################################################
def startTransaction(self) -> Transaction:
tx = self._graph.begin()
return tx
###########################################################################
def queryResult(self, query):
# example query: "MATCH (a:Person) RETURN a.name, a.born LIMIT 4"
self._logger.debug(f"Executing query: {query}")
result = self._graph.run(query).data()
self._logger.debug(f"Result of query: {query} : {result}")
return result
###########################################################################
def getNodes(self,
nodeLabel: str,
property: str, operator: str, value: str,
orderByProperty: str = None,
nlimit: int = 10):
'''
This method will returns list of Nodes if the node property matches value.
Returns [] if nothing matches.
operators : = <> > >= < <= 'STARTS WITH' 'ENDS WITH' 'CONTAINS'
Refer to: https://py2neo.org/v4/matching.html?highlight=matcher#node-matching
'''
matcher = NodeMatcher(self._graph)
matchQuery = f"_.{property} {operator} {value}"
if orderByProperty:
searchNodes = list(matcher.match(nodeLabel).where(
matchQuery).order_by(f"_.{orderByProperty}").limit(nlimit))
else:
searchNodes = list(matcher.match(
nodeLabel).where(matchQuery).limit(nlimit))
self._logger.info(f"{len(searchNodes)} nodes matched search criteria")
return searchNodes
###########################################################################
def getNodeCount(self, label=None, properties: dict = None):
count = 0
if label:
if properties:
count = len(self._graph.nodes.match(label, **properties))
else:
count = len(self._graph.nodes.match(label))
else:
count = len(self._graph.nodes)
self._logger.info(
f"{count} nodes of type:{label} matched search criteria")
return count
###########################################################################
def deleteAllNodes(self, nodeLabel=None):
if nodeLabel:
self._logger.debug(f"Deleting all nodes of type:{nodeLabel}")
deleteQuery = f'MATCH (n:{nodeLabel}) DETACH DELETE n'
self._logger.debug(f"Deleted all nodes of type:{nodeLabel}")
else:
self._logger.debug(f"Deleting all nodes")
deleteQuery = f'MATCH (n) DETACH DELETE n'
self._logger.info(f"Deleted all nodes")
return self.queryResult(query=deleteQuery)
###############################################################################
# FINISH #
###############################################################################