LoginSignup
4
7

More than 5 years have passed since last update.

[Neo4J] ④Cypherでグラフ構造を扱ってみる

Last updated at Posted at 2015-11-14

息長くNeo4Jを試していこう、のコーナー。

最近、オープンになったグラフデータベース向けクエリ言語Cypherをマスターすれば、グラフ構造を作って検索したり、ができるようになる。ということで、Cypherを使いはじめてみよう。

前々回に入れてみた、py2neoをお供に使ってみる。インストールはpip経由で:

sudo pip install py2neo
$ python -V
Python 2.7.10

1) py2neoでバッチ処理

webに転がっていた、DRYでない微妙な例(しかも動かない)をとりあえず写経し修正し、バッチ処理ができるようにした:

test.py
from py2neo import Graph

graph = Graph("http://neo4j:yourpassword@:7474/db/data/")
statement = """
  MERGE (person:Person {name:{person_name}}) ON CREATE SET
    person.age = {person_age},
    person.sex = {person_sex}

  MERGE (pet:Pet {name:{pet_name}}) ON CREATE SET
    pet.type = {pet_type}

  MERGE (person)-[:owns]->(pet)

  RETURN person
  """

tx = graph.cypher.begin()

persons = [
    {'name': 'Homer', 'age': 32, 'sex': 'Male', 'pet_name': 'Buller', 'pet_type': 'Dog'},
    {'name': 'Lucy', 'age': 12, 'sex': 'Male', 'pet_name': 'Buller', 'pet_type': 'Dog'},
    {'name': 'Lucy', 'age': 12, 'sex': 'Male', 'pet_name': 'Betty', 'pet_type': 'Cat'}
]

for person in persons:
    print person
    tx.append(statement, {
      'person_name': person['name'],
      'person_age': person['age'],
      'person_sex': person['sex'],

      'pet_name': person['pet_name'],
      'pet_type': person['pet_type']
    })

tx.process()

tx.commit()

トランザクションの部分だけ取り出すと流れが分かる:

tx = graph.cypher.begin()
tx.append(statement, { ... })
tx.process()
tx.commit()

また、statement中のMERGE 〜 ON CREATEというcypher構文、マスターすれば、なかなかよさそうだ。

以下にあるJSONをコミットするpy2neoの例を見るに別の書き方もできそうだ。
http://jexp.github.io/blog/html/load_json.html

2) コマンドラインでクエリを書く。

お次は、コマンドラインからcypherをいじってみる(環境はMac)。

$ neo4j-shell
Unable to find any JVMs matching version "1.7".
Welcome to the Neo4j Shell! Enter 'help' for a list of commands
NOTE: Remote Neo4j graph database service 'shell' at port 1337

neo4j-sh (?)$ MATCH (p)-[:owns]-(pet) WHERE p.name = "Lucy" RETURN p, pet;
+------------------------------------------------------------------------------+
| p                                       | pet                                |
+------------------------------------------------------------------------------+
| Node[11]{name:"Lucy",age:12,sex:"Male"} | Node[12]{name:"Betty",type:"Cat"}  |
| Node[11]{name:"Lucy",age:12,sex:"Male"} | Node[10]{name:"Buller",type:"Dog"} |
+------------------------------------------------------------------------------+
2 rows
46 ms

neo4j-shell立ち上げ時に何か文句を言われるが無事、クエリをかけられた。

3) ブラウザ上でクエリ実行しグラフ化

同じクエリを、ブラウザ上で実行:

MATCH (p)-[:owns]-(pet) WHERE p.name = "Lucy" RETURN p, pet;

右のGraphボタンを押すと期待通りのグラフ画面が登場する:
http://localhost:7474/browser/
スクリーンショット 2015-11-14 19.52.40.png

4) cypherクエリ チートシート など

本家サイトにある以下:
http://neo4j.com/docs/stable/cypher-refcard/

日本語の入門はなかなか良い物がweb上では見つからないなぁ。

取り急ぎ、随時更新との"勉強メモ"に期待!
http://qiita.com/Keech/items/6bd5b667e935a20be018

こちらもマイペースでやっていこう^^;

4
7
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
4
7