php客户端neoclient遍历neo4j中的节点和关系及其属性等

时间:2021-03-15 18:04:20

php客户端neoclient遍历neo4j中的节点和关系及其属性等:

环境:
ubuntu 14.04
neo4j 2.3.0M02 企业版
neoclient
php5.5.9
环境配置请见前一篇博文

操作:
网络结构图:

create 
(n0:Person { name: 'S' }),
(n1:Person { name: 'A1' }),
(n2:Person { name: 'A2' }),
(n3:Person { name: 'A3' }),
(n4:Person { name: 'A4' }),
(n5:Person { name: 'A5' }),
(m1:Person { name: 'B1' }),
(m2:Person { name: 'B2' }),
(m3:Person { name: 'B3' }),
(m0:Person { name: 'D' }),
(n0)-[:KNOWS]->(n1),
(n1)-[:KNOWS]->(n2),
(n2)-[:KNOWS]->(n3),
(n3)-[:KNOWS]->(n4),
(n4)-[:KNOWS]->(n5),
(n5)-[:KNOWS]->(m0),
(n0)-[:KNOWS]->(m1),
(m1)-[:KNOWS]->(m2),
(m2)-[:KNOWS]->(m3),
(m3)-[:KNOWS]->(m0)

图:
php客户端neoclient遍历neo4j中的节点和关系及其属性等
获取节点信息:

$query = 'match n return n';
$result = $client->sendCypherQuery($query)->getResult();
$i=1;
foreach ($result->getNodes() as $node){
echo "</br>num $i :";
$i=$i+1;
echo $node->getLabel();
$prop = ($node->getLabel() === 'Person') ? 'name' : 'name';
$nodes[] = ['title' => $node->getProperty($prop),'label' => $node->getLabel()];
echo " -> $prop";
$p1=$node->getId();
echo " =>Id: $p1";
$p2=$node->getProperty('name');
echo " =>name: $p2";
}

输出结果:

num 1 :Person -> name =>Id: 129 =>name: S
num 2 :Person -> name =>Id: 130 =>name: A1
num 3 :Person -> name =>Id: 131 =>name: A2
num 4 :Person -> name =>Id: 132 =>name: A3
num 5 :Person -> name =>Id: 133 =>name: A4
num 6 :Person -> name =>Id: 134 =>name: A5
num 7 :Person -> name =>Id: 135 =>name: B1
num 8 :Person -> name =>Id: 136 =>name: B2
num 9 :Person -> name =>Id: 137 =>name: B3
num 10 :Person -> name =>Id: 138 =>name: D
node end

获取relationship信息:

 $query = 'match n optional match (n)-[r]->() return r';
$result = $client->sendCypherQuery($query)->getResult();
$j=1;
foreach ($result->getRelationships() as $rel){
$edges[] = [
'source' => $nodesPositions[$rel->getStartNode()->getId()],
'target' => $nodesPositions[$rel->getEndNode()->getId()]
];
echo "</br>num $j :";
$r0=$rel->getId();
echo " =>Id: $r0";
$r0=$rel->getType();
echo " =>Type: $r0";
$r1=$rel->getStartNode()->getId();
echo " =>startId: $r1";
$r2=$rel->getEndNode()->getId();
echo " =>endId: $r2";

}
echo "</br>relationship end</br>";

运行结果:

num 1 : =>Id: 147 =>Type: KNOWS =>startId: 129 =>endId: 130
num 1 : =>Id: 153 =>Type: KNOWS =>startId: 129 =>endId: 135
num 1 : =>Id: 148 =>Type: KNOWS =>startId: 130 =>endId: 131
num 1 : =>Id: 149 =>Type: KNOWS =>startId: 131 =>endId: 132
num 1 : =>Id: 150 =>Type: KNOWS =>startId: 132 =>endId: 133
num 1 : =>Id: 151 =>Type: KNOWS =>startId: 133 =>endId: 134
num 1 : =>Id: 152 =>Type: KNOWS =>startId: 134 =>endId: 138
num 1 : =>Id: 154 =>Type: KNOWS =>startId: 135 =>endId: 136
num 1 : =>Id: 155 =>Type: KNOWS =>startId: 136 =>endId: 137
num 1 : =>Id: 156 =>Type: KNOWS =>startId: 137 =>endId: 138
relationship end

参考:
【1】http://neo4j.com/docs/stable/javadocs/
【2】https://github.com/ikwattro/neo4j-neoclient-example/blob/master/index.php