こんにちは。Kaneyasuです。
今回からしばらくAmazon NeptuneでグラフDBを体験してみるというシリーズ記事を書いていきます。
本記事はシリーズの1回目です。
- Amazon NeptuneでグラフDBを体験してみる① Neptuneとクエリ実行環境を用意する
- Amazon NeptuneでグラフDBを体験してみる② Gremlinを用いた超単純なデータの操作
- Amazon NeptuneでグラフDBを体験してみる③ Amazon NeptuneとTom Sawyer Graph Database Browserと接続
本シリーズ記事の目標
- グラフDBの意味と用途を理解する
- プログラムからAmazon Neptuneにアクセスする方法を習得する
- Amazon Neptuneのセキュリティの確保方法を習得する
- Amazon Neptuneのスケーリングを習得する
- Amazon Neptuneのバックアップ、リカバリ方法を習得する
第1回目の目標
- Amazon Neptuneクラスターを起動する
- プログラムからAmazon Neptuneクラスターにアクセスし、クエリ実行可能な環境を用意する
- 上記をできる限りIaCで構築する
グラフのモデルとクエリ言語
グラフDBはモデルと呼ばれる種類と、アクセスするためのクエリ言語が複数あります。
ざっと調べた内容を表にまとめました。
モデルはプロパティグラフ、クエリ言語はGremlinが最もメジャーのようです。
なので、本シリーズで扱うのはプロパティグラフとGremlinとします。
モデル | 構造 | クエリ言語 |
---|---|---|
プロパティグラフ | - ノード(頂点)とエッジ(辺)で構成 - ノードとエッジに任意のプロパティを持つ - ノード: エンティティやオブジェクト - エッジ: ノード間の関係 |
- Gremlin (Apache TinkerPop) - Cypher (Neo4j) |
RDF | - トリプル形式(主語、述語、目的語) - 主語: リソースやエンティティ - 述語: 関係やプロパティ - 目的語: 関係の相手やプロパティの値 |
- SPARQL |
今回作成する環境
今回は便利なテンプレートを使用しない
AWS公式にAmazon Neptuneを一気に起動するテンプレートが存在します。
こちらなら、Amazon Neptuneだけでなく、Amazon Neptuneに接続するプログラムを実行する環境であるJupyter Notebook まで用意してくれます。
しかし、個人的にこちらは便利すぎて、これを使ってしまうと勉強にならないと感じました。
今回は勉強が目的なので、あえてこちらを使用せずに進めていきます。
構成図
Amazon Neptuneクラスターとそれに接続するプログラムの実行環境として、Jupyter Notebookを用意します。
Amazon Neptuneの設定
NeptuneはServerlessにはせず、インスタンスを一つ作ってクラスターとします。
Neptuneの認証はまずはIAM認証なしとします。
Jupyter Notebookの設定
Notebookは、Neptuneの画面から作れますが、今回はSageMaker側の汎用ノートブックを使用します。
これは、色々とインストールするところから始めないと理解が浅くなると考えたからです。
以下のページのPython を使用して汎用 SageMaker ノートブックを Neptune に接続する
を参考にします。
IaC
AWS CloudFormationテンプレートで書きます。
以下のページを参考にします。
ソースコード
IaCとNeptuneにアクセスするプログラムをこちらにアップしました。
cloudformation
ディレクトリのYAMLファイルを順に実行すれば、VPCとNeptuneクラスター・Notebookができあがります。
Neptuneクラスター・Notebookは、プライベートサブネットに属します。
Neptuneクラスターは、現状Notebookからのアクセスからしか考えておらず、外部からのアクセスは許可していません。
この記述です。
8182
はNeptuneクラスターのデフォルトポート番号です。
NeptuneSecurityGroup:
Type: "AWS::EC2::SecurityGroup"
Properties:
GroupName: !Sub "${ServiceName}-${StageName}-neptune-cluster-sg"
GroupDescription: "Enable access to Neptune"
VpcId: !ImportValue
Fn::Sub: "${ServiceName}-${StageName}-vpc"
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 8182
ToPort: 8182
SourceSecurityGroupId: !Ref NotebookSecurityGroup
Tags:
- Key: "Name"
Value: !Sub "${ServiceName}-${StageName}-neptune-cluster-sg"
- Key: "ServiceName"
Value: !Ref ServiceName
- Key: "StageName"
Value: !Ref StageName
NotebookからNeptuneクラスターにアクセスする
IaCを実行するとNotebookができるようにしています。
SageMakerの画面からNotebookインスタンスを開きます。
Notebookインスタンスの画面でJupyterを開く
をクリック
Notebookの編集画面に遷移したら、下記のページのプログラムを参考にプログラムを実行。
今回はNeptuneに対してGremlinでクエリするため、Gremlin Pythonクライアントをインストール。
!pip install gremlinpython
次にプログラムを実行してNeptuneクラスターにアクセスします。
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
from gremlin_python.driver.aiohttp.transport import AiohttpTransport
from gremlin_python.process.traversal import *
import os
port = 8182
server = '{Neptuneのエンドポイント}'
endpoint = f'wss://{server}:{port}/gremlin'
print(endpoint)
graph=Graph()
connection = None
try:
connection = DriverRemoteConnection(endpoint, 'g',
transport_factory=lambda: AiohttpTransport(call_from_event_loop=True))
g = graph.traversal().withRemote(connection)
results = (g.V().hasLabel('airport')
.sample(10)
.order()
.by('code')
.local(__.values('code', 'city').fold())
.toList())
# Print the results in a tabular form with a row index
for i, c in enumerate(results, 1):
print("%3d %4s %s" % (i, c[0], c[1]))
finally:
if connection is not None:
connection.close()
基本上記参考ページと同じプログラムですが、失敗した時にコネクションが残る動きをするので念の為finally
でコネクション切断処理を入れました。
{Neptuneのエンドポイント}
の部分は、Neptuneクラスターのエンドポイントを入れます。
このプログラムはReadしてるだけなので、エンドポイントのタイプは書き込み・読み込み(ライター・リーダー)どちらのエンドポイントでOKです。
エンドポイントを書き込んだ後、プログラムを実行して結果がPrintされる、またはエラーが起きなければ一旦成功です。
接続不可ならば403エラーなどが発生します。
次回に向けて
今回はここまでです。
第2回目は、Neptuneのデータ読み書きを実行します。