用flask_restful开发基于Neo4j的API接口

下面是一个用于在前端页面显示知识图谱的API接口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from flask import Flask
from flask_restful import Resource, Api
from py2neo import Graph

app = Flask(__name__)
api = Api(app)

class get_graph(Resource):
def get(self, query_node_name, query_node_label):
graph = Graph('http://localhost:7474', username='neo4j', password='****')

json_data = {}
d0 = graph.run("MATCH (a:"+query_node_label+") WHERE a.name = '"+query_node_name+"' RETURN id(a) as node_id, labels(a)[0] as node_label").data()
if d0:
node0_name = query_node_name
node0_id = d0[0]['node_id']
node0_label = d0[0]['node_label']
# print(node0_name, node0_label)

nodes_id = []
nodes_name = []
nodes_label = []

nid_p1 = []
r_p1 = []

nid_p2 = []
r_p2 = []

d1 = graph.run("MATCH (a)-[r]->(b) WHERE a.name = '"+node0_name+"' RETURN type(r) as relation, labels(b)[0] as node_label, b.name as node_name, id(b) as node_id").data()

for node in d1:
nid_p1.append(node['node_id'])
r_p1.append(node['relation'])

if node['node_id'] not in nodes_id:
nodes_id.append(node['node_id'])
nodes_name.append(node['node_name'])
nodes_label.append(node['node_label'])

d2 = graph.run("MATCH (a)-[r]->(b) WHERE b.name = '"+node0_name+"' RETURN type(r) as relation, labels(a)[0] as node_label, a.name as node_name, id(a) as node_id").data()

for node in d2:
nid_p2.append(node['node_id'])
r_p2.append(node['relation'])

if node['node_id'] not in nodes_id:
nodes_id.append(node['node_id'])
nodes_name.append(node['node_name'])
nodes_label.append(node['node_label'])

nodes_list = []
node0_json = {
"id": node0_id,
"name": node0_name,
"category": node0_label,
"score": 1
}
nodes_list.append(node0_json)
for node_id in nodes_id:
node_json = {
"id": node_id,
"name": nodes_name[nodes_id.index(node_id)],
"category": nodes_label[nodes_id.index(node_id)],
"score": 1
}
nodes_list.append(node_json)

links_list = []
for node_id in nid_p1:
link = {
"source": node0_id,
"target": node_id,
"label": r_p1[nid_p1.index(node_id)]
}
links_list.append(link)
for node_id in nid_p2:
link = {
"source": node_id,
"target": node0_id,
"label": r_p2[nid_p2.index(node_id)]
}
links_list.append(link)

json_data['data'] = {}
json_data['data']['nodes'] = nodes_list
json_data['data']['links'] = links_list
return json_data, 200
else:
json_data['data'] = {}
return json_data, 200

api.add_resource(get_graph, '/get_graph/<query_node_name>/<query_node_label>')

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5008)
0%