1
votes

Till now I was using PHP Rest Api in order to send requests with cypher queries and get a response back. The response is a huge string which makes it difficult to parse and can not be transformed to JSON. I now installed Neo4jPHP and I am trying to figure out how to write the same query I had in cypher. This is my query:

            MATCH (n:RealNode)-[r:contains*]-(z)  WHERE n.gid='123' RETURN n,z;")

What I actually want is to get a list of all the names of the nodes (name is a property inside each node) which is related to my n node. How do I do this?

I can not find many examples for Neo4jPHP onnline and the ones I found seem not to work. I downloaded the latest version from here (https://github.com/jadell/neo4jphp).

Thanks D.

RE-EDITED

I try this query in neo4j Server:

     MATCH (n)-[r:KNOWS*]-(z)  WHERE n.name='Arthur Dent' AND z.name='Ford Prefect'  RETURN n,z,r;

and I get all the 3 nodes which are connected to each other. The same query through neo4jPHP will return only the name of one node. Why is this happening?

        $querystring="MATCH path=(n:RealNode {gid:'58731'})-[:contains*]-(z) RETURN [x in nodes(path) | x.id] as names";
        $query=new Everyman\Neo4j\Cypher\Query($client,$querystring); 
        $result=$query->getResultSet();
        print_r($result);
        foreach($result as $row){
          echo $row['x']->getProperty('name') . "\n";
        }
2

2 Answers

2
votes

On Cypher level you might use a query like:

MATCH path=(n {name:'Arthur Dent'])-[:KNOWS*]-(z {name:'Ford Perfect'})
RETURN [x in nodes(path) | x.name] as names

You assign a variable to a pattern, here path. In the RETURN you iterate over all nodes along that path and extract its name property.

2 additional hints:

  1. consider assigning labels e.g. Person to your nodes and use a declarative index ( CREATE INDEX ON :Person(name) ) to speed up the look up for start/end node of your query
  2. for variable path length matches [:KNOWS*] consider using an upper limit, depending on the size and structure of your graph this can get rather expensive. [:KNOWS*10] to limit on 10th degree.
1
votes

After lots of trying and some help from Stefan Armbruster I made it work using Neo4jPHP. This is how it looks:

    $client = new Everyman\Neo4j\Client();
    $querystring="MATCH path=(n {gid:'58731'})-[:contains*]-(z) RETURN LAST([x in nodes(path) | x.id]) as names";
    $query=new Everyman\Neo4j\Cypher\Query($client,$querystring); 
    $result=$query->getResultSet();

    foreach($result as $resultItem){
        $resultArray[] = $resultItem['n'];
    }   
    print_r($resultArray); // prints the array

Neo4jPHP is very handy tool but not very popular. Small community and few examples online. Hope this helps someone.