我有neo4j
数据,如下所示:
此处COUNTEY_PROVINCE
与country
之间存在province
关系,PROVINCE_CITY
与province
和city
关系COUNTRY_CITY
关系在country
和city
之间。当用户使用country name
调用api时,我想要使用province
返回所有city
。为此,我运行了以下查询:
MATCH path=(cn:Country { name: "Bangladesh" })-[:COUNTRY_PROVINCE]->(pv:Province)-[:PROVINCE_CITY]->(ct:City)
RETURN { x: nodes(path) }
我得到以下结果(国家,省,市):
{ x: nodes(path) }
{ "x": [ { "name": "Bangladesh"}, { "name": "Dhaka" }, { "name": "Dhaka" } ] }
{ "x": [ { "name": "Bangladesh"}, { "name": "Dhaka" }, { "name": "Narayanganj" } ] }
{ "x": [ { "name": "Bangladesh"}, { "name": "Sylhet" }, { "name": "Sylhet" } ] }
{ "x": [ { "name": "Bangladesh"}, { "name": "Khulna" }, { "name": "Khulna" } ] }
{ "x": [ { "name": "Bangladesh"}, { "name": "Khulna" }, { "name": "Jessore" } ] }
{ "x": [ { "name": "Bangladesh"}, { "name": "Chittagong" }, { "name": "Chittagong" } ] }
{ "x": [ { "name": "Bangladesh"}, { "name": "Chittagong" }, { "name": "Comilla" } ] }
现在我的问题是,如何获得省和联系城市的国家/地区列表,如:
[
{
country: {
name: "Bangladesh",
province: [
{
name: "Dhaka",
city: [
{ name: "Dhaka" },
{ name: "Narayanganj" }
]
},
{
name: "Sylhet",
city: [
{ name: "Sylhet" }
]
},
{
name: "Chittagong",
city: [
{ name: "Chittagong" },
{ name: "Comilla" }
]
},
{
name: "Khulna",
city: [
{ name: "Khulna" },
{ name: "Jessore" }
]
}
]
}
}
]
答案 0 :(得分:1)
我在这里模拟你的场景。
加载初始数据集(类似于问题中描述的数据集):
CREATE (c:Country {name:"Country A"})
CREATE (p1:Province {name:"Province A"})
CREATE (p2:Province {name:"Province B"})
CREATE (c1:City {name:"City A"})
CREATE (c2:City {name:"City B"})
CREATE (c3:City {name:"City C"})
CREATE (c4:City {name:"City D"})
CREATE (c)-[:COUNTRY_PROVINCE]->(p1)
CREATE (p1)-[:PROVINCE_CITY]->(c1)
CREATE (p1)-[:PROVINCE_CITY]->(c2)
CREATE (c)-[:COUNTRY_PROVINCE]->(p2)
CREATE (p2)-[:PROVINCE_CITY]->(c3)
CREATE (p2)-[:PROVINCE_CITY]->(c4)
查询:
MATCH (cn:Country { name: "Country A" })-[:COUNTRY_PROVINCE]->(pv:Province)-[:PROVINCE_CITY]->(ct:City)
WITH cn, pv, collect({name : ct.name}) as cities
RETURN {coutry : {name : cn.name, province : collect( distinct { name:pv.name, city :cities }) } }
结果:
{
"coutry":{
"name":"Country A",
"province":[
{
"name":"Province A",
"city":[
{
"name":"City B"
},
{
"name":"City A"
}
]
},
{
"name":"Province B",
"city":[
{
"name":"City D"
},
{
"name":"City C"
}
]
}
]
}
}
答案 1 :(得分:0)
好吧,如果你要返回一条路径的节点,这显然就是你要获得的。你有几种不同的选择:
希望这有帮助。
此致 汤姆