123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- """
- 通用函数工具集
- 提供常用的图数据库操作和数据处理功能
- """
- import logging
- from app.core.graph.graph_operations import connect_graph
- logger = logging.getLogger("app")
- def delete_relationships(node_id):
- """
- 删除指定节点的所有关系
-
- Args:
- node_id: 节点ID
- """
- try:
- cql = """
- MATCH (n)-[r]-()
- WHERE id(n) = $node_id
- DELETE r
- """
- with connect_graph().session() as session:
- session.run(cql, node_id=node_id)
- return True
- except Exception as e:
- logger.error(f"删除关系错误: {e}")
- return False
- def update_or_create_node(node_id, **properties):
- """
- 更新或创建节点
-
- Args:
- node_id: 节点ID
- **properties: 节点属性
-
- Returns:
- 节点对象
- """
- try:
- # 检查节点是否存在
- with connect_graph().session() as session:
- check_query = "MATCH (n) WHERE id(n) = $node_id RETURN n"
- result = session.run(check_query, node_id=node_id).single()
-
- if result:
- # 如果有属性则更新,否则只返回节点
- if properties:
- props_string = ", ".join([f"n.{key} = ${key}" for key in properties])
- update_query = f"""
- MATCH (n) WHERE id(n) = $node_id
- SET {props_string}
- RETURN n
- """
- result = session.run(update_query, node_id=node_id, **properties).single()
- return result["n"]
- else:
- # 节点不存在,无法更新
- logger.warning(f"节点 {node_id} 不存在,无法更新")
- return None
- except Exception as e:
- logger.error(f"更新或创建节点错误: {e}")
- return None
- def get_node_by_id_no_label(node_id):
- """
- 通过ID获取节点,不考虑标签
-
- Args:
- node_id: 节点ID
-
- Returns:
- 节点对象
- """
- try:
- with connect_graph().session() as session:
- query = "MATCH (n) WHERE id(n) = $node_id RETURN n"
- result = session.run(query, node_id=node_id).single()
- return result["n"] if result else None
- except Exception as e:
- logger.error(f"获取节点错误: {e}")
- return None
|