当前位置:   article > 正文

python操作neo4j_from neo4j import graphdatabase

from neo4j import graphdatabase

python API操作neo4j

下载neo4j库

pip install neo4j -i https://mirror.baidu.com/pypi/simple
  • 1

连接neo4j

默认用户名和密码是neo4j

from neo4j import GraphDatabase 
url = "neo4j://localhost:7687"
username = "neo4j"
password = "neo4j"

GraphDatabase.driver(url, auth=(username, password))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

没报错就是连接成功

python 操作 neo4j 示例

from neo4j import GraphDatabase 

class HelloWorldExample:
    def __init__(self, uri, user, password):
        self.driver = GraphDatabase.driver(uri, auth=(user, password))
    
    def close(self):
        self.driver.close()
    
    def clear_data(self):
        def work(tx):
            tx.run("""
            MATCH (n) DETACH DELETE n
            """)
        with self.driver.session() as session:
            session.write_transaction(work)
    
    def create_node(self):
        def person_work(tx):
            tx.run("""create(p:Person{name: "小明"})""")
            tx.run("""create(p:Person{name: "小美"})""")
        with self.driver.session() as session:
            session.write_transaction(person_work)
    
    def create_relationship(self):
        def work(tx):
            tx.run("""MATCH (a:Person {name:'小明'}), (b:Person {name:'小美'}) MERGE (a)-[:爱]->(b)""")
        with self.driver.session() as session:
            session.write_transaction(work)
    
    def search(self, message):
        with self.driver.session() as session:
            greeting = session.write_transaction(self._work_search, message)
            print(greeting)
    
    @staticmethod
    def _work_search(tx, userName):
        result = tx.run("match(p:Person{name:$userName})-[:爱]-(whom) return whom.name", userName=userName)
        return result.single()[0]

url = "neo4j://localhost:7687"
username = "neo4j"
password = "neo4j"

app = HelloWorldExample(url, username, password)

app.clear_data()
app.create_node()
app.create_relationship()
app.search('小明')
app.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

如下图,实体和关系已建好,可以进行查询等操作
在这里插入图片描述

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号