LoginSignup
8
8

More than 5 years have passed since last update.

Gremlinと戯れる

Last updated at Posted at 2018-02-06

GraphDBを操作する為、Graph Traversal LanguageGremlin を使ってみます。

今回は、 Pythonで操作する為、 gremlin-python を導入しました。

  • インストール

pip を使って、gremlin-python をインストールします。

wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py --user
pip install gremlinpython --user

上記ですが、pythonの環境構築が適当です。。
真っ当な環境を作る場合は、python仮想環境等を作って、パッケージ管理を行ってください。

以降、REPLでの処理を想定しています。

  • GraphDBへの接続
from gremlin_python import statics
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection

graph = Graph()

g = graph.traversal().withRemote(DriverRemoteConnection('websocketのURL','g'))

* 頂点(Vertex, ノード)の情報表示

g.V().toList()

全ての頂点を対象として、idが表示される。

g.V().valueMap().toList()

頂点が保持しているpropertyの情報も表示する。

  • 端(Edge, リレーション)の情報表示
g.E().toList()

idが表示される。

g.E().valueMap().toList()

端が保持しているpropertyの情報も表示する。

  • 頂点の追加
g.addV('gremlin1').property('name', 'gremlin1').toSet()
  • 頂点のpropertyを利用した情報の取得
# 頂点のpropertyの値を取得.(propertyのvalueのlistを取得)
g.V().values('name').toList()

# 頂点に対し、該当するpropertyのkey/valueを持つ頂点を絞り込んで取得.(頂点のidを取得)
g.V().has('name','gremlin1').toList()

# propertyを追加して、追加されたことを確認
gremlin1 = g.V().has('name','gremlin1').toList()[0]
g.V(gremlin1).property('country','usa').toSet()
g.V(gremlin1).valueMap().toList()
# 以下のようなデータを取得.
# -> [{u'country': [u'usa'], u'name': [u'gremlin1']}] 
  • 端の追加
# 頂点 gremlin2を追加し、gremlin1からgremlin2へ橋を追加.
g.addV('gremlin2').property('name', 'gremlin2').toSet()
gremlin2 = g.V().has('name','gremlin2').toList()[0]

# fromの後ろに_があることに注意.
g.addE('friend').from_(gremlin1).to(gremlin2).toSet()

# 追加した端から情報が取得できることを確認.
g.V(gremlin1).out('friend').valueMap().toList()
  • 端のproperty操作
# 端にpropertyを追加する.
# labelから取得して追加.
g.E().hasLabel('friend').property('relation', 1.0).toSet()
# 頂点をから端を取得して追加.
# outではなく、outEで.
g.V(gremlin1).outE('friend').property('date', '20180206').toSet()

# 端に追加したpropertyの参照
friend = g.E().hasLabel('friend').next()
g.E(friend).valueMap().toList()
# 以下のようなデータを取得.
# -> [{u'date': u'20180206', u'relation': 1.0}]

一通りの追加と参照を実施してみましたが、
Gremlinには、他にも有用な取得方法が用意されていますので、一読ください。

Gremlin traversal

東京リージョンに Amazon Neptune がきてくれるはず!と期待しています!

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