2
0

Amazon NeptuneでグラフDBを体験してみる① Neptuneとクエリ実行環境を用意する

Last updated at Posted at 2024-09-01

こんにちは。Kaneyasuです。

今回からしばらくAmazon NeptuneでグラフDBを体験してみるというシリーズ記事を書いていきます。
本記事はシリーズの1回目です。

本シリーズ記事の目標

  • グラフ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クラスターのデフォルトポート番号です。

cloudformation/graphdb_2_neptune.yaml
  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インスタンスを開きます。

SageMakerの画面でNotebookインスタンスを開く

Notebookインスタンスの画面でJupyterを開くをクリック
Jupyterを開くをクリック

Newで、conda_python3をクリック
 2024-09-01 20.03.24.png

Notebookの編集画面に遷移したら、下記のページのプログラムを参考にプログラムを実行。

今回はNeptuneに対してGremlinでクエリするため、Gremlin Pythonクライアントをインストール。

!pip install gremlinpython

Gremlin Pythonクライアントをインストール

次にプログラムを実行して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です。

Neptuneクラスターのエンドポイント

エンドポイントを書き込んだ後、プログラムを実行して結果がPrintされる、またはエラーが起きなければ一旦成功です。
接続不可ならば403エラーなどが発生します。

次回に向けて

今回はここまでです。
第2回目は、Neptuneのデータ読み書きを実行します。

2
0
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
2
0