neo4j的python运用,py2neo整理基础功能,class实现减少代码重复 2022.4.10更新

根据py2neo整理基础功能,class实现减少代码重复

注意!使用本Neo4j_Helper前,请确保您已经安装了py2neo模块和re模块!!!!!!!

功能一览:
1.连接服务器

2.创建索引
3.创建一个或多个node节点, 返回创建的node的《id》
4.创建单个关系
5.创建关系,并添加一或多条关系数据

6.拿到单个node的信息未解码版
7.拿到单个node的信息字典版
8.拿到一个node的所有关系,并返回一个list

9.更改一条node节点数据,也可以用来添加多个节点数据

10.删除单个的node以及其关系
11.删除一个node的所有关系
12.删除一个node的一个关系
13.删除单个的node以及其关系
14.根据id删除节点(注意,只能删除没有关系的节点)
15.删除当前库中所有的数据,跑路需谨慎,跑路有风险
16.删除相同label的所有node
17.删除相同label的所有关系

18.执行任意cql代码

测试代码区域
4种功能对以亿为基数的数据创建节点添加关系时,根据根id来进行搜索,防止出现没有索引搜索时间过长的问题

废话不说,直接上代码

from py2neo import *
import re
class Neo4j_Helper(object):

    def __init__(self, url, user_name, user_passwd):
        self.url = url
        self.user_name = user_name
        self.user_passwd = user_passwd
        self.graph = None

    def connect_neo4j_service(self):
        self.graph = Graph(self.url, auth=(self.user_name, self.user_passwd))

    def create_index(self, index_label, index_property):
        cql = f"create index for (n:{index_label}) on (n.{index_property})"
        self.graph.run(cql)

    def create_node(self, node_label, node_dict):
        node = Node(node_label, **node_dict)
        self.graph.create(node)
        node1 = str(node)
        node_id_list = []
        list1 = re.findall(r'_.*?:', node1)
        for i in list1:
            node_id_list.append(i[1:-1])
        return node_id_list

    def create_one_relationship(self, f1_label, f1_detail, f2_label, f2_detail, relation_name):
        f1_node = self.get_one_node_position(f1_label, f1_detail)
        f2_node = self.get_one_node_position(f2_label, f2_detail)
        rel = Relationship(f2_node, relation_name, f1_node)
        self.graph.create(rel)

    def add_relationship_info(self, f1_label, f1_detail, f2_label, f2_detail, relation_name, info):
        node_point1 = self.get_one_node_position(f1_label, f1_detail)
        node_point2 = self.get_one_node_position(f2_label, f2_detail)
        node1_vs_node2 = Relationship(node_point1, relation_name, node_point2, **info)
        self.graph.merge(node1_vs_node2)

    def get_one_node_position(self, node_label, node_dict):
        node_data = NodeMatcher(self.graph)
        node_point = node_data.match(node_label, **node_dict).first()
        return node_point

    def get_one_node_dict(self, node_label, node_dict):
        f1_node = self.get_one_node_position(node_label, node_dict)
        return dict(f1_node)

    def get_one_node_relationship(self, node_label, node_dict):
        all_relation = RelationshipMatcher(self.graph)
        node_point = self.get_one_node_position(node_label, node_dict)
        rel = list(all_relation.match((node_point,)))
        return rel

    def add_one_node_info(self, node_label, node_name, info):
        node_point = self.get_one_node_position(node_label, node_name)
        self.graph.push(node_point.update(info))

    def change_one_node_info(self, node_label, node_name, info_dict):
        node_point = self.get_one_node_position(node_label, node_name)
        for i, j in info_dict.items():
            node_point[i] = j
        self.graph.push(node_point)

    def del_all_relationship_of_a_node(self, node_label, node_name):
        key = list(node_name.keys())[0]
        value = list(node_name.values())[0]
        value = "'" + value + "'"
        self.graph.run("MATCH s=((n:" +node_label+ '{'+ key +':'+ value+'}' +")-[ss]-()) delete ss")

    def del_one_relationship_of_a_node(self, node_label, node_name, relation_name):
        key = list(node_name.keys())[0]
        value = list(node_name.values())[0]
        value = "'" + value + "'"
        self.graph.run("MATCH s=((n:" + node_label + '{' + key + ':' + value + '}' + ")-[ss:"+relation_name+"]-()) delete ss")

    def del_one_node(self, node_label, node_name):
        key = list(node_name.keys())[0]
        value = list(node_name.values())[0]
        value = "'" + value + "'"
        self.graph.run('match (n:'+node_label+'{'+ key +':'+ value+'}'+') detach delete n')

    def del_one_node_by_id(self, id_num):
        self.graph.run(f'MATCH (n) WHERE id(n) = {id_num} DELETE n')

    def del_all(self):
        self.graph.delete_all()

    def del_all_node_of_same_label(self, node_label):
        cql = f"match (n:{node_label}) delete n"
        self.graph.run(cql)

    def del_all_relationship_of_same_label(self, relation_label):
        cql = f"MATCH (n)-[k:{relation_label}]->(f) Delete k"
        self.graph.run(cql)

    def run_any_cql_code(self, sentence):
        self.graph.run(sentence)

    def create_add_relationship_info(self, f1_label, f1_detail, f2_label, f2_detail, relation_name, info=None):
        key1 = list(f1_detail.keys())[0]
        value1 = list(f1_detail.values())[0]
        value1 = "'" + value1 + "'"
        key2 = list(f2_detail.keys())[0]
        value2 = list(f2_detail.values())[0]
        value2 = "'" + value2 + "'"
        cql_match_string = "MATCH (a:"+f1_label+"{"+key1+": "+value1+"}), (b:"+f2_label+"{"+key2+": "+value2+"}) "
        if info is None:
            cql_create_string = "CREATE (a)-[r:"+relation_name+"]->(b)"
        else:
            info_string = ', '.join(f'{i}: "{j}"' for i, j in info.items())
            info_string = "{" + info_string + "}"
            cql_create_string = "CREATE (a)-[r:"+relation_name+info_string+"]->(b)"
        cql_string = cql_match_string + cql_create_string
        self.graph.run(cql_string)

    def create_relationship_by_property_and_id(self, f1_label, f1_detail, f2_id, relation_name, info=None):
        key1 = list(f1_detail.keys())[0]
        value1 = list(f1_detail.values())[0]
        value1 = "'" + value1 + "'"
        if info is None:
            cql_string = "match (a:" + f1_label + "),(b) where a." + key1 + "=" + value1 + " and id(b)=" + str(
                f2_id) + " CREATE (a)-[r:" + relation_name + "]->(b)"
        else:
            info_string = ', '.join(f'{i}: "{j}"' for i, j in info.items())
            info_string = "{" + info_string + "}"
            cql_string = "match (a:"+f1_label+"),(b) where a."+key1+"="+value1+" and id(b)="+str(f2_id)+" CREATE (a)-[r:"+relation_name+info_string+"]->(b)"
        self.graph.run(cql_string)

    def create_relationship_by_id_and_property(self, f1_id, f2_label, f2_detail, relation_name, info=None):
        key2 = list(f2_detail.keys())[0]
        value2 = list(f2_detail.values())[0]
        value2 = "'" + value2 + "'"
        if info is None:
            cql_string = "match (a),(b:" + f2_label + ") where id(a)=" + str(
                f1_id) + " and b." + key2 + "=" + value2 + " CREATE (a)-[r:" + relation_name + "]->(b)"
        else:
            info_string = ', '.join(f'{i}: "{j}"' for i, j in info.items())
            info_string = "{" + info_string + "}"
            cql_string = "match (a),(b:"+f2_label+") where id(a)="+str(f1_id)+" and b."+key2+"="+value2+" CREATE (a)-[r:"+relation_name+info_string+"]->(b)"
        self.graph.run(cql_string)

    def create_relationship_by_id_and_id(self, f1_id, f2_id, relation_name, info=None):
        if info is None:
            cql_string = "match (a),(b) where id(a)=" + str(f1_id) + " and id(b)=" + str(
                f2_id) + " CREATE (a)-[r:" + relation_name + "]->(b)"
        else:
            info_string = ', '.join(f'{i}: "{j}"' for i, j in info.items())
            info_string = "{" + info_string + "}"
            cql_string = "match (a),(b) where id(a)=" + str(f1_id) + " and id(b)=" + str(f2_id) + " CREATE (a)-[r:" + relation_name + info_string + "]->(b)"
        self.graph.run(cql_string)

本人比较萌新,有不对的地方或者bug还请大佬们指导
如果有什么需要添加的功能也可以留言,我能力范围内的都会持续更新进去
有不理解的地方可以评论,我会尽快回复~

更新:

2022/1/5
新增内容:
1.创建关系,并添加一或多条关系数据
2.删除一个node的一个关系
3.删除一个node的所有关系

2022/1/7
新增内容:
1.删除相同label的所有节点
2.删除相同label的所有关系
3.创建索引

2022/4/10
新增内容:
1.功能测试区域,根据4种不同需求,用property或节点根id创建关系,防止节点无索引搜索时间过长

功能修正:
原:
创建一个或多个node节点
新:
创建一个或多个node节点, 同时返回创建的node的《id》

Original: https://blog.csdn.net/SRestia/article/details/122302253
Author: SRestia
Title: neo4j的python运用,py2neo整理基础功能,class实现减少代码重复 2022.4.10更新

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/555234/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球