I am new to neo4j and currently using Neo4jphp library with cypher to store and retrieve nodes. My logic is fairly simple. I want to get a node (post) and get all its likes (count of likes) and all comments (nodes) with their commenters (nodes of label user) and be able to parse the ResultSet in a php array to later encode it to Json.
The cypher statement I'm using is:
MATCH (user:User)-[:POSTED]->(post)
WHERE post.UserID = '13'
AND id(post) = 106
OPTIONAL MATCH ()-[rel:LIKES]-(post)
OPTIONAL MATCH (post)-[:HAS]-(comment:Comment)<-[:COMMENTED]-(commenter:User)
RETURN user, post, count(rel) AS Likes, rel, comment, commenter
The match retrieves all nodes correctly (this post has no likes though):
(source: bookintransit.com )
How do I get the correct representation of this graph using the library? Also note that for simplicity I retrieved one post node (id:106) in this example. But I'd like to retrieve a list of posts when I use the code in my application.
This is the php code I'm using:
$queryString = "MATCH (user:User)-[:POSTED]->(post) WHERE post.UserID = {qUser} OPTIONAL MATCH ()-[rel:LIKES]-(post) OPTIONAL MATCH (post)-[:HAS]-(comment:Comment)<-[:COMMENTED]-(commenter:User) RETURN user, post,count(rel) AS Likes, rel, comment, commenter ORDER BY post.TS DESC LIMIT ".$NumberOfPosts;
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString, array('qUser' => $UserID));
$result = $query->getResultSet();
if(count($result)>0){
foreach($result AS $row){
// How do I get the correct graph in a php array to parse to json
}
With neo4jphp I have no idea if it is feasible. BTW it is possible with neoclient :
NeoClient use a response formatter handling the graph result data content, so you get in result object what your graph looks like in the image you posted :
$result = $client->sendCypherQuery($yourQuery, $parameters);
$posts = $result->getNodes('Post');
$post = $result->getSingleNode('Post');
$comments = $post->getInboundRelationships('HAS');
foreach ($comments->getEndNode() as $comment) {
echo $comment->getProperty('text');
$user = $comment->getSingleRelationship('COMMENTED')->getEndNode();
echo $user->getProperty('username');
}
As you can see, the result set is just a graph representation of your response, you just need to navigate through it.
I think you are looking for something like this. Find all the posts of a user. With each post optionally find all of the comments and like for each; put the comments and related users into a collection; count the number of likes; and return it all per post.
MATCH (u:User {name: "13})-[:POSTED]-(p:Post)
WITH p
OPTIONAL MATCH (p)-[:HAS]-(c:Comment)-(u:User)
OPTIONAL MATCH (p)-[:HAS]-(l:Like)
WITH p
, [c, u] AS comment
, count(l) AS likes
RETURN p, collect(comment), likes
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.