使用py2neo查询/增加/删除neo4j索引

  • 为避免在使用一个新建的graph_db时忘记创建索引,故在neo4j数据导入程序运行初进行索引的检查。
  • 实现方式为在配置文件中配置需要使用的索引信息, 和neo4j中已存在的索引进行比较, 根据比较结果进行索引的增加, 删除等
  • 配置文件config.py
    class CONFIG:
        class neo4j:
            host = "127.0.0.1"
            user = "neo4j"
            password = ""
            # index config
            # label为key, 单/组合索引中的property_key组成元组, 索引组织为列表作为value;
            index = dict(
                    student = [("student_id",), ("name", "age")]    
                )
    
  • neo4j index 初始化文件
    from py2noe import Graph
    from config import CONFIG
    
    def neo4j_index_init():
        """ 初始化neo4j索引"""
        neo4j_graph = Graph(
                host = CONFIG.neo4j.host,
                user= CONFIG.neo4j.user,
                password = CONFIG.neo4j.password
            )
        for label, property_keys in CONFIG.neo4j.index.items():
            index_in_neo4j = neo4j_graph.schema.get_indexes(label)
            # 要求配置中的索引在neo4j中一定存在(neo4j中索引数量可能比配置中索引数量要多)
            # 创建配置中有,但是neo4j中不存在的索引
            for index_in_config in property_keys:
                if index_in_config not in index_in_neo4j:
                    neo4j_graph.schema.create_index(label, *index_in_config)
    
            """
            # 要求neo4j总索引和配置中索引完全一致的情况
            # 比对索引下属性是否相同
            if set(index_in_neo4j) != set(property_keys):
                # 删除neo4j中索引,并按配置进行重建索引
                for already_index in index_in_neo4j:
                    neo4j_graph.schema.drop_index(label, *already_index)
                for index_in_config in property_keys:
                    neo4j_graph.schema.create_index(label, *index_in_config)
            """
    
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值