-
Notifications
You must be signed in to change notification settings - Fork 137
Nodes and Relationships
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 some 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')
->setProperty('home', 'small cottage')
->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
// home: small cottage
$character->removeProperty('mood')
->setProperty('home', 'demolished')
->save();
foreach ($character->getProperties() as $key => $value) {
echo "$key: $value\n";
}
// prints:
// name: Arthur Dent
// home: demolished
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 the node will not be persisted to the server until Node::save()
is called again.
A node can be deleted as long as its ID has been set.
$earth = new Everyman\Neo4j\Node($client);
$earth->setId(123)
->delete();
Node::delete()
will return true
if the Node
was deleted successfully from the server, or false
otherwise. Note that it is unnecessary to call Node::load()
before deleting. Supplying a valid ID is good enough.