本文档将介绍在CentOS 7.3上部署图数据库Neo4j,包括使用Python访问Neo4j图数据库。
步骤一:安装JDK(略)
步骤二:安装Python 2.7版本
[root@openstack-node1 tmp]# python -V Python 2.7.5
步骤三:安装neo4j
[root@openstack-node1 tmp]# cd /tmp [root@openstack-node1 tmp]# wget http://debian.neo4j.org/neotechnology.gpg.key [root@openstack-node1 tmp]# rpm --import neotechnology.gpg.key [root@openstack-node1 tmp]# cat <<EOF > /etc/yum.repos.d/neo4j.repo > [neo4j] > name=Neo4j Yum Repo > baseurl=http://yum.neo4j.org/stable > enabled=1 > gpgcheck=1 > EOF [root@openstack-node1 tmp]# yum install neo4j -y
步骤三:安装Python的接口驱动去访问Neo4j
[root@openstack-node1 tmp]# yum -y install epel-release [root@openstack-node1 tmp]# yum -y install python-pip [root@openstack-node1 tmp]# pip install neo4j-driver [root@openstack-node1 tmp]# pip install --upgrade pip
步骤四:启动Neo4j
[root@openstack-node1 tmp]# neo4j --help Usage: neo4j { console | start | stop |restart | status | version } [root@openstack-node1 tmp]# neo4j console Active database: graph.db Directories in use: home: /var/lib/neo4j config: /etc/neo4j logs: /var/log/neo4j plugins: /var/lib/neo4j/plugins import: /var/lib/neo4j/import data: /var/lib/neo4j/data certificates: /var/lib/neo4j/certificates run: /var/run/neo4j Starting Neo4j. ……
安装好以后,在控制台启动Neo4j,然后打开浏览器访问http://192.168.1.11:7474/ ,就可以查看Neo4j服务了。
登录图数据库的时候使用默认的用户名和密码(neo4j)连接,连接成功后需要修改neo4j的默认密码。
步骤五:运行Python测试用例
Neo4j支持一种叫做cypher的图查询语言,这里定义一个执行cypher的函数,然后调用插入一些测试数据,代码如下:
# !/usr/bin/python # -*- coding: utf-8 -*- """ create_author : jiangshouzhuang create_time : 2017-06-07 program : *_* Read and Write Neo4j *_* """ from neo4j.v1 import GraphDatabase class Neo4jHandler: """ Handler of graph database Neo4j reading and writing. """ def __init__(self,driver): """ Get Neo4j server driver. :param driver: driver object A driver object holds the detail of a Neo4j database including serverURIs,credentials and other configuration,see " http://neo4j.com/docs/api/python-driver/current/driver.html". """ self.driver = driver def __repr__(self): printer = 'o(>﹏<)o ......Neo4j old driver "{0}" carry me fly......o(^o^)o'.format(self.driver) return printer def listreader(self,cypher,keys): """ Read data from Neo4j in specified cypher. Read and parse data straightly from cypher field result. :param cypher: string Valid query cypher statement. :param keys: list Cypher query columns to return. :return: list Each returned record constructs a list and stored in a big list,[[...],[...],...]. """ with self.driver.session() as session: with session.begin_transaction() as tx: data = [] result = tx.run(cypher) for record in result: rows = [] for key in keys: rows.append(record[key]) data.append(rows) return data def dictreader(self,cypher): """ Read data from Neo4j in specified cypher. The function depends on constructing dict method of dict(key = value) andany error may occur if the "key" is invalid to Python. you can choose function dictreaderopted() below to read data by hand(viathe args "keys"). :param cypher: string Valid query cypher statement. :return: list Each returned record constructs a dict in "key : value" pairsand stored in a big list,[{...},{...},...]. """ with self.driver.session() as session: with session.begin_transaction() as tx: data = [] for record intx.run(cypher).records(): item = {} for args instr(record).split('>')[0].split()[1:]: exec"item.update(dict({0}))".format(args) data.append(item) return data def dictreaderopted(self,keys=None): """ Optimized function of dictreader(). Read and parse data straightly from cypher field result. :param cypher: string Valid query cypher statement. :param keys: list,default : none(call dictreader()) Cypher query columns to return. :return: list. Each returned record constructs an dict in "key : value" pairsand stored in a list,...]. """ if not keys: return self.dictreader(cypher) else: with self.driver.session() as session: with session.begin_transaction()as tx: data = [] result =tx.run(cypher) for record in result: item = {} for key in keys: item.update({key :record[key]}) data.append(item) return data def cypherexecuter(self,cypher): """ Execute manipulation into Neo4j in specified cypher. :param cypher: string Valid handle cypher statement. :return: none. """ with self.driver.session() as session: with session.begin_transaction() as tx: tx.run(cypher) session.close() # self test if __name__ == "__main__": uri = "bolt://192.168.1.11:7687" driver = GraphDatabase.driver(uri,auth=("neo4j","zhangyun")) MyNH = Neo4jHandler(driver) print(MyNH) cypher_exec = """ CREATE (Neo:Crew{name:'Neo'}),(Morpheus:Crew{name: 'Morpheus'}),(Trinity:Crew {name:'Trinity'}),(Cypher:Crew:Matrix{name: 'Cypher'}),(Smith:Matrix {name:'Agent Smith'}),(Architect:Matrix{name:'The Architect'}),(Neo)-[:KNOWS]->(Morpheus),(Neo)-[:LOVES]->(Trinity),(Morpheus)-[:KNOWS]->(Trinity),(Morpheus)-[:KNOWS]->(Cypher),(Cypher)-[:KNOWS]->(Smith),(Smith)-[:CODED_BY]->(Architect) """ # "example cypher statement fromhttp://console.neo4j.org/" cypher_read = """ MATCH (a)-[:KNOWS|LOVES]-> (b:Crew {name: 'Trinity'}) RETURN a.name AS l,b.nameAS r """ MyNH.cypherexecuter(cypher_exec) print(MyNH.listreader(cypher_read,['l','r'])) print(MyNH.dictreader(cypher_read)) print(MyNH.dictreaderopted(cypher_read,['l']))
将上述的代码保存到本地的文件中,比如neo4j_python_example.py,然后运行:
[root@openstack-node1 neo4j]# pythonneo4j_python_example.py o(>﹏<)o ......Neo4jold driver "<neo4j.v1.direct.DirectDriver object at0x7f87bcc6eed0>" carry me fly...... o(^o^)o [[u'Morpheus',u'Trinity'],[u'Neo',u'Trinity']] [{'r': u'Trinity','l': u'Morpheus'},{'r':u'Trinity','l': u'Neo'}] [{'l': u'Morpheus'},{'l': u'Neo'}]
然后再登录Neo4j查看:
原文链接:https://www.f2er.com/centos/377285.html