neo4j 图数据库 py2neo 操作 示例代码

文章目录

    • 摘要
    • 前置
    • NodeMatcher & RelationshipMatcher
      • 创建节点
      • 查询获取节点
      • 节点有则查询,无则创建
      • 创建关系
      • 查询关系
      • 关系有则查询,无则创建
    • Cypher语句
      • 创建节点

摘要

利用py2neo包,实现把excel表里面的数据,插入到neo4j 图数据库中;

  • 创建新(节点或关系)到neo4j图数据库中;
  • 能够获取neo4j 中已有的(节点或关系),不再创建新(节点或关系);

进阶, 敬请期待,案例

前置

安装py2neo: pip install py2neo
安装neo4j软件,请自行安装

NodeMatcher & RelationshipMatcher

代码由 Jupyter 编写,建议使用vscode

from py2neo import Graph, Node, NodeMatcher, RelationshipMatcher
import pandas as pd

# 连接到Neo4j数据库  
graph = Graph("bolt://localhost:7687", auth=("neo4j", "你设置的密码")) 

node_matcher = NodeMatcher(graph)
relationship_matcher = RelationshipMatcher(graph)

neo4j 图数据库 py2neo 操作 示例代码_第1张图片

TODO: 设置neo4j 远程连接

创建节点

node = Node("Person", name="Alice", age=18)
graph.create(node)

neo4j 图数据库 py2neo 操作 示例代码_第2张图片

查询获取节点

# 拿到匹配到的第一个节点
node_matcher.match('Person', name='Alice').first()

# 拿到可匹配到的所有
node_matcher.match('Person', name='Alice').all()

节点有则查询,无则创建

def get_node(class_, **kwargs):
    if node := node_matcher.match(class_, **kwargs):
        # 节点存在,则获取
        return node.first()
    else:
        # 节点不存在,则创建
        node = Node(class_, **kwargs)
        graph.create(node)
        return node

neo4j 图数据库 py2neo 操作 示例代码_第3张图片

创建关系

Alice - Friend -> Bob

node1 = get_node('Person', name='Alice', age=21)
node2 = get_node('Person', name='Bob', age=20)

graph.create(
                Relationship(node1, 'Friend', node2)
            )

neo4j 图数据库 py2neo 操作 示例代码_第4张图片

查询关系

查询 node1 和 node2 之间是否有 Friend 关系

node1 = get_node('Person', name='Alice', age=21)
node2 = get_node('Person', name='Bob', age=20)

relationship_matcher.match(
        [node1, node2],
        r_type='Friend'
    ).first()

关系有则查询,无则创建

def get_relation(node1, node2, r_type):
    if r :=  relationship_matcher.match(
                [node1, node2],
                r_type=r_type
            ):
        return r.first()
    else:
        r = Relationship(node1, r_type, node2)
        graph.create(r)
        return r
# 查询已有关系
get_relation(node1, node2, 'Friend')
# 创建新关系
get_relation(node1, node2, 'Classmate')

neo4j 图数据库 py2neo 操作 示例代码_第5张图片

Cypher语句

虽然 在 NodeMatcher & RelationshipMatcher 介绍的接口已经能够满足大部分情况的使用,本文仍想提供一种使用cypher语句的插入数据到neo4j图数据库的思路。

创建节点

graph.run(
    "create (n:Person {name:'js'}) return n"
)
graph.run(
    "MERGE (n:Person {name: $name}) \
            ON CREATE SET n.created_at = timestamp() \
            return n",
    name='Cyder'
)

你可能感兴趣的:(知识图谱,neo4j,python,自然语言处理)