Neo4j - 查找附近的节点集

时间:2017-12-19 11:11:03

标签: graph neo4j cypher graph-databases shortest-path

我想使用Neo4j获取靠近某个节点的节点。

Techniques that take edge costs是受欢迎的,但使用节点成本的方法不是。

例如,在this sample Graph中,节点A附近的节点是B,C,E,G,H,I。

  • 总费用在15以内。
  • 不包括A的费用。
  • 可以忽略边缘方向。

样本图的节点之间的最低成本预计如下。

A<->B : 3
A<->C : 8
A<->D : 50
A<->E : 10
A<->F : 16
A<->G : 11
A<->H : 13
A<->I : 14

可以使用以下查询创建示例图表。

CREATE
(a:Node{name:"A",cost:10}),
(b:Node{name:"B",cost:3}),
(c:Node{name:"C",cost:5}),
(d:Node{name:"D",cost:50}),
(e:Node{name:"E",cost:10}),
(f:Node{name:"F",cost:8}),
(g:Node{name:"G",cost:1}),
(h:Node{name:"H",cost:2}),
(i:Node{name:"I",cost:1}),
(a)-[:Edge]->(b),
(b)-[:Edge]->(c),
(a)-[:Edge]->(d),
(a)-[:Edge]->(e),
(c)-[:Edge]->(f),
(d)-[:Edge]->(f),
(e)-[:Edge]->(g),
(g)-[:Edge]->(h),
(h)-[:Edge]->(i),
(f)-[:Edge]->(i);

回应评论I rebuilt the graph。添加边缘来计算成本。

MATCH (n)-[]-(m)
MERGE (n)-[r:COST{cost:m.cost}]->(m)

我执行了以下查询。

MATCH(startNode:Node{name:"A"}),(endNode:Node)
CALL algo.shortestPath(startNode, endNode, "cost",{relationshipQuery:'COST', defaultValue:1.0,write:false,direction:'OUTGOING'})
YIELD nodeCount, totalCost
WITH nodeCount, totalCost, endNode
WHERE totalCost <= 15
RETURN nodeCount, totalCost, endNode
ORDER BY totalCost ASC;

然后我得到了我期望的结果。

╒═══════════╤═══════════╤══════════════════════╕
│"nodeCount"│"totalCost"│"endNode"             │
╞═══════════╪═══════════╪══════════════════════╡
│0          │-1         │{"name":"A","cost":10}│
├───────────┼───────────┼──────────────────────┤
│2          │3          │{"name":"B","cost":3} │
├───────────┼───────────┼──────────────────────┤
│3          │8          │{"name":"C","cost":5} │
├───────────┼───────────┼──────────────────────┤
│2          │10         │{"name":"E","cost":10}│
├───────────┼───────────┼──────────────────────┤
│3          │11         │{"name":"G","cost":1} │
├───────────┼───────────┼──────────────────────┤
│4          │13         │{"name":"H","cost":2} │
├───────────┼───────────┼──────────────────────┤
│5          │14         │{"name":"I","cost":1} │
└───────────┴───────────┴──────────────────────┘

但是,当我在我实际使用的数据库中执行类似的查询时,由于计算量很大,我无法做到这一点......

Failed to invoke procedure `algo.shortestPath`: Caused by: java.lang.ArrayIndexOutOfBoundsException: -1340037571

有没有人有想法有效搜索附近的节点集?

1 个答案:

答案 0 :(得分:1)

您可以使用此密码查询执行此操作:

MATCH p=(start {name:"A"})-[r*..10]-(end {name:"I"})
RETURN reduce(x=0, n IN tail(nodes(p)) | x + n.cost) AS cost
ORDER BY cost ASC
LIMIT 1

但在这种情况下,Neo4j将搜索startend之间的所有现有路径,然后它将计算全局费用。所以这是一个昂贵的查询...

如果你想要表演,你应该看一下图表算法中algo.shortestPath函数的实现来创建你自己的程序/算法。