routes.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. """
  2. Graph API module
  3. 提供图数据库操作的API接口
  4. """
  5. from flask import request, jsonify
  6. from app.api.graph import bp
  7. from app.models.result import success, failed
  8. from app.core.graph import (
  9. connect_graph,
  10. create_or_get_node,
  11. create_relationship,
  12. get_subgraph,
  13. execute_cypher_query
  14. )
  15. from app.core.graph.graph_operations import MyEncoder
  16. import logging
  17. import json
  18. logger = logging.getLogger("app")
  19. # 查询图数据
  20. @bp.route('/query', methods=['POST'])
  21. def query_graph():
  22. """
  23. 执行自定义Cypher查询
  24. Args (通过JSON请求体):
  25. cypher (str): Cypher查询语句
  26. params (dict, optional): 查询参数
  27. Returns:
  28. JSON: 包含查询结果的响应
  29. """
  30. try:
  31. # 获取查询语句
  32. cypher = request.json.get('cypher', '')
  33. params = request.json.get('params', {})
  34. if not cypher:
  35. return jsonify(failed("查询语句不能为空"))
  36. # 执行查询
  37. data = execute_cypher_query(cypher, params)
  38. return jsonify(success(data))
  39. except Exception as e:
  40. logger.error(f"图数据查询失败: {str(e)}")
  41. return jsonify(failed(str(e)))
  42. # 创建节点
  43. @bp.route('/node/create', methods=['POST'])
  44. def create_node():
  45. """
  46. 创建新节点
  47. Args (通过JSON请求体):
  48. labels (list): 节点标签列表
  49. properties (dict): 节点属性
  50. Returns:
  51. JSON: 包含创建的节点信息的响应
  52. """
  53. try:
  54. # 获取节点信息
  55. labels = request.json.get('labels', [])
  56. properties = request.json.get('properties', {})
  57. if not labels:
  58. return jsonify(failed("节点标签不能为空"))
  59. # 构建标签字符串
  60. label = ':'.join(labels)
  61. # 创建节点
  62. node_id = create_or_get_node(label, **properties)
  63. # 查询创建的节点
  64. cypher = f"MATCH (n) WHERE id(n) = {node_id} RETURN n"
  65. result = execute_cypher_query(cypher)
  66. if result and len(result) > 0:
  67. return jsonify(success(result[0]))
  68. else:
  69. return jsonify(failed("节点创建失败"))
  70. except Exception as e:
  71. logger.error(f"创建节点失败: {str(e)}")
  72. return jsonify(failed(str(e)))
  73. # 创建关系
  74. @bp.route('/relationship/create', methods=['POST'])
  75. def create_rel():
  76. """
  77. 创建节点间的关系
  78. Args (通过JSON请求体):
  79. startNodeId (int): 起始节点ID
  80. endNodeId (int): 结束节点ID
  81. type (str): 关系类型
  82. properties (dict, optional): 关系属性
  83. Returns:
  84. JSON: 包含创建的关系信息的响应
  85. """
  86. try:
  87. # 获取关系信息
  88. start_node_id = request.json.get('startNodeId')
  89. end_node_id = request.json.get('endNodeId')
  90. rel_type = request.json.get('type')
  91. properties = request.json.get('properties', {})
  92. if not all([start_node_id, end_node_id, rel_type]):
  93. return jsonify(failed("关系参数不完整"))
  94. # 创建关系
  95. rel_id = create_relationship(start_node_id, end_node_id, rel_type, **properties)
  96. if rel_id:
  97. # 查询创建的关系
  98. cypher = f"MATCH ()-[r]-() WHERE id(r) = {rel_id} RETURN r"
  99. result = execute_cypher_query(cypher)
  100. if result and len(result) > 0:
  101. return jsonify(success(result[0]))
  102. return jsonify(failed("关系创建失败"))
  103. except Exception as e:
  104. logger.error(f"创建关系失败: {str(e)}")
  105. return jsonify(failed(str(e)))
  106. # 获取图谱数据
  107. @bp.route('/subgraph', methods=['POST'])
  108. def get_graph_data():
  109. """
  110. 获取子图数据
  111. Args (通过JSON请求体):
  112. nodeIds (list): 节点ID列表
  113. relationshipTypes (list, optional): 关系类型列表
  114. maxDepth (int, optional): 最大深度,默认为1
  115. Returns:
  116. JSON: 包含节点和关系的子图数据
  117. """
  118. try:
  119. # 获取请求参数
  120. node_ids = request.json.get('nodeIds', [])
  121. rel_types = request.json.get('relationshipTypes', [])
  122. max_depth = request.json.get('maxDepth', 1)
  123. if not node_ids:
  124. return jsonify(failed("节点ID列表不能为空"))
  125. # 获取子图
  126. graph_data = get_subgraph(node_ids, rel_types, max_depth)
  127. return jsonify(success(graph_data))
  128. except Exception as e:
  129. logger.error(f"获取图谱数据失败: {str(e)}")
  130. return jsonify(failed(str(e)))