1. 定义单实例的driver对象,在python应用中利用此driver完成neo4j的操作
from neo4j import GraphDatabase
driver = GraphDatabase.driver(uri, auth=(username, password))
# 可以检查连接状态
driver.verify_connectivity()
2. 定义工作单元函数 Unit of Work
该函数接收的第一个参数是tx,代表driver对应的事务对象。内部一般是由三部分构成,分别是cypher字符串,tx.run()语句和返回值。cypher字符串的变量可以用 .format 带入,也可以用$占位,然后利用tx.run(cypher,params)的参数params完成字符变量替换。
# 读
def get_movies(tx, sort, order, limit, skip, user_id):
cypher = """
MATCH (m:Movie)
WHERE exists(m.`{0}`)
RETURN m {{ .* }} AS movie
ORDER BY m.`{0}` {1}
SKIP $skip
LIMIT $limit
""".format(sort, order)
result = tx.run(cypher, limit=limit, skip=skip, user_id=user_id)
return [row.value("movie") for row in result]
# 写
def create_user(tx, email, encrypted, name):
return tx.run("""
CREATE (u:User {
userId: randomUuid(),
email: $email,
password: $encrypted,
name: $name
})
RETURN u
""",
email=email,
encrypted=encrypted,
name=name
).single()
3. 利用事务执行单元函数
# 读
with self.driver.session() as session:
return session.read_transaction(get_movies, sort, order, limit, skip, user_id)
# 写
with self.driver.session() as session:
result = session.write_transaction(
create_user,
email,
encrypted,
name
)
user = result['u']
当然,这里也可以自定义错误处理
# Import the Exception classes from neo4j.exceptions
from neo4j.exceptions import Neo4jError, ConstraintError
# Attempt a query
try:
tx.run(cypher, params)
except ConstraintError as err:
print("Handle constaint violation")
print(err.code)
print(err.message)
except Neo4jError as err:
print("Handle generic Neo4j Error")
print(err.code)
print(err.message)
网友评论