gpt4 book ai didi

neo4j Cypher 分层树构建对 JSON 的响应

转载 作者:行者123 更新时间:2023-12-04 00:06:58 25 4
gpt4 key购买 nike

你能帮我建立密码查询吗?我有以下图形数据库结构:

(parent:Category)-[:subcategory]->(child:Category)

有了这个图形数据,我就有了深层次的分层树。

我在 Stackoverfllow.com 上找到了以下代码并针对我的数据进行了更改:

MATCH (root:Category)-[:subcategory]->(parent:Category)-[:subcategory]->(child:Category)
WITH root, {category: parent, children: collect(child)} AS parent_with_children
WHERE NOT(()-[:subcategory]->(root))
RETURN {category: root, children: collect(parent_with_children)}

但他仅针对具有 3 级树的深度构建响应。我需要更大的。我正在尝试像这个例子一样构建 json 响应:

  [
category: {
name: "PC"
children: {
category: {
name: "Parts"
children: {
category: {
name: "CPU"
...
}
}
},
category: {
name: "Accessories"
...
}
}
},
category: {
name: "Laptop"
...
}
]

Cypher 可以进行递归调用吗?我觉得这样会更好。

谢谢。

附:我知道关于 SO 有类似的问题,但它们对我没有帮助。

最佳答案

当叶子处于任意深度时,

Cypher 不太适合在树结构中转储图形数据。

但是,使用 neo4j 3.x,如果您能够安装 APOC plugin,则可以接近您想要的。在您的服务器上并使用 apoc.convert.toTree 过程。

首先,让我们创建一些示例数据:

CREATE
(c1:Category {name: 'PC'}),
(c1)-[:subcategory]->(c2:Category {name: 'Parts'}),
(c2)-[:subcategory]->(c3:Category {name: 'CPU'}),
(c3)-[:subcategory]->(c4:Category {name: 'CacheRAM'}),
(c1)-[:subcategory]->(c5:Category {name: 'Accessories'}),
(c5)-[:subcategory]->(c6:Category {name: 'Mouse'}),
(c5)-[:subcategory]->(c7:Category {name: 'Keyboard'}),
(c10:Category {name: 'Laptop'}),
(c10)-[:subcategory]->(c20:Category {name: 'Parts'}),
(c20)-[:subcategory]->(c30:Category {name: 'CPU'}),
(c10)-[:subcategory]->(c40:Category {name: 'Accessories'}),
(c40)-[:subcategory]->(c50:Category {name: 'Stylus'});

然后用这个查询:

MATCH p=(n:Category)-[:subcategory*]->(m)
WHERE NOT ()-[:subcategory]->(n)
WITH COLLECT(p) AS ps
CALL apoc.convert.toTree(ps) yield value
RETURN value;

...您将获得 N 个结果行,其中 N 是根 Category 节点的数量。以下是示例结果的片段:

{
...
"row": [
{
"_id": 150,
"_type": "Category",
"name": "PC",
"subcategory": [
{
"_id": 154,
"_type": "Category",
"name": "Accessories",
"subcategory": [
{
"_id": 156,
"_type": "Category",
"name": "Keyboard"
},
{
"_id": 155,
"_type": "Category",
"name": "Mouse"
}
]
},
{
"_id": 151,
"_type": "Category",
"name": "Parts",
"subcategory": [
{
"_id": 152,
"_type": "Category",
"name": "CPU",
"subcategory": [
{
"_id": 153,
"_type": "Category",
"name": "CacheRAM"
}
]
}
]
}
]
}
],
...
"row": [
{
"_id": 157,
"_type": "Category",
"name": "Laptop",
"subcategory": [
{
"_id": 158,
"_type": "Category",
"name": "Parts",
"subcategory": [
{
"_id": 159,
"_type": "Category",
"name": "CPU"
}
]
},
{
"_id": 160,
"_type": "Category",
"name": "Accessories",
"subcategory": [
{
"_id": 161,
"_type": "Category",
"name": "Stylus"
}
]
}
]
}
],
...
}

关于neo4j Cypher 分层树构建对 JSON 的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38578114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com