package_function.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. # 封装mysql执行函数、创建节点函数
  2. from flask_sqlalchemy import SQLAlchemy
  3. from app.core.graph.graph_operations import connect_graph
  4. from py2neo import Node, RelationshipMatch
  5. import logging
  6. logger = logging.getLogger(__name__)
  7. db = SQLAlchemy()
  8. def execute_sql(cur, sql, params):
  9. result = db.session.execute(sql, params)
  10. return result.fetchall()
  11. def sql_commit(sql):
  12. try:
  13. db.session.execute(sql)
  14. db.session.commit()
  15. except Exception as e:
  16. db.session.rollback()
  17. raise e
  18. def sql_execute_result(sql):
  19. try:
  20. result = db.session.execute(sql)
  21. return result.fetchall()
  22. except Exception as e:
  23. raise e
  24. # 创建或获取节点
  25. """
  26. def create_or_get_node(label, **properties):
  27. node = connect_graph().nodes.match(label, **properties).first()
  28. if node is None:
  29. node = Node(label, **properties)
  30. connect_graph().create(node)
  31. return node
  32. """
  33. # 查询是否存在节点
  34. """
  35. def get_node(label, **properties):
  36. node = connect_graph.nodes.match(label, **properties).first()
  37. # 如果没有找到匹配的节点,node 将会是 None
  38. return node
  39. """
  40. # 关系权重生成
  41. def relation_weights(relation):
  42. relation_list = ['父亲', '母亲', '儿子', '女儿']
  43. if relation in relation_list:
  44. return 3
  45. else:
  46. return 1
  47. def workplace_weights(workplace_list, workplace):
  48. if workplace in workplace_list:
  49. return 3
  50. else:
  51. return 1
  52. def soure_organization_name(workplace):
  53. query = f"match (n:workplace)<-[r:workin]-(subordinate_person:worker)" \
  54. f"WHERE n.organization_no = '{workplace}' " \
  55. f"return subordinate_person.code as code"
  56. driver = None
  57. try:
  58. driver = connect_graph()
  59. with driver.session() as session:
  60. result = session.run(query)
  61. data = result.data()
  62. return data
  63. except (ConnectionError, ValueError) as e:
  64. logger.error(f"Neo4j数据库连接失败: {str(e)}")
  65. return []
  66. finally:
  67. if driver:
  68. driver.close()
  69. # 输入人员编码列表,得到员工与工作单位的关系,并且在此函数内完成员工,亲属,以及人-工作单位关系的创建
  70. def create_person_workplace(code_list, flag, relatives_type):
  71. nodes = []
  72. links = []
  73. condition = tuple(map(int, relatives_type.split(",")))
  74. relation_dict = {
  75. (0, 0, 0, 0): lambda: [],
  76. (0, 0, 0, 1): lambda: [],
  77. (0, 0, 1, 0): lambda: [],
  78. (0, 1, 0, 0): lambda: person_relative(links, code_list, 0),
  79. (0, 1, 0, 1): lambda: person_relative(links, code_list, 0),
  80. (0, 1, 1, 0): lambda: person_relative(links, code_list, 0),
  81. (0, 1, 1, 1): lambda: person_relative(links, code_list, 0),
  82. (1, 0, 0, 0): lambda: person_relative(links, code_list, 1),
  83. (1, 0, 0, 1): lambda: person_relative(links, code_list, 1),
  84. (1, 0, 1, 0): lambda: person_relative(links, code_list, 1),
  85. (1, 0, 1, 1): lambda: person_relative(links, code_list, 1),
  86. (1, 1, 0, 0): lambda: person_relative(links, code_list, (0, 1)),
  87. (1, 1, 0, 1): lambda: person_relative(links, code_list, (0, 1)),
  88. (1, 1, 1, 0): lambda: person_relative(links, code_list, (0, 1)),
  89. (1, 1, 1, 1): lambda: person_relative(links, code_list, (0, 1))
  90. }
  91. query = """
  92. MATCH (n:worker)-[r:relatives]-(m:worker), (n)-[:workin]-(wrk_n:workplace), (m)-[:workin]-(wrk_m:workplace)
  93. WHERE n.code IN $codes
  94. RETURN
  95. n.name as employee,
  96. id(n) as id_n,
  97. wrk_n.name as employee_workplace,
  98. id(wrk_n) as id_wrk_n,
  99. m.name as relatives,
  100. id(m) as id_m,
  101. wrk_m.name as relatives_workplace,
  102. id(wrk_m) as id_wrk_m,
  103. CASE WHEN exists(wrk_m.organization_no) THEN 1 ELSE 0 END as relatives_status
  104. """
  105. result = []
  106. driver = None
  107. try:
  108. driver = connect_graph()
  109. with driver.session() as session:
  110. result = session.run(query, codes=code_list).data()
  111. except (ConnectionError, ValueError) as e:
  112. logger.error(f"Neo4j数据库连接失败: {str(e)}")
  113. return nodes, links
  114. finally:
  115. if driver:
  116. driver.close()
  117. handle_function = relation_dict.get(condition, [])
  118. for row in result:
  119. employee = row['employee']
  120. id_employee = row['id_n']
  121. employee_workplace = row['employee_workplace']
  122. id_employee_workplace = row['id_wrk_n']
  123. relatives = row['relatives']
  124. id_relatives = row['id_m']
  125. relatives_workplace = row['relatives_workplace']
  126. id_relatives_workplace = row['id_wrk_m']
  127. relatives_status = row['relatives_status']
  128. nodes.extend(create_node(employee, id_employee, 'selected'))
  129. nodes.extend(create_node(employee_workplace, id_employee_workplace,
  130. 'work_place_selected' if flag else 'internel_work_place'))
  131. links.extend(create_relation(id_employee, id_employee_workplace, 'work_in'))
  132. temp_node, temp_link = handle_condition(condition, relatives, id_relatives, relatives_workplace,
  133. id_relatives_workplace, relatives_status)
  134. nodes.extend(temp_node)
  135. links.extend(temp_link)
  136. if condition[0] != 0 or condition[1] != 0:
  137. links.extend(handle_function())
  138. return nodes, links
  139. # 处理不同筛选条件的节点/关系
  140. def handle_condition(condition, relatives, id_relatives, relatives_workplace, id_relatives_workplace, relatives_status):
  141. nodes = []
  142. links = []
  143. if condition == (0, 0, 0, 1):
  144. nodes.extend(
  145. create_node(relatives_workplace, id_relatives_workplace, '' if relatives_status else 'externel_work_place'))
  146. elif condition == (0, 0, 1, 0):
  147. nodes.extend(
  148. create_node(relatives_workplace, id_relatives_workplace, 'internel_work_place' if relatives_status else ''))
  149. elif condition == (0, 0, 1, 1):
  150. nodes.extend(
  151. create_node(relatives_workplace, id_relatives_workplace,
  152. 'internel_work_place' if relatives_status else 'externel_work_place'))
  153. elif condition == (0, 1, 0, 0):
  154. nodes.extend(create_node(relatives, id_relatives, 'external_relatives' if relatives_status == 0 else ''))
  155. elif condition == (0, 1, 0, 1):
  156. nodes.extend(create_node(relatives, id_relatives, '' if relatives_status else 'external_relatives'))
  157. nodes.extend(
  158. create_node(relatives_workplace, id_relatives_workplace, '' if relatives_status else 'externel_work_place'))
  159. links.extend(create_relation(id_relatives, id_relatives_workplace if relatives_status == 0 else '', 'work_in'))
  160. elif condition == (0, 1, 1, 0):
  161. nodes.extend(create_node(relatives, id_relatives, '' if relatives_status else 'external_relatives'))
  162. nodes.extend(
  163. create_node(relatives_workplace, id_relatives_workplace, 'internel_work_place' if relatives_status else ''))
  164. elif condition == (0, 1, 1, 1):
  165. nodes.extend(create_node(relatives, id_relatives, '' if relatives_status else 'external_relatives'))
  166. nodes.extend(
  167. create_node(relatives_workplace, id_relatives_workplace,
  168. 'internel_work_place' if relatives_status else 'externel_work_place'))
  169. links.extend(create_relation(id_relatives, id_relatives_workplace if relatives_status == 0 else '', 'work_in'))
  170. elif condition == (1, 0, 0, 0):
  171. nodes.extend(create_node(relatives, id_relatives, 'internal_relatives' if relatives_status else ''))
  172. elif condition == (1, 0, 0, 1):
  173. nodes.extend(create_node(relatives, id_relatives, 'internal_relatives' if relatives_status else ''))
  174. nodes.extend(
  175. create_node(relatives_workplace, id_relatives_workplace, '' if relatives_status else 'externel_work_place'))
  176. elif condition == (1, 0, 1, 0):
  177. nodes.extend(create_node(relatives, id_relatives, 'internal_relatives' if relatives_status else ''))
  178. nodes.extend(
  179. create_node(relatives_workplace, id_relatives_workplace, 'internel_work_place' if relatives_status else ''))
  180. links.extend(create_relation(id_relatives, id_relatives_workplace if relatives_status else '', 'work_in'))
  181. elif condition == (1, 0, 1, 1):
  182. nodes.extend(create_node(relatives, id_relatives, 'internal_relatives' if relatives_status else ''))
  183. nodes.extend(
  184. create_node(relatives_workplace, id_relatives_workplace,
  185. 'internel_work_place' if relatives_status else 'externel_work_place'))
  186. links.extend(create_relation(id_relatives, id_relatives_workplace if relatives_status else '', 'work_in'))
  187. elif condition == (1, 1, 0, 0):
  188. nodes.extend(
  189. create_node(relatives, id_relatives, 'internal_relatives' if relatives_status else 'external_relatives'))
  190. elif condition == (1, 1, 0, 1):
  191. nodes.extend(
  192. create_node(relatives, id_relatives, 'internal_relatives' if relatives_status else 'external_relatives'))
  193. nodes.extend(
  194. create_node(relatives_workplace, id_relatives_workplace,
  195. 'externel_work_place' if relatives_status == 0 else ''))
  196. links.extend(create_relation(id_relatives, id_relatives_workplace if relatives_status == 0 else '', 'work_in'))
  197. elif condition == (1, 1, 1, 0):
  198. nodes.extend(
  199. create_node(relatives, id_relatives, 'internal_relatives' if relatives_status else 'external_relatives'))
  200. nodes.extend(
  201. create_node(relatives_workplace, id_relatives_workplace, 'internel_work_place' if relatives_status else ''))
  202. links.extend(create_relation(id_relatives, id_relatives_workplace if relatives_status else '', 'work_in'))
  203. elif condition == (1, 1, 1, 1):
  204. nodes.extend(
  205. create_node(relatives, id_relatives, 'internal_relatives' if relatives_status else 'external_relatives'))
  206. nodes.extend(
  207. create_node(relatives_workplace, id_relatives_workplace,
  208. 'internel_work_place' if relatives_status else 'externel_work_place'))
  209. links.extend(create_relation(id_relatives, id_relatives_workplace, 'work_in'))
  210. return nodes, links
  211. # 创建节点
  212. def create_node(name, nodeid, node_type):
  213. if name in (None, '无') or node_type == '':
  214. return []
  215. return [{'name': name, 'id': nodeid, 'type': node_type}]
  216. # 创建关系
  217. def create_relation(start, end, relation_type):
  218. if end in (None, '无', ''):
  219. return []
  220. return [{"source": start, "target": end, "type": relation_type}]
  221. # 创建员工和亲属的关系
  222. def person_relative(links, code_list, status):
  223. query = """
  224. MATCH (n:worker)-[r:relatives]-(m:worker)
  225. WHERE n.code IN $codes
  226. {}
  227. RETURN id(STARTNODE(r)) AS startnode, r.content AS content, id(ENDNODE(r)) AS endnode
  228. """.format("WITH CASE WHEN exists(m.code) THEN 1 ELSE 0 END AS status,r "
  229. "WHERE status = $relatives_status" if isinstance(status, int) else "")
  230. driver = None
  231. try:
  232. driver = connect_graph()
  233. with driver.session() as session:
  234. result = session.run(query, codes=code_list, relatives_status=status).data()
  235. except (ConnectionError, ValueError) as e:
  236. logger.error(f"Neo4j数据库连接失败: {str(e)}")
  237. return links
  238. finally:
  239. if driver:
  240. driver.close()
  241. for row in result:
  242. startnode = row['startnode']
  243. endnode = row['endnode']
  244. content = row['content']
  245. links.extend(create_relation(startnode, endnode, content))
  246. return links