[Neo4j系列十三]Neo4j的python操作库Neo4j-Driver

neo4j 1年前 ⋅ 1452 阅读

Neo4j Bolt Driver for Python是python操作neo4j的基础库,像py2neo,neomodel都是基于Neo4j-Driver开发的,封装一些易用的方法。在使用Neo4j-Driver时,你可以发挥cypher的一切可能性,包括使用扩展包apoc和algo等,这也就是你的开发工作非常灵活。

1.安装python驱动包

  • pip源安装

pip install neo4j-driver
  • pip的github链接安装

pip install git+https://github.com/neo4j/neo4j-python-driver.git#egg=neo4j-driver

2.Driver Objects

每一个基于neo4j的应用都需要driver对象,这个对象包含了与neo4j数据库建立连接的细节,其中包括URI,证书和其他配置。

  • Driver构建

    • 直接import DirectDriver类
      from neo4j.v1 import DirectDriver

 from neo4j.v1 import DirectDriver
 driver = DirectDriver("bolt://localhost:7687", auth=("neo4j", "123"))
  • 通过GraphDatabase类方法

from neo4j.v1 import GraphDatabase
diver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "123"))
  • URI
    bolt协议,地址,端口号组成uri

  • Configuration

    • auth
      对于数据库server的认证,比如(“neo4j”, “password”)

    • encrypted
      是否具有安全传输层协议Transport Layer Security,TLS如果可以则默认为True

    • 其他
      trust 信任度
      user_agent 用户代理
      max_connection_lifetime 最大的连接存活时间
      max_connection_pool_size 最大连接池数量
      connection_acquisition_timeout 获得连接认可的最长时间
      connection_timeout 等待一个新连接的最长时间
      keep_alive 否使用TCP KEEP_ALIVE设置
      max_retry_time 最大的重试时间

3.Sessions & Transactions

neo4j支持三种事务类型auto-commit transactions(自动提交事务), explicit transactions (明确事务)and transaction functions(事务函数).

  • 自动提交事务Auto-commit Transactions
    使用Session.run(),这种方式快速简单,但也需要一次声明一次事务,同时提交失败后不会自动重试。

def create_person(driver, name):
    with driver.session() as session:        return session.run("CREATE (a:Person {name:$name}) "
                           "RETURN id(a)", name=name).single().value()
  • 明确事务 Explicit Transactions
    使用Session.begin_transaction()创建事务开始,使用with自动关闭
    使用Transaction.success检测是否成功
    使用Transaction.commit()与Transaction.rollback()明确地控制事务过程

def create_person(driver, name):
    with driver.session() as session:
        tx = session.begin_transaction()
        node_id = create_person_node(tx)
        set_person_name(tx, node_id, name)
        tx.commit()def create_person_node(tx):
    return tx.run("CREATE (a:Person)"
                  "RETURN id(a)", name=name).single().value()def set_person_name(tx, node_id, name):
    tx.run("MATCH (a:Person) WHERE id(a) = $id "
           "SET a.name = $name", id=node_id, name=name)
  • 事务函数 Transaction Functions
    事务函数是目前最强大的事务提交形式,提供存取模式与重试功能。

def create_person(tx, name):
    return tx.run("CREATE (a:Person {name:$name}) "
                  "RETURN id(a)", name=name).single().value()with driver.session() as session:
    node_id = session.write_transaction(create_person, "Alice")

参考链接:https://neo4j.com/docs/api/python-driver/current/index.html

更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: