0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Neo4jを使ったグラフDBの作成

Last updated at Posted at 2025-07-06

ColabからのNeo4jへのアクセス

!pip install neo4j
from neo4j import GraphDatabase

# URI examples: "neo4j://localhost", "neo4j+s://xxx.databases.neo4j.io"
URI = "neo4j+**********"
AUTH = ("neo4j", "*****")

with GraphDatabase.driver(URI, auth=AUTH) as driver:
    driver.verify_connectivity()
  • URIとAUTHはNeo4jのサイト上でインスタンス作成時に確認可能
  • 上記コードをColab上で実行し、とりあえずNeo4jの環境にアクセスできることが確認できた。

ノードや関係の追加と、Web上での確認

Colab上で下記のコードを実行

ef create_battle_of_sekigahara(tx):
    # ノードの作成
    tx.run("CREATE (ieyasu:Person {name: '徳川家康'})")
    tx.run("CREATE (mitsunari:Person {name: '石田三成'})")
    tx.run("CREATE (eastern_army:Army {name: '東軍'})")
    tx.run("CREATE (western_army:Army {name: '西軍'})")

    # 関係性の作成
    tx.run("""
    MATCH (ieyasu:Person {name: '徳川家康'}), (eastern_army:Army {name: '東軍'})
    CREATE (ieyasu)-[:LEADER_OF]->(eastern_army)
    """)
    tx.run("""
    MATCH (mitsunari:Person {name: '石田三成'}), (western_army:Army {name: '西軍'})
    CREATE (mitsunari)-[:LEADER_OF]->(western_army)
    """)
    tx.run("""
    MATCH (eastern_army:Army {name: '東軍'}), (western_army:Army {name: '西軍'})
    CREATE (eastern_army)-[:BATTLED]->(western_army)
    """)

# セッションの開始
with driver.session() as session:
    session.write_transaction(create_battle_of_sekigahara)

driver.close()

下記のクエリをNeo4jで実行する

MATCH (p)-[r]->(q)
RETURN p, r, q

Neo4j上でグラフDBが作成されたことが確認できた。

image (1).png

参考サイト

ナレッジグラフを構築してみた

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?