KGAPI.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. from pprint import pprint
  2. import requests
  3. import json
  4. from hashlib import md5
  5. import uvicorn
  6. from fastapi import FastAPI
  7. from typing import Optional
  8. app = FastAPI()
  9. def getQaAttachment(data):
  10. nodes = []
  11. ids = []
  12. links = []
  13. for d in data:
  14. if not d['target']['id']:
  15. d['target']['id'] = md5(str(d['target']['entity']).encode(encoding='UTF-8')).hexdigest()
  16. if not d['target']['id'] in ids:
  17. nodes.append({"id":d['target']['id'], "name": str(d['target']['entity']), "target":True, "source":False})
  18. ids.append(d['target']['id'])
  19. if not d['source']['id'] in ids:
  20. nodes.append({"id":d['source']['id'], "name": d['source']['entity'], "source":True, "target":False})
  21. ids.append(d['source']['id'])
  22. links.append({'source': d['source']['id'], 'name':d["relation"], 'target': d['target']['id']})
  23. return nodes, links
  24. # 请求头
  25. headers = {
  26. "token": '369ca613c7a74a58b0f95be2cfd59257',
  27. "Content-Type": "application/json",
  28. }
  29. @app.get('/person_to_person')
  30. def search_person(query: str, less: Optional[bool] = False):
  31. """
  32. # 人与人的相关关系查询
  33. # 必选参数:
  34. # query: 人名
  35. # 可选参数
  36. # less: 显示少量关系
  37. """
  38. url = 'http://180.76.188.39:8085/mpks/api/extra/gremlin'
  39. if less:
  40. json_obj = {
  41. # "gremlin": "g.has('name.@value', MATCH, '"+ query +"').outE(['当前公司','最高学历学校']).inV.inE('相关机构').outV.with('*').graph"
  42. "gremlin": "g.has('name.@value', MATCH, '"+ query +"').outE('相关机构').limit(8).inV.inE('相关机构').outV.with('*').graph"
  43. }
  44. else:
  45. json_obj = {
  46. "gremlin": "g.has('name.@value', MATCH, '"+ query +"').outE('相关机构').inV.inE('相关机构').outV.with('*').graph"
  47. }
  48. # 请求查询
  49. r = requests.post(url, headers=headers, json=json_obj)
  50. rst = json.loads(r.text)
  51. entity_array = []
  52. nodes = []
  53. links = []
  54. ids = dict([])
  55. # 查询成功
  56. if (rst['errno'] == 0) and rst['data']:
  57. # 所有实体
  58. for entity in rst['data']['vertices']:
  59. if entity["@id"] not in ids:
  60. ids[entity["@id"]] = entity["name"]
  61. nodes.append({
  62. "id": entity["@id"],
  63. "name": entity["name"],
  64. "target": False if (entity["@type"] == "人才特征demo") else True,
  65. "source": True if (entity["@type"] == "人才特征demo") else False,
  66. "itemStyle": {
  67. "normal": {
  68. "color": 'red' if (entity["@type"] == "人才特征demo") else 'blue'
  69. }
  70. },
  71. })
  72. for edge in rst['data']['edges']:
  73. source = {'id': edge['@from'], 'entity': ids[edge['@from']], "refId": None, "entityIndex": None}
  74. target = {'id': edge['@to'], 'entity': ids[edge['@to']], "refId": None, "entityIndex": None}
  75. relation = edge['@label']
  76. entity_array.append({"source": source, "relation": relation, "target": target})
  77. links.append({'source': edge['@from'], 'name': edge['@label'], 'target': edge['@to']})
  78. else:
  79. pprint(rst['errno'])
  80. pprint(rst['msg'])
  81. return {"errno": 0, "msg": [], "graph": entity_array, "nodes": nodes, "links": links}
  82. @app.get('/search_query')
  83. def search_query(query: str):
  84. """
  85. # 搜索接口,模糊搜索
  86. # 參數:
  87. # query: 查詢的關鍵詞
  88. """
  89. entity_array = []
  90. base_url = 'http://180.76.188.39:8085/mpks/api/search'
  91. json_obj = {
  92. "query": query,
  93. "sort": "relevance",
  94. "needCorrect": True,
  95. "saveHistory": False
  96. }
  97. r = requests.post(base_url, headers=headers, json=json_obj)
  98. rst = json.loads(r.text)
  99. # 查询结果
  100. if (rst['errno'] == 0) and rst['data']:
  101. # 当前实体
  102. source = {'id': rst['data']['results'][0]['entityList'][0]['@id'], 'entity': rst['data']['results'][0]['entityList'][0]['name'],'refId': None, "entityIndex": None}
  103. # 实体属性关系
  104. for dic in rst['data']['results'][0]['entityList'][0]['properties']:
  105. relation = dic['key']
  106. # 关系
  107. if isinstance(dic['value'], dict) and ("@id" in dic['value']):
  108. target = {"id": dic['value']['@id'], "entity":dic['value']['value'], 'refId': None, "entityIndex": None}
  109. entity_array.append({"source": source, "relation": relation, "target": target})
  110. # 属性
  111. elif (not isinstance(dic['value'], list)) or ("@id" not in dic['value'][0]):
  112. target = {"id": None, "entity":dic['value'], 'refId': None, "entityIndex": None}
  113. entity_array.append({"source": source, "relation": relation, "target": target})
  114. # 关系
  115. else:
  116. for vec in dic['value']:
  117. target = {"id": vec["@id"], "entity": vec["value"], 'refId': None, "entityIndex": None}
  118. entity_array.append({"source": source, "relation": relation, "target": target})
  119. # 边
  120. for edge in rst['data']['results'][0]['entityList'][0]['graphData']['vertices']:
  121. relation = edge['@type'].replace('demo', '')
  122. target = {"id": edge["@id"], "entity": edge["name"], 'refId': None, "entityIndex": None}
  123. entity_array.append({"source": source, "relation": relation, "target": target})
  124. else:
  125. pprint(rst['errno'])
  126. pprint(rst['msg'])
  127. nodes, links = getQaAttachment(entity_array)
  128. return {"errno": 0, "msg": [], "graph": entity_array, "nodes": nodes, "links": links}
  129. @app.get('/search_gremlin')
  130. def search_gremlin(query: Optional[str] = None, _id: Optional[str] = None):
  131. """
  132. # 搜索接口,精确搜索
  133. # 參數:
  134. # query[可选]: 使用实体名称查询
  135. # _id [可选]: 使用实体 id 查询
  136. # 同时填写时 _id 优先
  137. g.has("name.@value",MATCH,"于策").outE("相关机构").inV.inE("相关机构").outV.with("*").graph
  138. """
  139. # 请求地址
  140. url = 'http://180.76.188.39:8085/mpks/api/extra/gremlin'
  141. # 查询语句
  142. if _id:
  143. json_obj = {
  144. "gremlin" : "g.key('"+ _id +"').both.with('*').graph"
  145. }
  146. elif query:
  147. json_obj = {
  148. "gremlin" : "g.has('name.@value', MATCH, '"+ query +"').both.with('*').graph"
  149. }
  150. else:
  151. return {"errno": 3001, "msg": "can not get query or id", "data": []}
  152. # 请求查询
  153. r = requests.post(url, headers=headers, json=json_obj)
  154. rst = json.loads(r.text)
  155. entity_array = []
  156. # 查询成功
  157. if (rst['errno'] == 0) and rst['data']:
  158. # 当前实体
  159. source = {'id': rst['data']['vertices'][0]['@id'], 'entity': rst['data']['vertices'][0]['name'],'refId': None, "entityIndex": None}
  160. # 属性
  161. for relation in rst['data']['vertices'][0].keys():
  162. if relation not in ['@context', '@del', '@edge_number', '@formattype', '@fromtype', '@fromurl', '@id', '@kbid', '@nodeid', '@semiid', '@tags', '@type', '_id', '_type', 'alias', 'appId', 'name', 'nodeId', 'tags', '教育经历', '工作经历', '项目经历', '培训和海外经历', '最高学历学校', '当前公司']:
  163. target = {'id': None, 'entity': rst['data']['vertices'][0][relation], 'refId': None, "entityIndex": None}
  164. if rst['data']['vertices'][0][relation]:
  165. entity_array.append({"source": source, "relation": relation, "target": target})
  166. # 关系
  167. if len(rst['data']['vertices']) > 1:
  168. for index in range(1, len(rst['data']['vertices'])):
  169. target = {'id': rst['data']['vertices'][index]['@id'], 'entity': rst['data']['vertices'][index]['name'], 'refId': None, "entityIndex": None}
  170. for edge in rst['data']['edges']:
  171. if edge['@from'] == rst['data']['vertices'][index]['@id']:
  172. entity_array.append({"source": target, "relation": edge['@label'].replace('demo', ''), "target": source})
  173. break
  174. else:
  175. entity_array.append({"source": source, "relation": rst['data']['vertices'][index]['@type'].replace('demo', ''), "target": target})
  176. # 边
  177. # for edge in rst['data']['edges']:
  178. # target = {'id': edge['@to'], 'entity': None, "refId": edge['@from'], "entityIndex": source_index}
  179. # relation = edge['@label']
  180. # entity_array.append({"source": source, "relation": relation, "target": target})
  181. else:
  182. pprint(rst['errno'])
  183. pprint(rst['msg'])
  184. nodes, links = getQaAttachment(entity_array)
  185. return {"errno": 0, "msg": [], "graph": entity_array, "nodes": nodes, "links": links}
  186. if __name__ == '__main__':
  187. uvicorn.run(app=app, host='0.0.0.0', port=9000)