graph_operations.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. """
  2. Graph Database Core Operations
  3. 提供图数据库的基本操作功能
  4. """
  5. from neo4j import GraphDatabase
  6. from flask import current_app
  7. from app.services.neo4j_driver import Neo4jDriver
  8. import json
  9. import logging
  10. logger = logging.getLogger(__name__)
  11. class MyEncoder(json.JSONEncoder):
  12. """Neo4j数据序列化的自定义JSON编码器"""
  13. def default(self, obj):
  14. if isinstance(obj, (int, float, str, bool, list, dict, tuple, type(None))):
  15. return super(MyEncoder, self).default(obj)
  16. return str(obj)
  17. class GraphOperations:
  18. def __init__(self):
  19. self.driver = Neo4jDriver()
  20. def get_connection(self):
  21. return self.driver.connect()
  22. def close(self):
  23. self.driver.close()
  24. def connect_graph():
  25. """
  26. 连接到Neo4j图数据库
  27. Returns:
  28. Neo4j driver实例,如果连接失败则返回None
  29. """
  30. try:
  31. # 从Config获取Neo4j连接参数
  32. uri = current_app.config.get('NEO4J_URI')
  33. user = current_app.config.get('NEO4J_USER')
  34. password = current_app.config.get('NEO4J_PASSWORD')
  35. encrypted = current_app.config.get('NEO4J_ENCRYPTED')
  36. # 创建Neo4j驱动
  37. driver = GraphDatabase.driver(
  38. uri=uri,
  39. auth=(user, password),
  40. encrypted=encrypted
  41. )
  42. # 验证连接
  43. driver.verify_connectivity()
  44. return driver
  45. except Exception as e:
  46. # 处理连接错误
  47. logger.error(f"Error connecting to Neo4j database: {str(e)}")
  48. return None
  49. def create_or_get_node(label, **properties):
  50. """
  51. 创建具有给定标签和属性的新节点或获取现有节点
  52. 如果具有相同id的节点存在,则更新属性
  53. Args:
  54. label (str): Neo4j节点标签
  55. **properties: 作为关键字参数的节点属性
  56. Returns:
  57. 节点id
  58. """
  59. try:
  60. with connect_graph().session() as session:
  61. # 检查是否提供了id
  62. if 'id' in properties:
  63. node_id = properties['id']
  64. # 检查节点是否存在
  65. query = f"""
  66. MATCH (n:{label}) WHERE id(n) = $node_id
  67. RETURN n
  68. """
  69. result = session.run(query, node_id=node_id).single()
  70. if result:
  71. # 节点存在,更新属性
  72. props_string = ", ".join([f"n.{key} = ${key}" for key in properties if key != 'id'])
  73. if props_string:
  74. update_query = f"""
  75. MATCH (n:{label}) WHERE id(n) = $node_id
  76. SET {props_string}
  77. RETURN id(n) as node_id
  78. """
  79. result = session.run(update_query, node_id=node_id, **properties).single()
  80. return result["node_id"]
  81. return node_id
  82. # 如果到这里,则创建新节点
  83. props_keys = ", ".join([f"{key}: ${key}" for key in properties])
  84. create_query = f"""
  85. CREATE (n:{label} {{{props_keys}}})
  86. RETURN id(n) as node_id
  87. """
  88. result = session.run(create_query, **properties).single()
  89. return result["node_id"]
  90. except Exception as e:
  91. logger.error(f"Error in create_or_get_node: {str(e)}")
  92. raise e
  93. def create_relationship(start_node, end_node, relationship_type, properties=None):
  94. """
  95. 创建两个节点之间的关系
  96. Args:
  97. start_node: 起始节点
  98. end_node: 结束节点
  99. relationship_type: 关系类型
  100. properties: 关系属性
  101. Returns:
  102. 创建的关系对象
  103. """
  104. if not hasattr(start_node, 'id') or not hasattr(end_node, 'id'):
  105. raise ValueError("Invalid node objects provided")
  106. if properties is None:
  107. properties = {}
  108. query = """
  109. MATCH (start), (end)
  110. WHERE id(start) = $start_id AND id(end) = $end_id
  111. MERGE (start)-[r:%s]->(end)
  112. SET r += $properties
  113. RETURN r
  114. """ % relationship_type
  115. with connect_graph().session() as session:
  116. result = session.run(query,
  117. start_id=start_node.id,
  118. end_id=end_node.id,
  119. properties=properties)
  120. return result.single()["r"]
  121. def get_subgraph(node_ids, rel_types=None, max_depth=1):
  122. """
  123. 获取以指定节点为起点的子图
  124. Args:
  125. node_ids: 节点ID列表
  126. rel_types: 关系类型列表(可选)
  127. max_depth: 最大深度,默认为1
  128. Returns:
  129. 包含节点和关系的字典
  130. """
  131. try:
  132. # 处理节点ID列表
  133. node_ids_str = ', '.join([str(nid) for nid in node_ids])
  134. # 处理关系类型过滤
  135. rel_filter = ''
  136. if rel_types:
  137. rel_types_str = '|'.join(rel_types)
  138. rel_filter = f":{rel_types_str}"
  139. # 构建Cypher语句
  140. cypher = f"""
  141. MATCH path = (n)-[r{rel_filter}*0..{max_depth}]-(m)
  142. WHERE id(n) IN [{node_ids_str}]
  143. RETURN path
  144. """
  145. # 执行查询
  146. with connect_graph().session() as session:
  147. result = session.run(cypher)
  148. # 处理结果为图谱数据
  149. nodes = {}
  150. relationships = {}
  151. for record in result:
  152. path = record["path"]
  153. # 处理节点
  154. for node in path.nodes:
  155. if node.id not in nodes:
  156. node_dict = dict(node)
  157. node_dict['id'] = node.id
  158. node_dict['labels'] = list(node.labels)
  159. nodes[node.id] = node_dict
  160. # 处理关系
  161. for rel in path.relationships:
  162. if rel.id not in relationships:
  163. rel_dict = dict(rel)
  164. rel_dict['id'] = rel.id
  165. rel_dict['type'] = rel.type
  166. rel_dict['source'] = rel.start_node.id
  167. rel_dict['target'] = rel.end_node.id
  168. relationships[rel.id] = rel_dict
  169. # 转换为列表形式
  170. graph_data = {
  171. 'nodes': list(nodes.values()),
  172. 'relationships': list(relationships.values())
  173. }
  174. return graph_data
  175. except Exception as e:
  176. logger.error(f"Error getting subgraph: {str(e)}")
  177. raise e
  178. def execute_cypher_query(cypher, params=None):
  179. """
  180. 执行Cypher查询并返回结果
  181. Args:
  182. cypher: Cypher查询语句
  183. params: 查询参数(可选)
  184. Returns:
  185. 查询结果的列表
  186. """
  187. if params is None:
  188. params = {}
  189. try:
  190. with connect_graph().session() as session:
  191. result = session.run(cypher, **params)
  192. # 处理查询结果
  193. data = []
  194. for record in result:
  195. record_dict = {}
  196. for key, value in record.items():
  197. # 节点处理
  198. if hasattr(value, 'id') and hasattr(value, 'labels') and hasattr(value, 'items'):
  199. node_dict = dict(value)
  200. node_dict['_id'] = value.id
  201. node_dict['_labels'] = list(value.labels)
  202. record_dict[key] = node_dict
  203. # 关系处理
  204. elif hasattr(value, 'id') and hasattr(value, 'type') and hasattr(value, 'start_node'):
  205. rel_dict = dict(value)
  206. rel_dict['_id'] = value.id
  207. rel_dict['_type'] = value.type
  208. rel_dict['_start_node_id'] = value.start_node.id
  209. rel_dict['_end_node_id'] = value.end_node.id
  210. record_dict[key] = rel_dict
  211. # 路径处理
  212. elif hasattr(value, 'start_node') and hasattr(value, 'end_node') and hasattr(value, 'nodes'):
  213. path_dict = {
  214. 'nodes': [dict(node) for node in value.nodes],
  215. 'relationships': [dict(rel) for rel in value.relationships]
  216. }
  217. record_dict[key] = path_dict
  218. # 其他类型直接转换
  219. else:
  220. record_dict[key] = value
  221. data.append(record_dict)
  222. return data
  223. except Exception as e:
  224. logger.error(f"Error executing Cypher query: {str(e)}")
  225. raise e
  226. def get_node(label, **properties):
  227. """
  228. 查询具有给定标签和属性的节点
  229. Args:
  230. label (str): Neo4j节点标签
  231. **properties: 作为关键字参数的节点属性
  232. Returns:
  233. 节点对象,如果不存在则返回None
  234. """
  235. try:
  236. with connect_graph().session() as session:
  237. # 构建查询条件
  238. conditions = []
  239. params = {}
  240. # 处理ID参数
  241. if 'id' in properties:
  242. conditions.append("id(n) = $node_id")
  243. params['node_id'] = properties['id']
  244. # 移除id属性,避免在后续属性匹配中重复
  245. properties_copy = properties.copy()
  246. properties_copy.pop('id')
  247. properties = properties_copy
  248. # 处理其他属性
  249. for key, value in properties.items():
  250. conditions.append(f"n.{key} = ${key}")
  251. params[key] = value
  252. # 构建查询语句
  253. where_clause = " AND ".join(conditions) if conditions else "TRUE"
  254. query = f"""
  255. MATCH (n:{label})
  256. WHERE {where_clause}
  257. RETURN n
  258. LIMIT 1
  259. """
  260. # 执行查询
  261. result = session.run(query, **params).single()
  262. return result["n"] if result else None
  263. except Exception as e:
  264. logger.error(f"Error in get_node: {str(e)}")
  265. return None
  266. def relationship_exists(start_node, rel_type, end_node, **properties):
  267. """
  268. 检查两个节点之间是否存在指定类型和属性的关系
  269. Args:
  270. start_node: 起始节点
  271. rel_type: 关系类型
  272. end_node: 结束节点
  273. **properties: 关系的属性
  274. Returns:
  275. bool: 是否存在关系
  276. """
  277. try:
  278. with connect_graph().session() as session:
  279. # 构建查询语句
  280. query = """
  281. MATCH (a)-[r:%s]->(b)
  282. WHERE id(a) = $start_id AND id(b) = $end_id
  283. """ % rel_type
  284. # 添加属性条件
  285. if properties:
  286. conditions = []
  287. for key, value in properties.items():
  288. conditions.append(f"r.{key} = ${key}")
  289. query += " AND " + " AND ".join(conditions)
  290. query += "\nRETURN count(r) > 0 as exists"
  291. # 执行查询
  292. params = {
  293. 'start_id': start_node.id,
  294. 'end_id': end_node.id,
  295. **properties
  296. }
  297. result = session.run(query, **params).single()
  298. return result and result["exists"]
  299. except Exception as e:
  300. logger.error(f"Error in relationship_exists: {str(e)}")
  301. return False