Cypher and gremlin queries

Josh Adell edited this page Apr 10, 2014 · 8 revisions

neo4jphp supports executing both Cypher and Gremlin queries via REST. The following links can provide more information about these two query languages and how to use them:

Executing a Cypher Query

The following snippet finds all nodes connected to node 1 through an incoming "KNOWS" relationship at the end of an outgoing "HAS" relationship via a Cypher query:

$queryString = "START n=node(1) ".
    "MATCH (n)<-[:KNOWS]-(x)-[:HAS]->()".
    "RETURN x";
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString);
$result = $query->getResultSet();

Query::getResultSet() returns a Query\ResultSet object (discussed below.)

It is also possible to supply named parameters to a Cypher query:

$queryString = "START n=node({nodeId}) ".
    "MATCH (n)<-[:KNOWS]-(x)".
    "WHERE = {name}".
    "RETURN x";
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString, array('nodeId' => 1, 'name' => 'Bob'));
$result = $query->getResultSet();

Executing a Gremlin Query

neo4jphp also supports Gremlin queries. The following code performs the same query as above, using Gremlin:

$queryString = "g.v(1).in('KNOWS').out('HAS').uniqueObject.toList()";
$query = new Everyman\Neo4j\Gremlin\Query($client, $queryString);
$result = $query->getResultSet();

Gremlin queries also return a Query\ResultSet object. Like with Cypher queries, named parameters can be passed when instantiating a Gremlin query:

$queryString = "g.v(nodeId).in(inType).out(outType).uniqueObject.toList()";
$query = new Everyman\Neo4j\Gremlin\Query($client, $queryString, array(
    'nodeId' => 1,
    'inType' => 'KNOWS',
    'outType' => 'HAS',
$result = $query->getResultSet();

Working with Result Sets

Each of the above queries returns a result set, that can be iterated over to get values returned by the query. Each element of the result set is a Query\Row object that can be accessed like an array. The names of the elements in the row are the names specified in the RETURN clause of the query

Here is an example of iterating over the result set from the above Cypher query:

foreach ($result as $row) {
    echo $row['x']->getProperty('name') . "\n";

Since the results of the query are nodes, the element in each row is a Node object. If multiple columns of data are returned, each one can be accessed in the row by name (the names specified in the RETURN caluse of the query):

// Example query: "START n=node(1) MATCH (x)-[:KNOWS]->(n) RETURN x, COUNT(n) AS y
// column 'x' is a node object, column 'y' is a scalar value
foreach ($result as $row) {
    echo $row['x']->getProperty('name') . ": " . $row['y'] ."\n";

Note that for Gremlin queries, if the data columns are not explicitly named, they will be numerically indexed, starting at 0.

Entities in result sets are lazily loaded. This means that the node objects in the above example are not retrieved from the server until they are actually accessed in the row.