graph_operations.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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_id, end_node_id, rel_type, **properties):
  94. """
  95. 在两个节点之间创建关系
  96. Args:
  97. start_node_id: 起始节点ID
  98. end_node_id: 结束节点ID
  99. rel_type: 关系类型
  100. **properties: 关系的属性
  101. Returns:
  102. 关系的ID
  103. """
  104. try:
  105. # 构建属性部分
  106. properties_str = ', '.join([f"{k}: ${k}" for k in properties.keys()])
  107. properties_part = f" {{{properties_str}}}" if properties else ""
  108. # 构建Cypher语句
  109. cypher = f"""
  110. MATCH (a), (b)
  111. WHERE id(a) = $start_node_id AND id(b) = $end_node_id
  112. CREATE (a)-[r:{rel_type}{properties_part}]->(b)
  113. RETURN id(r) as rel_id
  114. """
  115. # 执行创建
  116. with connect_graph().session() as session:
  117. params = {
  118. 'start_node_id': int(start_node_id),
  119. 'end_node_id': int(end_node_id),
  120. **properties
  121. }
  122. result = session.run(cypher, **params).single()
  123. if result:
  124. return result["rel_id"]
  125. else:
  126. logger.error("Failed to create relationship")
  127. return None
  128. except Exception as e:
  129. logger.error(f"Error creating relationship: {str(e)}")
  130. raise e
  131. def get_subgraph(node_ids, rel_types=None, max_depth=1):
  132. """
  133. 获取以指定节点为起点的子图
  134. Args:
  135. node_ids: 节点ID列表
  136. rel_types: 关系类型列表(可选)
  137. max_depth: 最大深度,默认为1
  138. Returns:
  139. 包含节点和关系的字典
  140. """
  141. try:
  142. # 处理节点ID列表
  143. node_ids_str = ', '.join([str(nid) for nid in node_ids])
  144. # 处理关系类型过滤
  145. rel_filter = ''
  146. if rel_types:
  147. rel_types_str = '|'.join(rel_types)
  148. rel_filter = f":{rel_types_str}"
  149. # 构建Cypher语句
  150. cypher = f"""
  151. MATCH path = (n)-[r{rel_filter}*0..{max_depth}]-(m)
  152. WHERE id(n) IN [{node_ids_str}]
  153. RETURN path
  154. """
  155. # 执行查询
  156. with connect_graph().session() as session:
  157. result = session.run(cypher)
  158. # 处理结果为图谱数据
  159. nodes = {}
  160. relationships = {}
  161. for record in result:
  162. path = record["path"]
  163. # 处理节点
  164. for node in path.nodes:
  165. if node.id not in nodes:
  166. node_dict = dict(node)
  167. node_dict['id'] = node.id
  168. node_dict['labels'] = list(node.labels)
  169. nodes[node.id] = node_dict
  170. # 处理关系
  171. for rel in path.relationships:
  172. if rel.id not in relationships:
  173. rel_dict = dict(rel)
  174. rel_dict['id'] = rel.id
  175. rel_dict['type'] = rel.type
  176. rel_dict['source'] = rel.start_node.id
  177. rel_dict['target'] = rel.end_node.id
  178. relationships[rel.id] = rel_dict
  179. # 转换为列表形式
  180. graph_data = {
  181. 'nodes': list(nodes.values()),
  182. 'relationships': list(relationships.values())
  183. }
  184. return graph_data
  185. except Exception as e:
  186. logger.error(f"Error getting subgraph: {str(e)}")
  187. raise e
  188. def execute_cypher_query(cypher, params=None):
  189. """
  190. 执行Cypher查询并返回结果
  191. Args:
  192. cypher: Cypher查询语句
  193. params: 查询参数(可选)
  194. Returns:
  195. 查询结果的列表
  196. """
  197. if params is None:
  198. params = {}
  199. try:
  200. with connect_graph().session() as session:
  201. result = session.run(cypher, **params)
  202. # 处理查询结果
  203. data = []
  204. for record in result:
  205. record_dict = {}
  206. for key, value in record.items():
  207. # 节点处理
  208. if hasattr(value, 'id') and hasattr(value, 'labels') and hasattr(value, 'items'):
  209. node_dict = dict(value)
  210. node_dict['_id'] = value.id
  211. node_dict['_labels'] = list(value.labels)
  212. record_dict[key] = node_dict
  213. # 关系处理
  214. elif hasattr(value, 'id') and hasattr(value, 'type') and hasattr(value, 'start_node'):
  215. rel_dict = dict(value)
  216. rel_dict['_id'] = value.id
  217. rel_dict['_type'] = value.type
  218. rel_dict['_start_node_id'] = value.start_node.id
  219. rel_dict['_end_node_id'] = value.end_node.id
  220. record_dict[key] = rel_dict
  221. # 路径处理
  222. elif hasattr(value, 'start_node') and hasattr(value, 'end_node') and hasattr(value, 'nodes'):
  223. path_dict = {
  224. 'nodes': [dict(node) for node in value.nodes],
  225. 'relationships': [dict(rel) for rel in value.relationships]
  226. }
  227. record_dict[key] = path_dict
  228. # 其他类型直接转换
  229. else:
  230. record_dict[key] = value
  231. data.append(record_dict)
  232. return data
  233. except Exception as e:
  234. logger.error(f"Error executing Cypher query: {str(e)}")
  235. raise e