<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>neo4jPython Tech</title>
	<atom:link href="https://tech.nkhn37.net/category/python/python-libraries/neo4j/feed" rel="self" type="application/rss+xml" />
	<link>https://tech.nkhn37.net</link>
	<description>Python学習サイト</description>
	<lastBuildDate>Sat, 10 Jan 2026 00:00:45 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://tech.nkhn37.net/wp-content/uploads/2021/01/cropped-lion-normal-clear-1-32x32.png</url>
	<title>neo4jPython Tech</title>
	<link>https://tech.nkhn37.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【Python】neo4jによるグラフデータベースの使い方</title>
		<link>https://tech.nkhn37.net/python-neo4j-graph-database/</link>
					<comments>https://tech.nkhn37.net/python-neo4j-graph-database/#respond</comments>
		
		<dc:creator><![CDATA[naoki-hn]]></dc:creator>
		<pubDate>Thu, 28 Apr 2022 20:00:00 +0000</pubDate>
				<category><![CDATA[neo4j]]></category>
		<category><![CDATA[Cypher Query]]></category>
		<category><![CDATA[グラフデータベース]]></category>
		<guid isPermaLink="false">https://tech.nkhn37.net/?p=3646</guid>

					<description><![CDATA[Pythonでグラフデータベースであるneo4jを操作する方法について解説します。 グラフデータベース neo4j neo4jとは、NeoTechnology社が提供しているグラフデータベースのことを言います。 データベ [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Pythonでグラフデータベースである<span class="marker"><strong>neo4j</strong></span>を操作する方法について解説します。</p>



<h2 class="wp-block-heading jinr-heading d--bold">グラフデータベース neo4j</h2>



<p><span class="marker"><strong>neo4j</strong></span>とは、NeoTechnology社が提供しているグラフデータベースのことを言います。</p>



<p>データベースというとまず最初に思い浮かべるのはリレーショナルデータベース（RDB）かと思います。近年では、キー・バリュー型、列指向型、ドキュメント型などの様々なタイプのデータベースが登場しています。グラフデータベースもそういったデータベースの一種です。</p>



<p>グラフデータベースとは、以下の例のように「ノード」と「リレーションシップ」という要素で構成され、要素と関係性をグラフで表現します。（※このグラフは以降の説明の操作で作成します。）</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="971" height="536" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-55.png" alt="neo4j sample" class="wp-image-3687" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-55.png 971w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-55-300x166.png 300w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-55-768x424.png 768w" sizes="(max-width: 971px) 100vw, 971px" /></figure>
</div>


<p>RDBは、列と行でレコードを表現しますが、グラフデータベースであるneo4jでは、ノード間の関連をリレーションシップという形で紐づけて表現することになります。ネットワーク構造を持つようなデータを直感的に表現できるという利点があります。</p>



<p>また、neo4jではデータベース操作用言語として、<span class="marker"><strong>Cypher Query</strong></span>という言語をサポートします。Cypher QueryはSQLに似た形式となっておりデータのアクセスや表現を行うことができます。簡単な例については以降で紹介します。</p>



<p>本記事では、まずneo4jをインストールし、Cypher Queryでグラフデータベースを操作してみます。その後、Pythonプログラムからアクセスして操作する方法について説明します。</p>



<h2 class="wp-block-heading jinr-heading d--bold">neo4jの利用方法とグラフデータベース作成</h2>



<h3 class="wp-block-heading jinr-heading d--bold">neo4jの利用方法</h3>



<p><span class="marker"><strong>neo4j</strong></span>を利用するにはneo4jの<a rel="noreferrer noopener" href="https://neo4j.com/" target="_blank">公式ページ</a>にアクセスします。そこで、「Start Free for Developers」をクリックしてください。（※公式ページの構成は変わっている可能性があります）</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="1024" height="765" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-29-1024x765.jpg" alt="neo4j 公式ページ" class="wp-image-3647" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-29-1024x765.jpg 1024w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-29-300x224.jpg 300w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-29-768x574.jpg 768w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-29.jpg 1200w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>neo4jはクラウドサービスとして使用できます。本記事での目的は学習目的で使ってみることなので、AuraDB Freeというところの「Start Free」をクリックします。こちらはクレジットカード情報など不要です。用途によってProfessionalやEnterpriseの使用を検討してみてください。</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="1024" height="404" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-39-1024x404.png" alt="neo4j ライセンス" class="wp-image-3659" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-39-1024x404.png 1024w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-39-300x118.png 300w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-39-768x303.png 768w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-39-1536x606.png 1536w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-39.png 1200w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Emailアドレス、パスワードの入力をして「Register」をクリックします。</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-full"><img decoding="async" width="790" height="937" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-31.png" alt="neo4j 登録" class="wp-image-3650" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-31.png 790w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-31-253x300.png 253w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-31-768x911.png 768w" sizes="(max-width: 790px) 100vw, 790px" /></figure>
</div>


<p>Emailの確認が必要でメールが送付されます。メールに記載の「Verify my e-mail address」というボタンを押して確認を完了させてください。メールが届かない場合は、以下のResendを押してみてください。</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="557" height="248" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-32.png" alt="neo4j 登録" class="wp-image-3651" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-32.png 557w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-32-300x134.png 300w" sizes="(max-width: 557px) 100vw, 557px" /></figure>
</div>


<p>Emailの確認後に上記画面のDashboardをクリックするとサービスとプライバシーポリシーの確認が出るので、確認して「I agree」をクリックしてください。</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="544" height="459" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-33.png" alt="neo4j 登録" class="wp-image-3652" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-33.png 544w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-33-300x253.png 300w" sizes="(max-width: 544px) 100vw, 544px" /></figure>
</div>


<p>以上で、neo4jを使用する準備が整います。</p>



<h3 class="wp-block-heading jinr-heading d--bold">neo4jデータベースを作成する</h3>



<p>Dashboardを最初に開くと「Let&#8217;s create your first database」ということで最初のデータベースを作成するページが開かれるかと思います。Database detailsのDatabase Nameの部分に任意のデータベース名を入力して、「Create Database」をクリックしてください。</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="553" height="1024" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-36-553x1024.png" alt="neo4j データベース作成" class="wp-image-3655" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-36-553x1024.png 553w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-36-162x300.png 162w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-36.png 608w" sizes="(max-width: 553px) 100vw, 553px" /></figure>
</div>


<p>上記を実行するとデータベースを作成することができます。</p>



<p>データベースの資格情報として以下のようにUsernameとPasswordが表示されるます。後の接続で必要になりますので控えてから「Continue」をクリックしてください。</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-full"><img decoding="async" width="542" height="641" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-37.png" alt="neo4j データベース作成" class="wp-image-3656" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-37.png 542w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-37-254x300.png 254w" sizes="(max-width: 542px) 100vw, 542px" /></figure>
</div>


<p>以下のようなデータベースが作成されればデータベースの作成は完了です。Runningとなっているので起動状態となっています。</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="569" height="176" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-38.png" alt="neo4j データベース作成" class="wp-image-3657" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-38.png 569w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-38-300x93.png 300w" sizes="(max-width: 569px) 100vw, 569px" /></figure>
</div>


<h2 class="wp-block-heading jinr-heading d--bold">neo4jのグラフデータベース操作用言語 Cypher Query</h2>



<h3 class="wp-block-heading jinr-heading d--bold">WebベースのDB管理ツール</h3>



<p>上記までで、グラフデータベースを作成することができました。データベースのQueryをクリックすると、WebベースのDB管理ツール画面が表示でき、neo4jの操作用言語であるCypher Queryを実行することができるようになります。</p>


<div class="wp-block-image is-resized">
<figure class="aligncenter size-full"><img decoding="async" width="889" height="275" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-40.png" alt="neo4j Cypher Query" class="wp-image-3665" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-40.png 889w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-40-300x93.png 300w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-40-768x238.png 768w" sizes="(max-width: 889px) 100vw, 889px" /></figure>
</div>


<p>以下のようなConnect画面が出ますので、データベース作成時に控えたUsername、Passwordを入力して「Connect」をクリックしてください。</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="1024" height="370" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-41-1024x370.png" alt="neo4j Cypher Query" class="wp-image-3666" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-41-1024x370.png 1024w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-41-300x108.png 300w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-41-768x277.png 768w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-41.png 1039w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>接続できると以下のようにコマンドを入力できるようなコンソール画面になります。neo4jでは、ここにCypher Queryを入力することでデータベースを操作することができます。</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="274" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-42-1024x274.png" alt="neo4j Cypher Query" class="wp-image-3667" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-42-1024x274.png 1024w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-42-300x80.png 300w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-42-768x205.png 768w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-42-1536x411.png 1536w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-42.png 1907w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h3 class="wp-block-heading jinr-heading d--bold">Cypher Queryによるデータの操作例</h3>



<p>Cypher Queryを使ってneo4jを操作する例を簡単な例を使ってみてみましょう。以降のコマンドは、上記のWebの管理ツールのコンソール上にコマンドを打って実行してみます。</p>



<h4 class="wp-block-heading jinr-heading d--bold">ノードの追加</h4>



<p>まずは、簡単にノードを追加してみます。以下のようなCypher Queryを入力して「<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/25b6.png" alt="▶" class="wp-smiley" style="height: 1em; max-height: 1em;" />」をクリックまたは「Ctrl+enter」を押して実行します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">CREATE (p:Person {name: "taro"})
RETURN p</pre>



<p>実行すると、以下のようにtaroというノードが作成されます。</p>



<figure class="wp-block-image size-full"><img decoding="async" width="976" height="536" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-56.png" alt="neo4j python sample" class="wp-image-3691" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-56.png 976w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-56-300x165.png 300w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-56-768x422.png 768w" sizes="(max-width: 976px) 100vw, 976px" /></figure>



<p>Cypher Queryの構成としては、Personという種類のノードで、属性としてname=&#8221;taro&#8221;を持っているものを作成（CREATE）しているということになります。RETURNの部分は表示するものを指定していると思ってもらえればいいかと思います。</p>



<h4 class="wp-block-heading jinr-heading d--bold">リレーションシップの追加</h4>



<p>次にノードとノードをつなぐリレーションシップを作成してみます。以下のようなCypher Queryを入力して実行します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">MATCH (p:Person {name:"taro"})
CREATE (p)-[:FRIEND]->(hanako:Person {name:"hanako"})
RETURN p,hanako</pre>



<p>上記のコマンドは、まずtaroをMATCHでpに取得してきて、hanakoとFRIENDというリレーションシップでつなぐという意味になっています。実行すると、以下のようにhanakoというノードが作成されるとともにFRIENDという関係の矢印が作成されます。</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="984" height="540" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-53.png" alt="neo4j python sample" class="wp-image-3685" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-53.png 984w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-53-300x165.png 300w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-53-768x421.png 768w" sizes="(max-width: 984px) 100vw, 984px" /></figure>
</div>


<p>リレーションシップについては、Cypher Queryで「()-[]-&gt;()」という形式を使うことでノード間を接続します。[]の部分がリレーションシップの定義です。今回の例では[:FRIEND]というのはFRIENDという種類の関係性を作成していることを意味しています。</p>



<h4 class="wp-block-heading jinr-heading d--bold">繰り返しを使用する</h4>



<p>Cypher Queryでは繰り返しで関係性を作ることも可能です。以下のようなCypher Queryを実行します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">MATCH (p:Person {name:"taro"})
FOREACH (name in ["jiro", "haruka", "sakura"] | 
  CREATE (p)-[:FRIEND]->(:Person {name:name}))</pre>



<p>上記を実行すると「Added ~」というような形で表示がされると思います。その後、以下で全てのノードと関係性を表示してみてください。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">MATCH (n) OPTIONAL MATCH (n)-[r]-()
RETURN n,r</pre>



<p>以下の図のようにtaroから各ノードへの関係性が作成されたのが分かるかと思います。</p>



<figure class="wp-block-image size-full"><img decoding="async" width="971" height="536" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-54.png" alt="neo4j python sample" class="wp-image-3686" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-54.png 971w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-54-300x166.png 300w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-54-768x424.png 768w" sizes="(max-width: 971px) 100vw, 971px" /></figure>



<p>プログラミングにある程度慣れている方なら直感的にわかるかと思いますが、inに指定しているリストの中身が順にnameに設定され、CREATEで設定しているname属性の値として使用されています。Pythonのfor _ in ~という形と同じですので、Pythonプログラムを作ったことがある方であれば分かりやすいのではないかと思います。</p>



<h4 class="wp-block-heading jinr-heading d--bold">全てのノードを検索する</h4>



<p>既に上記で出てきていますが、データベース上の全てのノードを検索するには、以下のようなCypher Queryを実行します。よく使う方法として覚えておくとよいでしょう。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">MATCH (n) OPTIONAL MATCH (n)-[r]-()
RETURN n,r</pre>



<h4 class="wp-block-heading jinr-heading d--bold">全てのノードを削除する</h4>



<p>データベース上の全てのノードを削除するには、以下のようなCypher Queryを実行します。データを一度リセットしたい場合に使用できます。上記のサンプルを実行していてよく分からなくなった場合は、一度全て削除してみて再度操作してみてください。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">MATCH (n) OPTIONAL MATCH (n)-[r]-()
DELETE n,r</pre>



<section class="wp-block-jinr-blocks-iconbox b--jinr-block b--jinr-iconbox"><div class="d--simple-iconbox6 ">
			<i class="jif jin-ifont-v2books" aria-hidden="true"></i>
			<div class="a--jinr-iconbox">
<p>Cyper Query Language については、neo4j の Developer Guide の<a href="https://neo4j.com/docs/cypher-manual/current/introduction/" target="_blank" rel="noreferrer noopener">こちら</a>を参考にしてください。</p>
</div>
		</div></section>



<h2 class="wp-block-heading jinr-heading d--bold">Pythonからneo4jグラフデータベースを操作する</h2>



<p>上記まででneo4jのインストール方法とCypher Queryによるデータベースの簡単な操作方法について紹介してきました。以降では、Pythonプログラムから直接neo4jのデータベースを操作する方法について紹介します。</p>



<h3 class="wp-block-heading jinr-heading d--bold">Pythonで使用するためにneo4jをインストールする</h3>



<p>Pythonでneo4jを使用するには、以下のようにpip installでインストールを実行します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install neo4j</pre>



<p>正常に完了すればneo4jをPythonで使用する環境が整います。</p>



<h3 class="wp-block-heading jinr-heading d--bold">Pythonでneo4jを使用するサンプルプログラム</h3>



<p>neo4jにPythonでアクセスするためのサンプルプログラムを以下に示します。</p>



<p>接続情報はneo4j.iniというファイルに記載して、configparserで読み込む形式にしています。以下の記載は接続情報などはXXXというように伏せているため皆さんの環境の接続情報に書き換えて使ってみてください。</p>



<p><strong>【設定ファイル】</strong>neo4j.ini</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[NEO4J]
uri = neo4j+s://xxxxxxxxxxxxxxxx:7687
user = xxxxxx
password = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</pre>



<p><strong>【サンプルプログラム】</strong>neo4j_sample.py</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import configparser

from neo4j import GraphDatabase


def clear_db(tx):
    tx.run('MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n,r')


def search_all(tx):
    result = tx.run('MATCH (n) OPTIONAL MATCH (n)-[r]-() RETURN n,r')
    return [r for r in result]


def add_person_node(tx, name):
    tx.run('CREATE (p:Person {name: $name}) RETURN p', {'name': name})


def add_friend_relationship(tx, name, friend_name=None):
    if not friend_name:
        tx.run('CREATE (p:Person {name: $name}) RETURN p', {'name': name})
    else:
        tx.run('MATCH (p:Person {name: $name}) '
               'CREATE (p)-[:FRIEND]->(:Person {name: $friend_name})',
               name=name, friend_name=friend_name)


def main():
    # ===== neo4jの設定取得
    config = configparser.ConfigParser()
    config.read('neo4j.ini')
    uri = config['NEO4J']['uri']
    user = config['NEO4J']['user']
    password = config['NEO4J']['password']

    # neo4jドライバーの作成
    driver = GraphDatabase.driver(uri, auth=(user, password))
    with driver.session() as session:
        # データベースのクリア
        session.write_transaction(clear_db)

        # ノードの追加
        session.write_transaction(add_person_node, 'taro')

        # FRIEND関係の追加
        session.write_transaction(add_friend_relationship, 'taro', 'hanako')
        # 繰り返しで追加
        friend_list = ['jiro', 'haruka', 'sakura']
        for f in friend_list:
            session.write_transaction(add_friend_relationship, 'taro', f)

        # データの検索
        result = session.read_transaction(search_all)

    # 結果の確認
    for res in result:
        print(res)


if __name__ == '__main__':
    main()</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
&lt;Record n=&lt;Node id=63 labels=frozenset({'Person'}) properties={'name': 'taro'}> r=&lt;Relationship id=42 nodes=(&lt;Node id=63 labels=frozenset({'Person'}) properties={'name': 'taro'}>, &lt;Node id=67 labels=frozenset({'Person'}) properties={'name': 'sakura'}>) type='FRIEND' properties={}>>
&lt;Record n=&lt;Node id=63 labels=frozenset({'Person'}) properties={'name': 'taro'}> r=&lt;Relationship id=41 nodes=(&lt;Node id=63 labels=frozenset({'Person'}) properties={'name': 'taro'}>, &lt;Node id=66 labels=frozenset({'Person'}) properties={'name': 'haruka'}>) type='FRIEND' properties={}>>
&lt;Record n=&lt;Node id=63 labels=frozenset({'Person'}) properties={'name': 'taro'}> r=&lt;Relationship id=40 nodes=(&lt;Node id=63 labels=frozenset({'Person'}) properties={'name': 'taro'}>, &lt;Node id=65 labels=frozenset({'Person'}) properties={'name': 'jiro'}>) type='FRIEND' properties={}>>
&lt;Record n=&lt;Node id=63 labels=frozenset({'Person'}) properties={'name': 'taro'}> r=&lt;Relationship id=39 nodes=(&lt;Node id=63 labels=frozenset({'Person'}) properties={'name': 'taro'}>, &lt;Node id=64 labels=frozenset({'Person'}) properties={'name': 'hanako'}>) type='FRIEND' properties={}>>
&lt;Record n=&lt;Node id=64 labels=frozenset({'Person'}) properties={'name': 'hanako'}> r=&lt;Relationship id=39 nodes=(&lt;Node id=63 labels=frozenset({'Person'}) properties={'name': 'taro'}>, &lt;Node id=64 labels=frozenset({'Person'}) properties={'name': 'hanako'}>) type='FRIEND' properties={}>>
&lt;Record n=&lt;Node id=65 labels=frozenset({'Person'}) properties={'name': 'jiro'}> r=&lt;Relationship id=40 nodes=(&lt;Node id=63 labels=frozenset({'Person'}) properties={'name': 'taro'}>, &lt;Node id=65 labels=frozenset({'Person'}) properties={'name': 'jiro'}>) type='FRIEND' properties={}>>
&lt;Record n=&lt;Node id=66 labels=frozenset({'Person'}) properties={'name': 'haruka'}> r=&lt;Relationship id=41 nodes=(&lt;Node id=63 labels=frozenset({'Person'}) properties={'name': 'taro'}>, &lt;Node id=66 labels=frozenset({'Person'}) properties={'name': 'haruka'}>) type='FRIEND' properties={}>>
&lt;Record n=&lt;Node id=67 labels=frozenset({'Person'}) properties={'name': 'sakura'}> r=&lt;Relationship id=42 nodes=(&lt;Node id=63 labels=frozenset({'Person'}) properties={'name': 'taro'}>, &lt;Node id=67 labels=frozenset({'Person'}) properties={'name': 'sakura'}>) type='FRIEND' properties={}>></pre>



<p><strong>【実行後neo4jの状態】</strong></p>



<figure class="wp-block-image size-full"><img decoding="async" width="977" height="543" src="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-52.png" alt="neo4j python sample" class="wp-image-3684" srcset="https://tech.nkhn37.net/wp-content/uploads/2022/04/image-52.png 977w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-52-300x167.png 300w, https://tech.nkhn37.net/wp-content/uploads/2022/04/image-52-768x427.png 768w" sizes="(max-width: 977px) 100vw, 977px" /></figure>



<p>実行結果を管理ツールで見てみると前の節で順番にCypher Queryを実行したのと同じグラフができていることが分かります。コンソール上の出力結果では、グラフに出てくる全てのノードと関係性が列挙されます。</p>



<p>以降でサンプルの説明をしていきます。</p>



<h4 class="wp-block-heading jinr-heading d--bold">Pythonからneo4jへ接続する</h4>



<p>neo4jを使用するためには、neo4jパッケージからGraphDatabaseをimportします。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from neo4j import GraphDatabase</pre>



<p>以下の部分はneo4j.iniから接続情報を取得している部分です。neo4jというよりconfigparserモジュールの使い方というところですので、configparserの使い方が分からない方は「<a href="https://tech.nkhn37.net/python-configparser-basic/" target="_blank" rel="noreferrer noopener">configparserによるconfigファイル管理</a>」も参考にしてください。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    # ===== neo4jの設定取得
    config = configparser.ConfigParser()
    config.read('neo4j.ini')
    uri = config['NEO4J']['uri']
    user = config['NEO4J']['user']
    password = config['NEO4J']['password']</pre>



<p>neo4jに接続するには、以下の記載の部分のようにドライバーを取得し、sessionにより接続します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    driver = GraphDatabase.driver(uri, auth=(user, password))
    with driver.session() as session:</pre>



<h4 class="wp-block-heading jinr-heading d--bold">write_transactionでneo4jに書き込みを行う</h4>



<p>neo4jへ書き込みを行う場合には、neo4jのセッションを作成した後に<span class="marker"><strong>write_transaction</strong></span>を使用することで実行できます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    with driver.session() as session:
        # データベースのクリア
        session.write_transaction(clear_db)

        # ノードの追加
        session.write_transaction(add_person_node, 'taro')

        # FRIEND関係の追加
        session.write_transaction(add_friend_relationship, 'taro', 'hanako')
        # 繰り返しで追加
        friend_list = ['jiro', 'haruka', 'sakura']
        for f in friend_list:
            session.write_transaction(add_friend_relationship, 'taro', f)</pre>



<p>具体的には、処理に関する関数とその関数に渡す引数を渡します。関数自体を渡すことになりますので、session.write_transaction(clear_db)というようにclear_db関数に()はないことに注意しましょう。例えばclear_dbはデータベースをすべて削除する関数です。</p>



<p>具体的に渡す関数として実装しているのは以下の部分です。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def clear_db(tx):
    tx.run('MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n,r')


def add_person_node(tx, name):
    tx.run('CREATE (p:Person {name: $name}) RETURN p', {'name': name})


def add_friend_relationship(tx, name, friend_name=None):
    if not friend_name:
        tx.run('CREATE (p:Person {name: $name}) RETURN p', {'name': name})
    else:
        tx.run('MATCH (p:Person {name: $name}) '
               'CREATE (p)-[:FRIEND]->(:Person {name: $friend_name})',
               name=name, friend_name=friend_name)</pre>



<p>関数はtxという引数を受け取るように作成します。neo4jモジュールのwrite_transactionの方でtxが設定され、tx.runによりCypher Queryを実行します。clear_dbは単純にデータを全て削除するCypher Queryをtx.runに渡していることが分かるかと思います。</p>



<p>一方で、add_person_nodeやadd_friend_relationshipという方は、txの他に引数を受け取っています。受け取った引数は、Cypher Query上で$name、$friend_nameのように指定することで、受け取った引数を当てはめてCypher Queryを実行できます。Oracle等のDBMSをプログラムから扱ったことがある人であればバインド変数と思っていただければわかるかと思います。</p>



<h4 class="wp-block-heading jinr-heading d--bold">read_transactionでneo4jからデータを取得する</h4>



<p>neo4jの読み込みを行う場合には、neo4jのセッションを作成した後に<span class="marker"><strong>read_transaction</strong></span>を使用することで実行できます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    with driver.session() as session:
        # データの検索
        result = session.read_transaction(search_all)

    # 結果の確認
    for res in result:
        print(res)</pre>



<p>read_transactionに渡している関数であるsearch_allは以下の部分で定義しています。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def search_all(tx):
    result = tx.run('MATCH (n) OPTIONAL MATCH (n)-[r]-() RETURN n,r')
    return [r for r in result]</pre>



<p>考え方は上記のwrite_transactionと同様です。全データ検索用のCypher Queryをtx.runに渡しています。結果は「&#8217;neo4j.work.result.Result&#8217;」というもので返却されますが扱いやすいようにリスト内包表記でリストに返却して返しています。</p>



<p></p>



<p>以上が、Pythonでのneo4jでの簡単な使い方です。write_transactionやread_transactionに渡す関数を色々変えてもらえば任意のデータベース操作関数や専用のクラスを作成するといったことも可能になります。色々試してみてください。</p>


<section class="b--jinr-block b--jinr-blogcard d--blogcard-hover-up d--blogcard-style1 d--blogcard-mysite t--round "><div class="a--blogcard-label ef">あわせて読みたい</div><a class="o--blogcard-link t--round" href="https://tech.nkhn37.net/python-tech-summary-page/"><div class="c--blogcard-image"><img decoding="async" class="a--blogcard-img-src" width="128" height="72" src="https://tech.nkhn37.net/wp-content/uploads/2024/08/Python-Tech-Pythonプログラミングガイド_new1-640x360.jpg" alt="【Python Tech】プログラミングガイド" /></div><div class="a--blogcard-title d--bold">【Python Tech】プログラミングガイド</div></a></section>]]></content:encoded>
					
					<wfw:commentRss>https://tech.nkhn37.net/python-neo4j-graph-database/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Disk: Enhanced  を使用したページ キャッシュ

Served from: tech.nkhn37.net @ 2026-04-06 01:23:27 by W3 Total Cache
-->