0
1

More than 3 years have passed since last update.

node.jsでneo4jのOGMを使う④データを操作してみる

Last updated at Posted at 2020-11-01

#1)準備:テストデータを入れる

適当にテストデータを作ります。

create (:actor{name:"堺雅人"})-[:ACTS_IN{name:"半沢直樹"}]->(:movie{name:"半沢直樹"})

match (a:actor{name:"堺雅人"}) merge (a)-[:ACTS_IN{name:"小見門健介"}]->(:movie{name:"リーガルハイ"})

match (m:movie{name:"半沢直樹"}) merge (a:actor{name:"香川照之"})-[:ACTS_IN{name:"大和田常務"}]->(m)

match (m:movie{name:"リーガルハイ"}) merge (a:actor{name:"新垣結衣"})-[:ACTS_IN{name:"黛"}]->(m)

image.png

#2)スキーマ定義を行う

スキーマを定義したjsファイルを入れる[model]ディレクトリを作りスキーマ定義を行います。

/model/actor.js
module.exports = {
  id: {
    type: 'uuid',
    primary: true
  },
  name: 'string',
    acts_in: {
        type: "relationships",
        target: "movie",
        relationship: "ACTS_IN",
        direction: "out",
        properties: {
            name: "string"
        },
        eager: true // <-- eager load this relationship
    }
}
/model/movie.js
module.exports = {
  id: {
    type: 'uuid',
    primary: true
  },
  name: 'string'
}

#3)定義したスキーマを利用してデータを読みこむ

テストデータのnodeを読み込んで出力してみます。

index.js
        var neode = require('neode');

        //①.envファイルの設定を元にneo4jサーバーに接続
        const instance = new neode.fromEnv();

        //②modelディレクトリ内のスキーマ定義ファイルを読み込む
        instance.withDirectory(__dirname+'/model');

        //③actorノードをすべて読み込む
        instance.model("actor").all()
        .then(actors => {
            //④すべてのactorの出演movie名を出力
            actors.forEach(actor =>{
                console.log(""+actor.get('name')+"")
                const acts_ins = actor.get('acts_in')
                acts_ins.forEach(acts_in =>{
                    console.log("出演:"+acts_in.endNode().get("name"));
                })
            })
        })

すべてのデータをJsonで出力する場合は下記で取得できます。

index.js
actors.toJson().then(json=>console.log(json))

Collection型で取得したデータに使えるメソッド

  • length()・・・データ件数の取得
  • get(index)・・・指定したnodeの取得
  • first()
  • map(fn)
  • find(fn)
  • forEach(fn)
  • toJson() ・・・すべてのJSONデータの取得(Promise)

##条件を指定してデータを取得する

all(properties, order, limit, skip)

instance.model("actor").all({name:"堺雅人"})

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1