cypher操作图数据库

简单示例

sql语法

  • 在Match语法中,无法关系使用$引入变量(案例中的max_path_len)。如果一定要引入,就使用format的字符串占位符方法。
  • 在Match语法中,允许节点的属性使用$引入变量。
  • 如果sql已经使用了format格式,由于节点属性是用{}括起来的,f占位符也是用{}括起来,未避免冲突,对属性值需要使用双{},如f"xxx (a:Company {{name:$name}})-[*...{max_path_len}]-()"。

返回值

  • 返回值类型type(results) = <class 'py2neo.cypher.Cursor'>,可迭代列表里的每个元素type(result) = <class 'py2neo.cypher.Record'>。

  • 通过 result['属性名']的方式获取对应sql return里各个对象值。

  • 节点Node对象默认是不可哈希的,而set要求元素是可hash的,所以即使两个Node对象有相同的属性,它们也被视为是不同的对象,导致不能直接使用set(nodes)去重。

    from py2neo import Graph

    database_url = "http://localhost:7474"

    database_url = "bolt://localhost:7687"
    database_username = "neo4j"
    database_password = "neo4jcf"

    Bolt是Neo4j专门为图数据库设计的高性能网络协议,它是二进制的,比HTTP协议更快、更轻量级。

    graph = Graph(database_url, auth=(database_username, database_password))

    查询的最大路径长度

    max_path_len = 3

    def has_duplicates(nodes: tuple):
    # 由于Node对象默认是不可哈希的,而set要求元素是可hash的,所以即使两个Node对象有相同的属性,它们也被视为是不同的对象,导致不能直接使用set(nodes)去重。
    name_set = set(node["name"] for node in nodes)
    return len(nodes) != len(name_set)

    方案一:在节点中指定属性

    cypher_query = f"""
    MATCH path=(a:Company {{name:$name}})-[*..{max_path_len}]-(b:Company)
    RETURN path
    """

    方案二:在where中指定属性

    cypher_query = f"""

    MATCH path=(a:Company)-[*..{max_path_len}]-(b:Company)

    where a.name=$name

    RETURN path

    """

    一种:

    results = graph.run(cypher_query, parameters={"name": "企业A"})

    二种:

    results = graph.run(cypher_query, name="企业A")

    print(f"type(results) = {type(results)}") # type(results) = <class 'py2neo.cypher.Cursor'>

    for result in results:
    '''
    path的值示例:
    Path(Node('Company', name='企业A', risk='否'), 工作单位(Node('Company', name='企业A', risk='否'), Node('Person', name='人A')), 认识(Node('Person', name='人A'), Node('Person', name='人B')), 董事(Node('Person', name='人B'), Node('Company', name='企业B', risk='是')))
    其中,type(result) = <class 'py2neo.cypher.Record'>
    '''
    path = result["path"]
    nodes = path.nodes # 获取路径中的所有节点,type(nodes)=tuple
    # 这个路径中没有重复的节点
    if not has_duplicates(nodes):
    print(path)

相关推荐
黑金IT2 天前
将Neo4j用于Python学习的创新方法
python·学习·neo4j
RINO喵2 天前
DAY10 Tensorflow 基本函数使用
人工智能·tensorflow·neo4j
落落落sss8 天前
封装neo4j的持久层和服务层
java·前端·网络·数据库·spring·elasticsearch·neo4j
缘友一世9 天前
Spring Data Neo4j
java·spring·neo4j
亲持红叶9 天前
神经网络常见激活函数 10-GELU函数
人工智能·神经网络·neo4j
我爱夜来香A9 天前
图数据库neo4j进阶(一):csv文件导入节点及关系
数据库·neo4j
缘友一世13 天前
Neo4j 5.26.x容器 APOC插件Generating Graphs无法正常使用解决方法/Neo4j 5.26.x容器安装APOC拓展库
neo4j
Gratitute_林腾13 天前
neo4j-neo4j网页版的基本操作
neo4j
Gratitute_林腾13 天前
neo4j-解决导入数据后出现:Database ‘xxxx‘ is unavailable. Run :sysinfo for more info.
数据库·neo4j
初学者↑13 天前
知识图谱可视化系统python+neo4j+vue3
python·知识图谱·neo4j