如何使用 jbuilder 从 Neo4j::ActiveModel 生成 GraphJSON
How to generate GraphJSON from Neo4j::ActiveModel using jbuilder
用于以浏览器alchemy.js requires data in the GraphJSON格式呈现图形数据的前端库,主要由nodes
和edges
顶级键组成。
考虑一个 Services
的图,它可以有 dependencies
(因此 dependent_services
):
class Service
include Neo4j::ActiveNode
has_many :out, :dependencies, type: :DEPENDS_ON, model_class: :Service
has_many :in, :dependent_services, origin: :dependencies, model_class: :Service
end
在 jbuilder 模板中检索节点数据非常有效:
nodes = ([service] + service.dependencies + service.dependent_services).uniq
json.nodes nodes do |node|
json.id node.id
json.name node.name
json.type node.class.to_s
json.url "#{url_for(node)}.json"
end
是否有一种巧妙的方法来检索节点之间的边列表(关系)?
我找到了一个相对优雅的解决方案,以防万一其他人正在寻找这个:
# Collect all relations into flat array
relations = [service.dependencies, service.dependent_services].map {|r| r.rels}.flatten
# Collect relation into edges array
json.edges relations.map do |edge|
json.source edge.start_node_id.to_s.to_i
json.target edge.end_node_id.to_s.to_i
json.caption edge.type
end
当然,第二部分是 jbuilder
具体的,但最重要的是 .rels
属性 包含所有 outgoing/incoming 关系的列表。
我正在为此使用 neo4j
gem @9.0.7,可以在此处找到文档:https://github.com/neo4jrb/neo4j-core/wiki/Relationship
用于以浏览器alchemy.js requires data in the GraphJSON格式呈现图形数据的前端库,主要由nodes
和edges
顶级键组成。
考虑一个 Services
的图,它可以有 dependencies
(因此 dependent_services
):
class Service
include Neo4j::ActiveNode
has_many :out, :dependencies, type: :DEPENDS_ON, model_class: :Service
has_many :in, :dependent_services, origin: :dependencies, model_class: :Service
end
在 jbuilder 模板中检索节点数据非常有效:
nodes = ([service] + service.dependencies + service.dependent_services).uniq
json.nodes nodes do |node|
json.id node.id
json.name node.name
json.type node.class.to_s
json.url "#{url_for(node)}.json"
end
是否有一种巧妙的方法来检索节点之间的边列表(关系)?
我找到了一个相对优雅的解决方案,以防万一其他人正在寻找这个:
# Collect all relations into flat array
relations = [service.dependencies, service.dependent_services].map {|r| r.rels}.flatten
# Collect relation into edges array
json.edges relations.map do |edge|
json.source edge.start_node_id.to_s.to_i
json.target edge.end_node_id.to_s.to_i
json.caption edge.type
end
当然,第二部分是 jbuilder
具体的,但最重要的是 .rels
属性 包含所有 outgoing/incoming 关系的列表。
我正在为此使用 neo4j
gem @9.0.7,可以在此处找到文档:https://github.com/neo4jrb/neo4j-core/wiki/Relationship