Neo4j图形数据库

Neo4j图形数据库

Neo4j是一个高性能的,NOSQL图形数据库,它将结构化数据存储在网络上而不是表中。它是一个嵌入式的、基于磁盘的、具备完全的事务特性的Java持久化引擎,但是它将结构化数据存储在网络(从数学角度叫做图)上而不是表中。Neo4j也可以被看作是一个高性能的图引擎,该引擎具有成熟数据库的所有特性。程序员工作在一个面向对象的、灵活的网络结构下而不是严格、静态的表中——但是他们可以享受到具备完全的事务特性、企业级的数据库的所有好处

展现形式:节点 – 联系 -> 节点 ,其中节点、联系都可以附带自己的属性

部署

1.本地安装jdk17,同时配置好java环境变量

2.https://neo4j.com/deployment-center/#community官网直接下载neo4j解压后配置bin目录环境变量

3.启动neo4j服务:neo4j.bat console

4.项目地址:http://localhost:7474/browser/

5.首次登录账号密码都是neo4j,修改后密码neo4j123456(第一次登录后自主随便修改)

常用cypher语言

Cypher是一种专门用于图数据库(如Neo4j)的查询语言,它提供了一种强大且易于使用的声明式查询方式,用于处理图形数据。可以理解为

#创建一个节点

create (n:Person {name: ‘我’, age:30})

#创建带关系的节点

create(p:Person{name:“我”, age:“30”})-[:包工程{金额:1000}]->(n:Person{name:“damn明”, age:“29”})

#删除节点

match (n:Person{name:“蛋明”}) delete n

#删除关系

match(p:Person{name:“我”, age:“30”})-[f:包工程]->(n:Person{name:“damn明”, age:“29”})
delete f

#找到节点,给节点加标签

match (t:Person) where id(t)=2 set t:好人 return t

#增加属性

match (a:好人) where id(a)=2 set a.战斗力=200 return a

#通过关系查找

match(p:Person) – [:包工程] -> (n:Person) return p,n

#删除所有关系和节点

MATCH (n)
OPTIONAL MATCH (n)-[r]-()
DELETE n, r

py2neo

#概述

Py2neo是一个客户端库和工具包,用于从Python应用程序和命令行使用Neo4j(Neo4j Graph Data Platform | Graph Database Management System)。该库同时支持 Bolt 和 HTTP,并提供高级 API、OGM、管理工具、交互式控制台、Pygments 的 Cypher 词法分析器以及许多其他功能

#安装

pip install py2neo -i https://pypi.tuna.tsinghua.edu.cn/simple/

#连接

from py2neo import Graph, Node, Relationship, NodeMatcher


#1.启动neo4j: neo4j.bat console

##连接neo4j数据库,输入地址、用户名、密码
##注意:这句代码适用老版的py2neo,即适用于2021.1之前的
# graph = Graph('http://localhost:7474', username='neo4j', password='neo4j123456')

##适用于新版,连接neo4j数据库
graph = Graph('http://localhost:7474', auth=("neo4j", "neo4j123456"), name='neo4j')
matcher = NodeMatcher(graph) #创建关系需要用到

#常用方法

#创建数据
def create_data():
    node_1 = Node('book', name='黄帝内经')  #label标签名book ,name属性名黄帝内经
    graph.create(node_1)#节点创建到数据库

    #创建结点Node
    node_1 = Node('book', name='黄帝内经')  #label标签名book ,name属性名黄帝内经
    node_2 = Node('book', name='素问')
    node_3 = Node('book', name='灵枢')
    node_4 = Node('book', name='内经')
    graph.create(node_1)#节点创建到数据库
    graph.create(node_2)
    graph.create(node_3)
    graph.create(node_4)

    #创建联系Relationship
    node_1_include_node_2 = Relationship(node_1, '包括', node_2)
    node_1_include_node_3 = Relationship(node_1, '包括', node_3)
    node_1_elsename_node_4 = Relationship(node_1, '别称', node_4)
    graph.create(node_1_include_node_2)
    graph.create(node_1_include_node_3)
    graph.create(node_1_elsename_node_4)




#清除所有节点、联系
def clear_all():
    graph.run('''MATCH (n) 
                 OPTIONAL MATCH (n)-[r]-() 
                 DELETE n, r''')


#删除指定节点,只删除一个没有关系节点
def delete_no_relationship_node():
    node=matcher.match('book').where(name='黄帝内经').first() #先匹配,叫黄帝内经的第一个结点
    graph.delete(node)


#删除指定关系和节点
def delete_relationship_node():
    b = list(matcher.match('book').where(name='黄帝内经'))[0]
    graph.delete(b)


