- app.py
# coding=utf-8
from flask import Flask, jsonify, render_template
from py2neo import Graph
import py2neo.client.json
app = Flask(__name__)
graph = Graph()
def buildNodes(nodeRecord):
data = {"id": str(nodeRecord['id']), "label": next(iter(nodeRecord['label']))}
data.update(nodeRecord['n'])
return {"data": data}
def buildEdges(relationRecord):
data = {"source": str(relationRecord['start_id']), "target": str(relationRecord['end_id']), "relationship": relationRecord['type']}
return {"data": data}
@app.route('/')
def index():
return render_template('index.html')
@app.route('/graph')
def get_graph():
nodes = list(map(buildNodes, py2neo.client.json.dehydrate(graph.run('MATCH (n) RETURN id(n) as id, labels(n) as label, n').data())))
edges = list(map(buildEdges, py2neo.client.json.dehydrate(graph.run('MATCH (n1)-[r]->(n2) RETURN id(r) as id, id(n1) as start_id, id(n2) as end_id, type(r) as type, r').data())))
return jsonify(elements = {"nodes": nodes, "edges": edges})
if __name__ == '__main__':
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.run(debug = True, host='10.110.41.71')
- getJsonData.js
$(function(){
$.get('/graph', function(result) {
var cy = cytoscape({
container: document.getElementById('cy'),
style: [
{ selector: 'node[label = "Person"]',
style: {'background-color': '#6FB1FC', 'label': 'data(name)'}
},
{ selector: 'node[label = "Movie"]',
style: {'background-color': '#F5A45D', 'label': 'data(title)'}
},
{
selector: 'edge',
style: {
'width': 3,
'line-color': 'blue',
'target-arrow-color': 'red',
'target-arrow-shape': 'triangle',
'curve-style': 'bezier'
}
}
],
layout: { name: 'cose'},
elements: result.elements
});
}, 'json');
});
- index.html
<!DOCTYPE html>
<html>
<head>
<title>Cytoscape.js展示neo4j数据</title>
<link href="/static/css/style.css" rel="stylesheet" />
<script src="/static/js/jquery-3.6.0.min.js"></script>
<script src="/static/js/cytoscape.min.js"></script>
<script src="/static/js/getJsonData.js"></script>
</head>
<body>
<h1>网络图</h1>
<div id="cy"></div>
</body>
</html>
- style.css
/* cytoscape graph */
#cy {
height: 600px;
width: 1200px;
background-color: #f9f9f9;
}
目录结构
补充两句:
- py2neo.client.json.dehydrate方法解决该错误:
TypeError: Object of type map is not JSON serializable - 参考了以下链接:
https://www.jetbrains.com/pycharm/download/#section=windows
http://blog.csdn.net/zhongzhu2002/article/details/45843283
http://blog.csdn.net/zhongzhu2002/article/details/46043047
http://blog.csdn.net/zhongzhu2002/article/details/46049197
https://blog.csdn.net/weixin_39430584/article/details/83380636
https://dormousehole.readthedocs.io/en/latest/
https://js.cytoscape.org/
https://jquery.com/download/
https://py2neo.org/2021.0/database/index.html