tshell_blog

ソフトウェアと車輪がついた乗り物のはなし

Neo4JをNode.jsから使う

tshell.hatenablog.com

Neo4JをDockerでお手軽に試してみました。
実用的なアプリケーションを作るとなるとPythonやらJavascript(Node.js)などから使えるようにしたいです。
公式ドキュメントのDriver Manualを見ながら,Node.jsでNeo4Jにアクセスしてみます。

環境

以下の環境で試しました。

  • Windows 10 Professional version 1903
  • Node.js 12.10.0

インストール

Driver ManualのGet Started .NETJavaJavascript用ドライバ(Neo4Jアクセス用ライブラリ)のインストール方法が記載されています。
今回はJavascriptを使うので,1.2. Driver versions and installationの中のExample 1.1. Acquire the driverのタブをJavascriptにすると書いてある内容を実行していきます。

以下のコマンドを実行してインストール可能なneo4j-driverの一覧を表示します。

> npm show neo4j-driver@* version

4.0.0をインストールすることにします。

> npm install neo4j-driver@4.0.0

サンプルコードの作成

Get Startedに載っているサンプルは残念ながら動きませんでした。
以下のようなソースをindex.jsとして作成します。

neo4j = require('neo4j-driver');

const uri = 'bolt://localhost';
const user = 'neo4j';
const password = 'neo4j';

const driver = neo4j.driver(uri, neo4j.auth.basic(user, password));
const session = driver.session();

session
.run(
    'CREATE (a:Greeting) SET a.message = $message RETURN a.message + ", from node " + id(a)',
       { message: 'hello, world' }
)
.then(result => {
    session.close();
    const singleRecord = result.records[0];
    const greeting = singleRecord.get(0);

    console.log(greeting);
})
.catch(error =>{
    session.close();
    throw error;
});

以下のコマンドで実行します。

node index.js

Neo4Jへの書き込みに成功すると以下のようなレスポンスが表示されます。

hello, world, from node 343

結果の確認

http://localhost:7474にアクセスして以下コマンドを実行します。 Neo4JのWebインターフェース,コマンド入力部で改行するにはShift + Enterを入力します。

MATCH (a:Greeting)
RETURN a

以下のようにノードが表示されます。ここではindex.jsを2回実行してしまったので2つ表示されています。

f:id:tshell:20200218214559p:plain

WHERE句を使えば指定したidのノードだけ表示させることができます。

MATCH (a:Greeting)
WHERE id(a) = 343
RETURN a

f:id:tshell:20200218214734p:plain