LoginSignup
3
3

More than 5 years have passed since last update.

pythonでNeo4jのクエリファイルを自動実行する

Last updated at Posted at 2018-02-16

はじめに

Neo4jのブラウザからクエリを実行するのは手間で時間がかかるし何より面倒くさいのでpythonでクエリを自動実行するスクリプトを書きました

更新履歴

  • 2018/02/17 12:14 readline()からread()に変更
  • 2018/02/19 01:34 大量にノードを追加するとNeo4jが重くなって動かなくなるので制限を追加

ソースコード

## coding:utf-8

import os
import sys
import time
from neo4j.v1 import GraphDatabase

# pip install neo4j-driver

URI      = "bolt://localhost:7687"
USER     = "neo4j"
PASSWORD = "neo4j"

try:
    driver = GraphDatabase.driver(URI, auth=(USER, PASSWORD))
except:
    print("can not connect neo4j")
    os._exit(1)

def regist_from_file(path):
    ts = time.time()
    if not os.path.isfile(path):
        print("{0} is not file".format(path))
        return

    buf = ""
    with open(path, "r") as f:
        buf = f.read()
    with driver.session() as session:
        with session.begin_transaction() as tx:
            try:
                record = tx.run(buf)
            except:
                print("can not run query {0}".format(path))
    te = time.time()
    print("regist {0} {1:.3f}s".format(path, te-ts))

def regist_from_dir(path):
    if not os.path.isdir(path):
        print("{0} is not directory".format(path))
        return
    dirlist = os.listdir(path)
    count = 0
    for f in dirlist:
        fpath = path + "/" + f
        if count >= limit:
            print("reached limit {0}".format(limit))
            return
        regist_from_file(fpath)
        count += 1

def regist_file(path, limit):
    if os.path.isdir(path):
        regist_from_dir(path, limit)
    elif os.path.isfile(path):
        regist_from_file(path)
    else:
        print("{0} is not exists".format(path))

if __name__ == '__main__':
    if len(sys.argv) <= 2:
        print("$PROG PATH LIMIT")
    limit = sys.argv[2]
    regist_file(sys.argv[1], int(sys.argv[2]))

まとめ

自動化によりかなり楽になった。わざわざ1ファイルずつコピペして貼り付けて描画されるのを待つのが馬鹿らしくなった。あの時間は何だったんだろう(笑)
ただ、クエリエラーが出たときに処理が中断してしまうのと、pythonなのかクエリが重いのかそこまで速度が出ていない
他の言語で試していないからわからない

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