functions.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. """
  2. 通用函数工具集
  3. 提供常用的图数据库操作和数据处理功能
  4. """
  5. import logging
  6. from app.core.graph.graph_operations import connect_graph
  7. logger = logging.getLogger("app")
  8. def delete_relationships(node_id):
  9. """
  10. 删除指定节点的所有关系
  11. Args:
  12. node_id: 节点ID
  13. """
  14. try:
  15. cql = """
  16. MATCH (n)-[r]-()
  17. WHERE id(n) = $node_id
  18. DELETE r
  19. """
  20. with connect_graph().session() as session:
  21. session.run(cql, node_id=node_id)
  22. return True
  23. except Exception as e:
  24. logger.error(f"删除关系错误: {e}")
  25. return False
  26. def update_or_create_node(node_id, **properties):
  27. """
  28. 更新或创建节点
  29. Args:
  30. node_id: 节点ID
  31. **properties: 节点属性
  32. Returns:
  33. 节点对象
  34. """
  35. try:
  36. # 检查节点是否存在
  37. with connect_graph().session() as session:
  38. check_query = "MATCH (n) WHERE id(n) = $node_id RETURN n"
  39. result = session.run(check_query, node_id=node_id).single()
  40. if result:
  41. # 如果有属性则更新,否则只返回节点
  42. if properties:
  43. props_string = ", ".join([f"n.{key} = ${key}" for key in properties])
  44. update_query = f"""
  45. MATCH (n) WHERE id(n) = $node_id
  46. SET {props_string}
  47. RETURN n
  48. """
  49. result = session.run(update_query, node_id=node_id, **properties).single()
  50. return result["n"]
  51. else:
  52. # 节点不存在,无法更新
  53. logger.warning(f"节点 {node_id} 不存在,无法更新")
  54. return None
  55. except Exception as e:
  56. logger.error(f"更新或创建节点错误: {e}")
  57. return None
  58. def get_node_by_id_no_label(node_id):
  59. """
  60. 通过ID获取节点,不考虑标签
  61. Args:
  62. node_id: 节点ID
  63. Returns:
  64. 节点对象
  65. """
  66. try:
  67. with connect_graph().session() as session:
  68. query = "MATCH (n) WHERE id(n) = $node_id RETURN n"
  69. result = session.run(query, node_id=node_id).single()
  70. return result["n"] if result else None
  71. except Exception as e:
  72. logger.error(f"获取节点错误: {e}")
  73. return None