我使用以下cypher查询从neo4j数据库中提取节点和关系: match p =(:Root)< - [:linkedTo] - () 展开节点(p)作为n展开rels(p)为r return {nodes:collect(distinct n),links:collect(distinct {source:id(endNode(r)),target:id(startNode(r))})}
我将查询结果转换为节点和链接数组,如下所示:
var obj = JSON.parse(xmlhttp.responseText);
var json = obj.data[0][0];
// Extract node list from neo4j/json data
var nodes = [];
for (n in json.nodes) {
var nodeObj = json.nodes[n];
var node = nodeObj.data;
node.id = nodeObj.metadata.id;
node.type = nodeObj.metadata.labels[0];
nodes.push(node);
}
// Create a node map
var nodeMap = {};
nodes.forEach(function(x) { nodeMap['_'+x.id] = x; nodeMap['_'+x.id].children = []; });
// Extract link list from neo4j/json data
var links = json.links.map(function(x) {
nodeMap['_'+x.source].children.push(nodeMap['_'+x.target]);
return { source: nodeMap['_'+x.source], target: nodeMap['_'+x.target] };
});
如何从节点和链接生成d3中的树? Console.log()显示节点和链接数组都具有正确的格式,每个节点还包含其子节点列表。
答案 0 :(得分:2)
如上所述,数据结构对于节点和子节点是正确的。缺少的部分是根节点。因此,我更改了cypher查询以识别根节点,该节点在我的图中追加为root,如下所示:
match p=(:Panel) <-[:belongsTo]- (), (root:Panel {Name: "root"})
unwind nodes(p) as n unwind rels(p) as r
return {root: id(root), nodes: collect(distinct n), links: collect(distinct {source: id(endNode(r)), target: id(startNode(r))})}
因此,树在http://bl.ocks.org/d3noob/8324872:
中按照建议声明var tree = d3.layout.tree()
.size([360, radius - 120]);
var diagonal = d3.svg.diagonal.radial()
.projection(function(d) { return [d.y, d.x / 180 * Math.PI]; });
var vis = d3.select("#chart").append("svg")
.attr("width", radius * 2)
.attr("height", radius * 2 - 150)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
// Compute the new tree layout starting with root
var root = nodeMap['_'+json.root];
var nodes = tree.nodes(root).reverse(), links = tree.links(nodes);
...
总而言之,诀窍是以JSON格式报告来自neo4j的根,节点和链接,然后构建节点数组,节点映射并根据链接将子节点分配给节点映射中的节点。