用于 neo4j 数据库的 PHP 客户端和驱动
For some more detailed write-ups you can refer to these blogposts:
Or watch any of these videos.
composer require laudis/neo4j-php-clientFind more details here
use Laudis\Neo4j\Authentication\Authenticate;
use Laudis\Neo4j\ClientBuilder;
$client = ClientBuilder::create()
->withDriver('bolt', 'bolt+s://user:password@localhost') // creates a bolt driver
->withDriver('neo4j', 'neo4j://neo4j.test.com?database=my-database', Authenticate::oidc('token')) // creates an auto routed driver with an OpenID Connect token
->withDefaultDriver('bolt')
->build();You have now created a client with bolt and neo4j drivers. The default driver that the client will use is bolt.
Note: The HTTP/HTTPS drivers were removed in version 3.3.0. Use Bolt (
bolt://,bolt+s://, …) or Neo4j (neo4j://, …) URIs only.
Read more about the URLs and how to use them to configure drivers here.
use Laudis\Neo4j\Contracts\TransactionInterface;
$result = $client->writeTransaction(static function (TransactionInterface $tsx) {
$result = $tsx->run('MERGE (x {y: "z"}:X) return x');
return $result->first()->get('x')['y'];
});
echo $result; // echos 'z'You can control the driver using three different approaches:
Auto committed queries are the most straightforward and most intuitive but have many drawbacks when running complex business logic or within a high availability environment.
$client->run(
'MERGE (user {email: $email})', //The query is a required parameter
['email' => '[email protected]'], //Requests can be optionally added
'backup' //The default connection can be overridden
);use Laudis\Neo4j\Databags\Statement;
$statement = new Statement('MERGE (user {email: $email})', ['email' => '[email protected]']);
$client->runStatement($statement, 'default');Transaction functions are the de facto standard when using the driver. It is the most portable as it is resistant to a lot of the pitfalls when first developing with high availability solutions such as Neo4j aura or a cluster.
The driver manages transaction functions:
ATTENTION: Because of the automatic retry functionality, the function should produce the same result on subsequent recalls, or in more technical terms: should be idempotent. Always remember this when designing the execution logic within the function.
Some examples:
…If you need lower-level access to the drivers' capabilities, then you want unmanaged transactions. They allow for completely controllable commits and rollbacks.
The beginTransaction method will start a transaction with the relevant driver.
use Laudis\Neo4j\Databags\Statement;
$tsx = $client->beginTransaction(
// This is an optional set of statements to execute while opening the transaction
[Statement::create('MERGE (x:Person({email: $email})', ['email' => '[email protected]'])],
'backup' // This is the optional connection alias
);Note that
beginTransactiononly returns the transaction object, not the results of the provided statements.
The transaction can run statements just like the client object as long as it is still open.
$result = $tsx->run('MATCH (x) RETURN x LIMIT 100');
$result = $tsx->runStatement(Statement::create('MATCH (x) RETURN x LIMIT 100'));
$results = $tsx->runStatements([Statement::create('MATCH (x) RETURN x LIMIT 100')]);Rollback a transaction:
$tsx->rollback();Commit a transaction:
$tsx->commit([Statement::create('MATCH (x) RETURN x LIMIT 100')]);Results are returned in a standard format of rows and columns:
// Results are a CypherList
$results = $client->run('MATCH (node:Node) RETURN node, node.id AS id');
// A row is a CypherMap
foreach ($results as $result) {
// Returns a Node
$node = $result->get('node');
echo $node->getProperty('id');
echo $result->get('id');
}Cypher values and types map to these php types and classes:
| Cypher | Php |
|---|---|
| null | * null |
| string | * string |
| integer | * int |
| float | * float |
| boolean | * bool |
| Map | * \Laudis\Neo4j\Types\CypherMap |
| List | * \Laudis\Neo4j\Types\CypherList |
| Point | * \Laudis\Neo4j\Contracts\PointInterface ** |
| Date | * \Laudis\Neo4j\Types\Date |
| Time | * \Laudis\Neo4j\Types\Time |
| LocalTime | * \Laudis\Neo4j\Types\LocalTime |
| DateTime | * \Laudis\Neo4j\Types\DateTime |
| DateTimeZoneId | * \Laudis\Neo4j\Types\DateTimeZoneId |
| LocalDateTime | * \Laudis\Neo4j\Types\LocalDateTime |
| Duration | * \Laudis\Neo4j\Types\Duration |
| Node | \Laudis\Neo4j\Types\Node |
| Relationship | \Laudis\Neo4j\Types\Relationship |
| Path | \Laudis\Neo4j\Types\Path |
| Vector | \Laudis\Neo4j\Types\Vector *** |
(*) These items can also be used as parameters in the bolt protocol and will automatically be converted by the driver, so they can be used in Cypher.
(***) Vector (e.g. embedding) is only produced when decoding results from the server; it is not supported as a query parameter.
Besides these examples, \DateTimeInterface will map to DateTimeZoneId in Cypher. An empty or list-type array will be converted to a cypher List, and an associative array will be converted to a map.
(**) A point can be one of four types implementing PointInterface: \Laudis\Neo4j\Types\CartesianPoint \Laudis\Neo4j\Types\Cartesian3DPoint \Laudis\Neo4j\Types\WGS84Point \Laudis\Neo4j\Types\WGS843DPoint
Cypher has lists and maps. This notion can be problematic as the standard php arrays encapsulate both. When you provide an empty array as a parameter, it will be impossible to determine an empty list or map.
The ParameterHelper class is the ideal companion for this:
use Laudis\Neo4j\ParameterHelper;
$client->run('MATCH (x) WHERE x.slug in $listOrMap RETURN x', ['listOrMap' => ParameterHelper::asList([])]); // will return an empty CypherList
$client->run('MATCH (x) WHERE x.slug in $listOrMap RETURN x', ['listOrMap' => ParameterHelper::asMap([])]); // will error
$client->run('MATCH (x) WHERE x.slug in $listOrMap RETURN x', ['listOrMap' => []]); // will return an empty CypherList| Driver Version | PHP Version | Neo4j Version |
|---|---|---|
| ^2.8 | 7.4, ^8.0 | ^3.5, ^4.0 |
| ^3.0 | ^8.0 | ^4.0, ^5.0 |
| Feature | Supported? |
|---|---|
| Authentication | Yes |
| Transactions | Yes |
| Bolt Protocol | Yes |
| Cluster | Yes |
| Aura | Yes |
| Jolt Protocol | Yes |
| Bookmarks | Yes |
In order to make the results of the Bolt protocol uniform, the driver provides and summarizes the results.
The default formatter is the \Laudis\Neo4j\Formatters\SummarizedResultFormatter, which is explained extensively in the result format section.
\Laudis\Neo4j\Formatter\SummarizedResultFormatter adds an extensive result summary.
The client builder provides an easy way to change the formatter:
…The driver API described here is the main target of the driver. Because of this, the client is nothing more than a driver manager. The driver creates sessions. A session runs queries through a transaction.
Because of this behaviour, you can access each concept starting from the client like this:
…If you need complete control, you can control each object with custom configuration objects.
A client manages drivers and routes the queries to the correct drivers based on preconfigured aliases.
The driver object is the thread-safe backbone that gives access to Neo4j. It owns a connection pool and can spawn sessions for carrying out work.
use Laudis\Neo4j\Basic\Driver;
use Laudis\Neo4j\Databags\DriverConfiguration;
$driver = Driver::create(
uri: 'neo4j://user:mypassword@Localhost:7687',
configuration: DriverConfiguration::create()->wi暂无开放 Issues,或尚未同步最近议题。