より詳細な記事については、これらのブログ投稿を参照できます。
または、これらのビデオのいずれかをご覧ください。
composer require laudis/neo4j-php-client詳細はこちらをご覧ください
use Laudis Neo4j Authentication Authenticate ;
use Laudis Neo4j ClientBuilder ;
$ client = ClientBuilder:: create ()
-> withDriver ( ' bolt ' , ' bolt+s://user:password@localhost ' ) // creates a bolt driver
-> withDriver ( ' https ' , ' https://test.com ' , Authenticate:: basic ( ' user ' , ' password ' )) // creates an http 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 ();これで、Bolt、HTTPS、Neo4Jドライバーを備えたクライアントを作成しました。クライアントが使用するデフォルトのドライバーはボルトです。
URLの詳細と、これらを使用してドライバーを構成する方法については、こちらをご覧ください。
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' 3つの異なるアプローチを使用してドライバーを制御できます。
自動コミットされたクエリは、最も簡単で直感的ですが、複雑なビジネスロジックを実行したり、高可用性環境内で多くの欠点があります。
$ 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 ' );runStatementsメソッドは、すべてのステートメントを一度に実行します。この方法は、特にHTTPプロトコルを使用する場合、データベース呼び出しの数を減らすための不可欠なツールです。
use Laudis Neo4j Databags Statement ;
$ results = $ client -> runStatements ([
Statement:: create ( ' MATCH (x) RETURN x LIMIT 100 ' ),
Statement:: create ( ' MERGE (x:Person {email: $email}) ' , [ ' email ' => ' [email protected] ' ])
]);ドライバーを使用する場合、トランザクション関数は事実上の標準です。 Neo4Jオーラやクラスターなどの高可用性ソリューションで最初に開発するとき、多くの落とし穴に耐性があるため、最も携帯可能です。
ドライバーはトランザクション関数を管理します。
注意:自動再試行機能のため、関数は後続のリコールで同じ結果を生成するか、より技術的な用語では次のようになります。関数内で実行ロジックを設計するときは、常にこれを覚えておいてください。
いくつかの例:
use Laudis Neo4j Contracts TransactionInterface ;
// Do a simple merge and return the result
$ result = $ client -> writeTransaction ( static function ( TransactionInterface $ tsx ) {
$ result = $ tsx -> run ( ' MERGE (x {y: "z"}:X) return x ' );
return $ result -> first ()-> get ( ' x ' )[ ' y ' ];
});
// Will result in an error
$ client -> readTransaction ( static function ( TransactionInterface $ tsx ) {
$ tsx -> run ( ' MERGE (x {y: "z"}:X) return x ' );
});
// This is a poorly designed transaction function
$ client -> writeTransaction ( static function ( TransactionInterface $ tsx ) use ( $ externalCounter ) {
$ externalCounter -> incrementNodesCreated ();
$ tsx -> run ( ' MERGE (x {y: $id}:X) return x ' , [ ' id ' => Uuid:: v4 ()]);
});
// This achieves the same effect but is safe in case it should be retried. The function is now idempotent.
$ id = Uuid:: v4 ();
$ client -> writeTransaction ( static function ( TransactionInterface $ tsx ) use ( $ id ) {
$ tsx -> run ( ' MERGE (x {y: $id}:X) return x ' , [ ' id ' => $ id ]);
});
$ externalCounter -> incrementNodesCreated ();ドライバーの機能への低レベルのアクセスが必要な場合は、管理されていないトランザクションが必要です。それらは、完全に制御可能なコミットとロールバックを可能にします。
beginTransactionメソッドは、関連するドライバーとのトランザクションを開始します。
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
);
beginTransaction、提供されたステートメントの結果ではなく、トランザクションオブジェクトのみを返すことに注意してください。
トランザクションは、クライアントオブジェクトがまだ開いている限り、クライアントオブジェクトと同じようにステートメントを実行できます。
$ 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 ' )]);ロールバックトランザクション:
$ tsx -> rollback ();トランザクションをコミットします:
$ tsx -> commit ([Statement:: create ( ' MATCH (x) RETURN x LIMIT 100 ' )]);結果は、行と列の標準形式で返されます。
// 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の値とタイプは、これらのPHPタイプとクラスにマッピングされます。
| cypher | Php |
|---|---|
| ヌル | * null |
| 弦 | * string |
| 整数 | * int |
| フロート | * float |
| ブール | * bool |
| 地図 | * LaudisNeo4jTypesCypherMap |
| リスト | * LaudisNeo4jTypesCypherList |
| ポイント | * LaudisNeo4jContractsPointInterface ** |
| 日付 | * LaudisNeo4jTypesDate |
| 時間 | * LaudisNeo4jTypesTime |
| LocalTime | * LaudisNeo4jTypesLocalTime |
| DateTime | * LaudisNeo4jTypesDateTime |
| Datetimezoneid | * LaudisNeo4jTypesDateTimeZoneId |
| LocalDateTime | * LaudisNeo4jTypesLocalDateTime |
| 間隔 | * LaudisNeo4jTypesDuration |
| ノード | LaudisNeo4jTypesNode |
| 関係 | LaudisNeo4jTypesRelationship |
| パス | LaudisNeo4jTypesPath |
(*)これらのアイテムは、ボルトプロトコルのパラメーターとして使用することもでき、ドライバーによって自動的に変換されるため、Cypherで使用できます。
これらの例に加えて、 DateTimeInterface CypherのDateTimeZoneIdにマッピングされます。空のまたはリストタイプのarray Cypher Listに変換され、 associative array mapに変換されます。
(**)ポイントは、PointInterfaceを実装する4つのタイプのいずれかの1つです: LaudisNeo4jTypesCartesianPoint LaudisNeo4jTypesCartesian3DPoint LaudisNeo4jTypesWGS84Point LaudisNeo4jTypesWGS843DPoint
Cypherにはリストとマップがあります。標準のPHPアレイが両方をカプセル化するため、この概念は問題になる可能性があります。空の配列をパラメーターとして提供する場合、空のリストまたはマップを決定することは不可能です。
ParameterHelperクラスは、これに理想的な仲間です。
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| ドライバーバージョン | PHPバージョン | NEO4Jバージョン |
|---|---|---|
| ^2.8 | 7.4、 ^8.0 | ^3.5、 ^4.0 |
| ^3.0 | ^8.0 | ^4.0、 ^5.0 |
| 特徴 | サポートされていますか? |
|---|---|
| 認証 | はい |
| トランザクション | はい |
| HTTPプロトコル | はい |
| ボルトプロトコル | はい |
| クラスタ | はい |
| オーラ | はい |
| ジョルトプロトコル | はい |
| ブックマーク | はい |
(*)ボルトプロトコルを実装する必要がありました
(**)HTTPプロトコルを実装する必要がありました
(***)は、最適なボルトプロトコルパフォーマンスのためにインストールできます
HTTPドライバーの使用を計画している場合は、PSR-7、PSR-17、およびPSR-18の実装がプロジェクトに含まれていることを確認してください。持っていない場合は、Composerを介してインストールできます。
composer require nyholm/psr7 nyholm/psr7-server kriswallsmith/buzzボルトプロトコルとHTTPユニフォームの結果を作成するために、ドライバーは結果のフォーマッツ(別名ハイドレーター)を提供します。クライアントは、これらのフォーマッタで構成可能です。自分で実装することもできます。
デフォルトのフォーマッタはLaudisNeo4jFormattersOGMFormatterです。これは、結果形式セクションで広く説明されています。
ドライバーはデフォルトで3つのフォーマッタを提供します。これらはすべて、フォーマッタネームスペースにあります。
LaudisNeo4jFormatterBasicFormatterは、すべてのcypherタイプを消去し、結果のマップのすべての値をスカラー、null、または配列値として単純に返すだけです。LaudisNeo4jFormatterOGMFormatterでは、ここで説明するように、cypherタイプをphpタイプにマッピングします。LaudisNeo4jFormatterSummarizedResultFormatterは、フォーマッターを飾り、広範な結果の概要を追加します。クライアントビルダーは、フォーマッタを変更する簡単な方法を提供します。
$ client = Laudis Neo4j ClientBuilder:: create ()
-> withFormatter ( Laudis Neo4j Formatter SummarizedResultFormatter:: create ())
-> build ();
/**
* The client will now return a result, decorated with a summary.
*
* @var LaudisNeo4jDatabagsSummarizedResult $results
*/
$ summarisedResult = $ client -> run ( ' MATCH (x) RETURN x ' );
// The summary contains extensive information such as counters for changed values in the database,
// information on the database, potential notifications, timing, a (profiled) plan, the type of query
// and information on the server itself.
$ summary = $ summarisedResult -> getSummary ();
// The result is exactly the same as the default.
$ result = $ summarisedResult -> getResult ();カスタムフォーマッタを使用するには、 LaudisNeo4jContractsFormatterInterface実装し、クライアントビルダーを使用するときにそれを提供します。
ここで説明するドライバーAPIは、ドライバーの主なターゲットです。このため、クライアントはドライバーマネージャーにすぎません。ドライバーはセッションを作成します。セッションは、トランザクションを通じてクエリを実行します。
この動作により、このようなクライアントから始まる各概念にアクセスできます。
use Laudis Neo4j ClientBuilder ;
// A builder is responsible for configuring the client on a high level.
$ builder = ClientBuilder:: create ();
// A client manages the drivers as configured by the builder.
$ client = $ builder -> build ();
// A driver manages connections and sessions.
$ driver = $ client -> getDriver ( ' default ' );
// A session manages transactions.
$ session = $ driver -> createSession ();
// A transaction is the atomic unit of the driver where are the cypher queries are chained.
$ transaction = $ session -> beginTransaction ();
// A transaction runs the actual queries
$ transaction -> run ( ' MATCH (x) RETURN count(x) ' );完全な制御が必要な場合は、各オブジェクトをカスタム構成オブジェクトで制御できます。
クライアントはドライバーを管理し、事前に設定されたエイリアスに基づいてクエリを正しいドライバーにルーティングします。
ドライバーオブジェクトは、NEO4Jにアクセスできるスレッドセーフバックボーンです。接続プールを所有しており、仕事を実行するためのセッションを生み出すことができます。
use Laudis Neo4j Basic Driver ;
use Laudis Neo4j Databags DriverConfiguration ;
$ driver = Driver:: create (
uri: ' neo4j://user:mypassword@Localhost:7687 ' ,
configuration: DriverConfiguration:: create ()-> withUserAgent ( ' MyApp/1.0.0 ' )
);セッションは、トランザクションの因果的に接続されたシーケンスの軽量コンテナです。必要に応じて接続プールから接続を借り、ブックマークを使用してチェーントランザクションを借ります。
use Laudis Neo4j Databags SessionConfiguration ;
use Laudis Neo4j Enum AccessMode ;
$ session = $ driver -> createSession (SessionConfiguration:: create ()
-> withDatabase ( ' my-database ' )
-> withAccessMode (AccessMode:: READ ())
);トランザクションは、1つ以上のクエリを含む可能性のある原子単位の作業です。各トランザクションは単一の接続にバインドされ、ブックマークによって因果チェーンで表されます。
クエリは、トランザクション内の実行可能ユニットであり、Cypher文字列とキー付きパラメーターセットで構成されています。各クエリは、ゼロ以上のレコードを含む可能性のある結果を出力します。
結果には、ヘッダーメタデータ、コンテンツレコード、サマリーメタデータで構成されるクエリからの出力が含まれています。 NEO4J 4.0以上では、アプリケーションは結果データのフローを制御しています。
URLスキームは、ドライバーを構成する最も簡単な方法です。
構成形式:
'<scheme>://<user>:<password>@<host>:<port>?database=<database>'
デフォルトの構成:
bolt://localhost:7687?database=neo4j
このライブラリは、ボルト、HTTP、NEO4Jの3つのドライバーをサポートしています。 URLのスキーム部分がドライバーを決定します。
| ドライバ | スキーム | 有効な証明書 | 自己署名証明書 | 関数 |
|---|---|---|---|---|
| neo4j | neo4j | neo4j+s | Neo4J+SSC | ボルト上のクライアントサイドルーティング |
| ボルト | ボルト | ボルト+s | ボルト+SSC | ボルト上の単一サーバー |
| http | http | https | PSRクライアントの実装を介して構成されています | HTTPを介した単一サーバー |
ドライバー、セッション、およびトランザクションは、構成オブジェクトを使用して構成できます。構成オプションの概要は、こちらをご覧ください。
| 名前 | コンセプト | 説明 | クラス |
|---|---|---|---|
| ユーザーエージェント | ドライバ | ユーザーエージェントは、クライアントをNEO4Jサーバーに識別するために使用されていました。 | DriverConfiguration |
| HTTP PSRバインディング | ドライバ | HTTPプロトコルを使用するときにドライバーが使用する関連するPSR実装。 | DriverConfiguration |
| データベース | セッション | 接続するデータベース。 | SessionConfiguration |
| フェッチサイズ | セッション | 一度にフェッチするための行の量。 | SessionConfiguration |
| アクセスモード | セッション | サーバーにアクセスするときのデフォルトモード。 | SessionConfiguration |
| ブックマーク | セッション | セッションで使用されているブックマーク。 (実験的) | SessionConfiguration |
| メタデータ | 取引 | トランザクション中に使用されるメタデータ。 (実験的) | TransactionConfiguration |
| タイムアウト | 取引 | タイミングを出す前の最大時間。 | TransactionConfiguration |
コード例:
use Laudis Neo4j Databags DriverConfiguration ;
use Laudis Neo4j Databags SessionConfiguration ;
use Laudis Neo4j Databags TransactionConfiguration ;
$ client = Laudis Neo4j ClientBuilder:: create ()
-> withDefaultDriverConfiguration (DriverConfiguration:: default ()-> withUserAgent ( ' MyApp/1.0.0 ' ))
-> withDefaultSessionConfiguration (SessionConfiguration:: default ()-> withDatabase ( ' app-database ' ))
-> withDefaultTransactionConfiguration (TransactionConfiguration:: default ()-> withTimeout ( 5.0 ))
-> build ();
// The client will run the query on a driver with the provided config,
// which spawns a session with the provided session config
// and runs the query in a transaction with the provided transaction config
$ client -> run ( ' MATCH (x) RETURN count(x) AS count ' );
// More granular control can be achieved by requesting the concepts yourself:
$ tsx = $ client -> getDriver ( ' default ' )
-> createSession (SessionConfiguration:: default ()-> withDatabase ( ' management-database ' ))
-> beginTransaction ( null , TransactionConfiguration:: default ()-> withTimeout ( 200 ));
$ tsx -> run ( ' SOME REALLY LONG MANAGEMENT QUERY ' );
$ tsx -> commit ();