#查找节点
def select_data():
    # 转化为numpy数据
    b = graph.run('match(n:book) return *').to_ndarray()
    print(b)

    # 以字典列表的形式返回查询的结果数据
    b = graph.run('match(n:book) return *').data()
    print(b)

案例demo

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

#连接neo4j数据库
class Handle_Graph:
    graph = Graph('http://localhost:7474', auth=("neo4j", "neo4j123456"), name='neo4j')
    matcher = NodeMatcher(graph)  # 创建关系需要用到

    def create_category_node(self):
        node_1 = Node('category', name='板材类')
        self.graph.create(node_1)#节点创建到数据库
        return node_1


    #创建品类、品名节点并创建节点联系“包含”
    def create_pm_node(self):
        father_node = self.create_category_node() #创建品类节点
        child_node_names = read_excel()

        for name in child_node_names:
            child_node = Node('pm', name=name)
            self.graph.create(child_node)

            father_node_include_child_node = Relationship(father_node, '包含', child_node)
            self.graph.create(father_node_include_child_node)

    #创建材质节点、关联pm -> material联系“材质有”
    def create_material(self):
        # 遍历pm、材质关系
        infos_list = read_excel_material()
        for info in infos_list:
            Cname = info[0]
            Mname = info[1]

            print(Cname, Mname)

            #创建材质节点
            material_node = Node('material', name=Mname)
            self.graph.create(material_node)

            #获取其关联pm节点
            pm_node = self.matcher.match('pm').where(name=Cname).first()
            #创建pm-material 关联
            pm_node_material_node = Relationship(pm_node, '材料有', material_node)
            self.graph.create(pm_node_material_node)

            print('--------------------------------------------------------------------')

    # 清除所有节点、联系
    def clear_all(self):
        self.graph.run('''MATCH (n) 
                     OPTIONAL MATCH (n)-[r]-() 
                     DELETE n, r''')

    # 数据查询,返回dict数据
    def query_graph(self):
        query = "MATCH (n:pm) RETURN n"
        data = self.graph.run(query).data()

        node_ids = []
        new_nodes = []
        new_links = []

        for a in data:
            for tk, tv in a.items():
                nodes = tv.nodes
                relations = tv.relationships
                for n in nodes:
                    if n.identity in node_ids:
                        continue
                    obj = {}
                    obj["id"] = n.identity
                    obj["label"] = []
                    if n.labels is not None:
                        for la in n.labels:
                            obj["label"].append(la)
                    for k, v in n.items():
                        obj[k] = v
                    node_ids.append(n.identity)
                    new_nodes.append(obj)
                for r in relations:
                    if r.identity in node_ids:
                        continue
                    li = {}
                    li["id"] = r.identity
                    if r.types() is not None:
                        li["label"] = []
                        for la in r.types():
                            li["label"].append(la)
                    li["source"] = r.start_node.identity
                    li["target"] = r.end_node.identity
                    for k, v in r.items():
                        li[k] = v
                    node_ids.append(r.identity)
                    new_links.append(li)
        result = {}
        result["nodes"] = new_nodes
        result["links"] = new_links
        return result


# def select_node():
#     # 使用Cypher查询获取所有pm节点
#     query = "MATCH (n:pm) RETURN n"
#     nodes = graph.run(query).data()
#
#     # 打印所有节点
#     for node in nodes:
#         print(node['name'])


#读取excel,返回所有pm
def read_excel():
    df = pd.read_excel('包含.xlsx')
    column_data = df['pm']
    return list(column_data)

def read_excel_material():
    final_list = []
    df = pd.read_excel('材质有.xlsx')
    for index, row in df.iterrows():
        final_list.append([row['TypeName'], row['MName']])
    return final_list



def main():
    graph = Handle_Graph()
    graph.clear_all()


if __name__ == '__main__':
    graph = Handle_Graph()

    #清除
    graph.clear_all()

    #2级节点创建
    graph.create_pm_node()

    #遍历2级节点
    # result = graph.query_graph()['nodes']
    # for i in result:
    #     print(i)

    #3级节点创建
    graph.create_material()



    # a = query_graph()['nodes']
    # print(a)

    # graph = handle_graph()
    # a = graph.query_graph()['nodes']
    # print(a)

    #遍历pm、材质关系
    # infos_list = read_excel_material()
    # for info in infos_list:
    #     print(info)

    # graph = Handle_Graph()
    # graph.create_material()


版权声明:本文为博主作者:然后呢、原创文章,版权归属原作者,如果侵权,请联系我们删除!

原文链接:https://blog.csdn.net/weixin_50981870/article/details/136915166

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2024年4月16日
下一篇 2024年4月16日

相关推荐