目录
1、安装库
pip install neo4j-driver
2、Python写数据库的基本操作
这种方式读写neo4j时,write_transaction主要接受两个参数,一个是操作数据库的函数,一个是要写入的数据的参数。而且可以看到,其实写数据到neo4j的函数create_person_node主要做是,构建Cypher语句,这个语句可以是任何的在neo4j数据库操作的原生语句。
例子中给出的是一个创建节点的Cyber语句,其实,这里也可以是一个创建关系的语句,或者查询的句子,都可以。具体的Cyber操作可以参考:https://blog.csdn.net/u011412768/article/details/109730567
另一个就是写数据时要用到的参数,一般就是节点的一些属性,这里只是给了一个name的属性,其实也可以加其他的属性,参数的使用方法和这里的name是一样的。
from neo4j import GraphDatabase
neo4j_username = "neo4j"
neo4j_password = "1234"
neo4j_bolt = "bolt://xx.xx.xx.xx:7687"
# 写入函数
def create_person_node(tx, name):
cmd = "CREATE (a:Person {name: $name}) RETURN id(a)"
tx.run(cmd , name=name)
# 建立连接
neo4j_client = GraphDatabase.driver(neo4j_bolt, auth=(neo4j_username, neo4j_password))
# 创建会话
_session = neo4j_client.session()
# 写入节点或者关系
_session.write_transaction(create_person_node, name)
# 关闭连接
neo4j_client.close()
关于Python通过neo4j-driver操作可以参考相应库的官方操作手册,这里也有一个可以参考的:https://www.cnblogs.com/ljhdo/p/10907941.html
3、Python 批量写neo4j数据库
在neo4j原生数据库中的操作可以参考:https://blog.csdn.net/for_yayun/article/details/105493946
把这种思想在Python中实现可以参考如下:
def _create_location_rel(self, tx, rows):
cql_command = "UNWIND $rows as row " \
"MERGE (src_node:profile{name: row.profile_id}) " \
"MERGE (location_node:location{name:row.camera_id,period:row.rel_period}) " \
"WITH src_node, location_node, row " \
"MERGE (src_node)-[r:top_location{count:row.camera_count}]->(location_node)"
tx.run(cql_command, rows=rows)
return None
i = 0
rows = []
for index, row in location_result.iterrows():
# 写入的每一条记录
rows.append({
"profile_id": str(row["profile_id"]),
"camera_id": str(row["camera_id"]),
"camera_count": row["camera_count"],
"rel_period": "{}_{}".format(start_datestr, end_datestr)
})
# 每1000条为一批数据,写到数据库中
i += 1
if i % 1000 == 0:
self.neo4j_client.session().write_transaction(_create_location_rel, rows)
print("finish write rows of {}".format(i))
rows = []
其它批量更新的方法可以参考:
Neo4j 批量 导入 数据 的 几种方式:http://weikeqin.com/2017/04/14/neo4j-import-data/
neo4j批量更新数据:https://www.cnblogs.com/ljhdo/p/5554560.html
4、Python查询neo4j数据
查询节点
def check_profile(tx, profile_id):
cql_command = "match (n:profile{name:'%s'}) return n.name" % (profile_id)
node = tx.run(cql_command).single()
return node
查询关系
def get_location(tx, profile_id, period):
cql_command = "match (:profile{name:'%s'})-[relation:top_location]->(location:location{period:'%s'})" \
"return relation, location" % (profile_id, period)
data = tx.run(cql_command).data()
return data
search_result = neo4j_client.session().write_transaction(get_location, aid, period)
location_count = {}
for result in search_result:
location_count[result["location"].get("name")] = result["relation"].get("count")