|
@@ -273,4 +273,94 @@ def execute_cypher_query(cypher, params=None):
|
|
|
return data
|
|
|
except Exception as e:
|
|
|
logger.error(f"Error executing Cypher query: {str(e)}")
|
|
|
- raise e
|
|
|
+ raise e
|
|
|
+
|
|
|
+def get_node(label, **properties):
|
|
|
+ """
|
|
|
+ 查询具有给定标签和属性的节点
|
|
|
+
|
|
|
+ Args:
|
|
|
+ label (str): Neo4j节点标签
|
|
|
+ **properties: 作为关键字参数的节点属性
|
|
|
+
|
|
|
+ Returns:
|
|
|
+ 节点对象,如果不存在则返回None
|
|
|
+ """
|
|
|
+ try:
|
|
|
+ with connect_graph().session() as session:
|
|
|
+ # 构建查询条件
|
|
|
+ conditions = []
|
|
|
+ params = {}
|
|
|
+
|
|
|
+ # 处理ID参数
|
|
|
+ if 'id' in properties:
|
|
|
+ conditions.append("id(n) = $node_id")
|
|
|
+ params['node_id'] = properties['id']
|
|
|
+ # 移除id属性,避免在后续属性匹配中重复
|
|
|
+ properties_copy = properties.copy()
|
|
|
+ properties_copy.pop('id')
|
|
|
+ properties = properties_copy
|
|
|
+
|
|
|
+ # 处理其他属性
|
|
|
+ for key, value in properties.items():
|
|
|
+ conditions.append(f"n.{key} = ${key}")
|
|
|
+ params[key] = value
|
|
|
+
|
|
|
+ # 构建查询语句
|
|
|
+ where_clause = " AND ".join(conditions) if conditions else "TRUE"
|
|
|
+ query = f"""
|
|
|
+ MATCH (n:{label})
|
|
|
+ WHERE {where_clause}
|
|
|
+ RETURN n
|
|
|
+ LIMIT 1
|
|
|
+ """
|
|
|
+
|
|
|
+ # 执行查询
|
|
|
+ result = session.run(query, **params).single()
|
|
|
+ return result["n"] if result else None
|
|
|
+
|
|
|
+ except Exception as e:
|
|
|
+ logger.error(f"Error in get_node: {str(e)}")
|
|
|
+ return None
|
|
|
+
|
|
|
+def relationship_exists(start_node, rel_type, end_node, **properties):
|
|
|
+ """
|
|
|
+ 检查两个节点之间是否存在指定类型和属性的关系
|
|
|
+
|
|
|
+ Args:
|
|
|
+ start_node: 起始节点
|
|
|
+ rel_type: 关系类型
|
|
|
+ end_node: 结束节点
|
|
|
+ **properties: 关系的属性
|
|
|
+
|
|
|
+ Returns:
|
|
|
+ bool: 是否存在关系
|
|
|
+ """
|
|
|
+ try:
|
|
|
+ with connect_graph().session() as session:
|
|
|
+ # 构建查询语句
|
|
|
+ query = """
|
|
|
+ MATCH (a)-[r:%s]->(b)
|
|
|
+ WHERE id(a) = $start_id AND id(b) = $end_id
|
|
|
+ """ % rel_type
|
|
|
+
|
|
|
+ # 添加属性条件
|
|
|
+ if properties:
|
|
|
+ conditions = []
|
|
|
+ for key, value in properties.items():
|
|
|
+ conditions.append(f"r.{key} = ${key}")
|
|
|
+ query += " AND " + " AND ".join(conditions)
|
|
|
+
|
|
|
+ query += "\nRETURN count(r) > 0 as exists"
|
|
|
+
|
|
|
+ # 执行查询
|
|
|
+ params = {
|
|
|
+ 'start_id': start_node.identity,
|
|
|
+ 'end_id': end_node.identity,
|
|
|
+ **properties
|
|
|
+ }
|
|
|
+ result = session.run(query, **params).single()
|
|
|
+ return result and result["exists"]
|
|
|
+ except Exception as e:
|
|
|
+ logger.error(f"Error in relationship_exists: {str(e)}")
|
|
|
+ return False
|