Skip to content

Nodes and Relationships

jadell edited this page Sep 15, 2011 · 13 revisions

Working with Nodes

Nodes are the first of the two major entity types in a graph database. A node is a collection of zero or more key-value pairs.

Neo4jPHP makes it very easy to create and work with nodes. The following code snippet creates two new nodes, sets some properties on each, and saves the nodes to the server. The $client variable was created according to Introduction - Creating a Connection to Neo4j.

$arthur = new Everyman\Neo4j\Node($client);
$arthur->setProperty('name', 'Arthur Dent')
    ->setProperty('mood', 'nervous')
    ->save();

$ford = new Everyman\Neo4j\Node($client);
$ford->setProperty('name', 'Ford Prefect')
    ->setProperty('occupation', 'travel writer')
    ->save();

$arthurId = $arthur->getId();

Each Node::setProperty() call returns the Node object, allowing the calls to be chained together fluently.

Node::save() will return true if the Node was saved successfully to the server, or false otherwise. If the save was unsuccessful, Client::getLastError() will return a diagnostic error code to aid debugging.

Now that the node has been created, the node's id can be used to retrieve the node from the server later. The following code retrieves the node and prints its properties:

$character = new Everyman\Neo4j\Node($client);
$character->setId($arthurId)
    ->load();

foreach ($character->getProperties() as $key => $value) {
    echo "$key: $value\n";
}
// prints:
//   name: Arthur Dent
//   mood: nervous

The call to Node::load() will return true or false depending on if the node was loaded successfully or not.

Node::getProperties() returns an array of all properties on a node, keyed by the property name. Individual properties can be retrieved with Node::getProperty and removed completely with Node::removeProperty(). Any changes to properties will not be persisted to the server until Node::save() is called again.

Clone this wiki locally