当前位置:   article > 正文

python 操作neo4j_python neo4j

python neo4j
  1. 安装依赖包
pip install neo4j
  • 1
  1. 使用
class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
            #else 指定了每次创建这个示例,都需要执行init函数
        # else:
        #     cls._instances[cls].__init__(*args, **kwargs)
        return cls._instances[cls]


from neo4j import GraphDatabase

class HelloWorldExample(metaclass = Singleton):

    # driver 只运行一次就好,否则会影响性能
    def __init__(self, uri, user, password):
        self.driver = GraphDatabase.driver(uri, auth=(user, password))

    def close(self):
        self.driver.close()

    def print_greeting(self, message):
        with self.driver.session() as session:
            greeting = session.execute_write(self._create_and_return_greeting, message)
            print(greeting)
            
    @staticmethod
    def get_relation(tx,ID=None):
        if ID:
            result = tx.run("MATCH(n1:Node{ID: $ID}) -[r: relation]->(c) return c",ID=ID)
        else:
            result = tx.run("MATCH(n1{ID:1})-[r: relation*..100] -(c) return distinct c")
        return [value[0]._properties for value in result.values()]
    
    def print_relation(self, ID=None):
        with self.driver.session() as session:
            greeting = session.execute_write(self.get_relation, ID)
            print(greeting)

    @staticmethod
    def _create_and_return_greeting(tx, message):
        result = tx.run("CREATE (a:Greeting) "
                        "SET a.message = $message "
                        "RETURN a.message + ', from node ' + id(a)", message=message)
        return result.single()[0]


if __name__ == "__main__":
    greeter = HelloWorldExample("bolt://192.168.214.133:30687", "neo4j", "ellischen")
    greeter.print_relation()
    greeter.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
  • 52

数据参考
https://editor.csdn.net/md/?articleId=130485418

https://neo4j.com/developer/python/

https://medium.com/neo4j/neo4j-driver-best-practices-dfa70cf5a763

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/161275
推荐阅读
相关标签
  

闽ICP备14008679号