py2neo+flask+cytoscape.js展示Neo4j图数据(贴源码)

  1. 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')
  1. 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');
});
  1. index.html



    Cytoscape.js展示neo4j数据
    
    
    
    


  

网络图

  1. style.css
/* cytoscape graph */
#cy {
    height: 600px;
    width: 1200px;
    background-color: #f9f9f9;
}

目录结构


46-2.JPG

补充两句:

  1. py2neo.client.json.dehydrate方法解决该错误:
    TypeError: Object of type map is not JSON serializable
  2. 参考了以下链接:
    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

你可能感兴趣的:(py2neo+flask+cytoscape.js展示Neo4j图数据(贴源码))