Neo4jPHPはNeo4jのREST APIにアクセスすることができるライブラリーで、パッケージ管理ツールであるComposerを利用してインストールすることができる。
開発環境
Mac 10.10.3 PHP 5.5.20(デフォルト)
Neo4j v2.2.2 ※Composerは設定済み
前提となる手順
Neo4jのインストール場所は適当なディレクトリでよい。localhost:7474でウェブインターフェイスが利用できる状態にしておく。
私のMacでの開発環境はドキュメントルートをユーザー別に設定してあるので(localhost/~user_name/)、/Users/user_name/Sitesディレクトリ以下に適当なディレクトリ(今回はneo4j_testとした)を作成し、その中にPHPファイルを作成した。
ターミナル
1 2 |
$cd /Users/user_name※/Sites/ $mkdir neo4j_test |
※部分は適宜変更すること
まずはComposerから準備する。neo4j_testディレクトリ内にcomposer.jsonを作成し、composer install(composer update)を実行する。
composer.json
1 2 3 4 5 |
{ "require": { "neoxygen/neoclient": "~2.0" } } |
次にNeo4jとの接続テスト用のPHPファイルを作成する。neo4j_testディレクトリ内にtest.phpを作成し、以下のコードを記述する。
test.php
1 2 3 4 5 6 7 8 9 10 11 |
<?php require('vendor/autoload.php'); use everyman\Neo4j\Client; $client = new Everyman\Neo4j\Client('localhost', 7474); $client->getTransport()->setAuth('Username', 'Password'); print_r($client->getServerInfo()); |
9行目でUsernameとPasswordを設定しているが、ここにはNeo4jをウェブインターフェイスではじめに表示させた時に登録した名前とパスワードを設定する。
もし忘れた場合は、「認証ファイルを削除しパスワードをリセットする」などを参照にしてパスワードを新たに設定すること。
実行結果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Array ( [extensions] => Array ( ) [node] => http://localhost:7474/db/data/node [node_index] => http://localhost:7474/db/data/index/node [relationship_index] => http://localhost:7474/db/data/index/relationship [extensions_info] => http://localhost:7474/db/data/ext [relationship_types] => http://localhost:7474/db/data/relationship/types [batch] => http://localhost:7474/db/data/batch [cypher] => http://localhost:7474/db/data/cypher [indexes] => http://localhost:7474/db/data/schema/index [constraints] => http://localhost:7474/db/data/schema/constraint [transaction] => http://localhost:7474/db/data/transaction [node_labels] => http://localhost:7474/db/data/labels [neo4j_version] => 2.2.2 [version] => Array ( [full] => 2.2.2 [major] => 2 [minor] => 2 [release] => 2 ) ) |
ノードとリレーションの生成
次にノードとリレーショナルを生成する。
以下のCypherと同じノードとリレーショナルを作成する。
内容は「Neo4j入門[NoSQL][グラフデータベース]」を参照。
1 2 3 4 |
CREATE (movie:Movie {title:"マトリックス"}), (person:Person {name:"キアヌ・リーブス"}) MERGE (person)-[:俳優 {name:"ネオ"}]->(movie) RETURN person,movie |
create.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php require('vendor/autoload.php'); use everyman\Neo4j\Client; $client = new Everyman\Neo4j\Client('localhost', 7474); $client->getTransport()->setAuth('Username', 'Password'); $movie = $client->makeNode(); $person = $client->makeNode(); $movieLabel = $client->makeLabel('Movie'); $personLabel = $client->makeLabel('Person'); $movie->setProperty('title', 'マトリックス')->save()->addLabels(array($movieLabel)); $person->setProperty('name', 'キアヌ・リーブス')->save()->addLabels(array($personLabel)); $relation = $client->makeRelationship(); $relation->setStartNode($person) ->setEndNode($movie) ->setType('俳優') ->setProperty('name', 'ネオ') ->save(); |
create.phpを実行したら、ウェブインターフェイスで確認。
$ MATCH n RETURN n
以上
参照サイト