【问题标题】:neo4j how to drop all constraintsneo4j 如何删除所有约束
【发布时间】:2014-04-16 22:24:01
【问题描述】:

是否有一个密码命令可以删除所有约束?

我知道我可以放弃特定的约束。

DROP CONSTRAINT ON (book:Book) ASSERT book.isbn IS UNIQUE

但是,我想在测试后作为拆卸的一部分清除 所有 约束。在文档中找不到任何内容,但类似:

DROP CONSTRAINT *

更新:我的测试设置。

编写一个基于 Promise 的小型 nodejs 密码客户端。我想测试在应用程序代码中定义唯一索引。

【问题讨论】:

  • 在测试期间,您需要完整的设置和拆卸,对吗?这里有一些方法可能会有所帮助。您是否更喜欢:使用能够通过DROP GRAPH 删除整个数据库的完整服务器;一个可编写脚本的轻量级服务器,可以在您指向neo4jlite --serve ./test-graph.db 的任何目录中托管图表;别的东西?您能描述一下您的特定测试设置吗?
  • @AndreasKollegger 完全正确!我试过DROP GRAPH,但出现语法错误。支持哪个 Neo4J/CQL 版本?
  • 抱歉,我应该澄清一下这两种方法都是理论上的,虽然是现实的可能性。由于通常在待办事项和完成时间之间取得平衡,我正试图了解我们应该在哪些方面付出更多努力。
  • @akollegger DROP GRAPH 会为我做的!现在我在测试运行之间清除数据库github.com/aj0strow/neo4j/blob/master/lib/neo4j.js#L57
  • 好的,我已经从中提取了一个功能请求。嗯,两个。请将未来的 cmets 转至trello.com/c/OuGbPLt4

标签: neo4j cypher


【解决方案1】:

我知道 OP 要求在测试中以编程方式执行此操作,而这个答案并不能真正满足这种情况。但是,如果您只是想在不编写程序的情况下快速删除所有约束,您可以使用以下查询生成DROP CONSTRAINT 命令列表:

CALL db.constraints() YIELD name
RETURN "DROP CONSTRAINT " + name + ";";

然后您可以快速从输出中删除管道并将其粘贴回cypher-shell 以将它们全部删除。如果这是您经常想做的事情,那么使用 shell 脚本编写脚本可能会很容易。

【讨论】:

    【解决方案2】:

    首先,你必须为连接创建 Neo4j 类:

    class Neo4jConnection:
        
        def __init__(self, uri, user, pwd):
            
            self.__uri = uri
            self.__user = user
            self.__pwd = pwd
            self.__driver = None
            
            try:
                self.__driver = GraphDatabase.driver(self.__uri, auth=(self.__user, self.__pwd))
            except Exception as e:
                print("Failed to create the driver:", e)
            
        def close(self):
            
            if self.__driver is not None:
                self.__driver.close()
            
        def query(self, query, parameters=None, db=None):
            
            assert self.__driver is not None, "Driver not initialized!"
            session = None
            response = None
            
            try: 
                session = self.__driver.session(database=db) if db is not None else self.__driver.session() 
                response = list(session.run(query, parameters))
            except Exception as e:
                print("Query failed:", e)
            finally: 
                if session is not None:
                    session.close()
            return response
    

    然后创建一个连接:

    uri = 'uri'
    pwd = 'pwd'
    user= 'user'
    
    conn = Neo4jConnection(uri=uri, user=user , pwd=pwd)
    

    并且,您可以运行以下命令来删除所有约束:

    ## drop all constraints
    const = conn.query("CALL db.constraints")
    
    for c in const:
        conn.query(f"DROP CONSTRAINT {c['name']}")
    

    【讨论】:

      【解决方案3】:

      如果您使用 node/javascript,您可以执行以下操作:

      const { records } = await cypher(`CALL db.constraints`)
      await Promise.all(records.map(record => {
        cypher(`DROP CONSTRAINT ${record.get('name')}`);
      }));
      

      【讨论】:

      • 按名称删除约束更安全,例如DROP CONSTRAINT ${record.get('name')};,因为如果属性名称需要使用“`”按描述删除将不起作用。将此约束添加到您的数据库并检查您的方法是否有效:CREATE CONSTRAINT ON (p:Person) ASSERT exists(p.`full name`);.
      【解决方案4】:

      这里是使用 neo4jrb gem 的助手:

      class MigrationHeper
        include Neo4j::Migrations::Helpers
        def drop_all
          execute("match (n) detach delete n;")
          execute("call db.constraints").each do |constraint|
            execute "drop " + constraint[:description]
          end
        end
      end
      

      【讨论】:

        【解决方案5】:

        这是我在 Python 中的操作方式:

            s = connection.get_session()
        
            # Drop constraints / indices
            for constraint in s.run("CALL db.constraints"):
                s.run("DROP " + constraint[0])
        

        感觉有点恶心,我觉得约束应该是更好的支持。

        【讨论】:

          【解决方案6】:

          注意使用APOC,您可以通过CALL apoc.schema.assert({}, {}) 删除所有索引和约束。

          【讨论】:

          • 很好 - 这太棒了,而且速度很快!
          • 不错的图书馆,他们什么时候把这些东西放到他们的核心;)
          【解决方案7】:

          您可以通过对http://localhost:7474/db/data/schema/constraint/http://localhost:7474/db/data/schema/index 的GET 请求获取所有索引和约束的列表。以下是我在 Ruby 中的做法,也许它会让您了解如何在 Node 中做同样的事情。

          c.after(:all) do
            conn = Faraday.new(url: "http://localhost:7474")
            response = conn.get('/db/data/schema/constraint/')
            constraints = JSON.parse(response.body)
            constraints.each do |constraint|
              Neo4j::Session.query("DROP CONSTRAINT ON (label:`#{constraint['label']}`) ASSERT label.#{constraint['property_keys'].first} IS UNIQUE")
            end 
          
            response = conn.get('/db/data/schema/index/')
            indexes = JSON.parse(response.body)
            indexes.each do |index|
              Neo4j::Session.query("DROP INDEX ON :`#{index['label']}`(#{index['property_keys'].first})")
            end
          end
          

          【讨论】:

          • 糟糕,为什么这里需要混合使用 http 和会话?
          【解决方案8】:

          删除约束的唯一方法是在每个约束级别上执行此操作。您可以使用例如:schema 在 Neo4j 浏览器中获取所有约束的列表。我只想为此写一个简短的脚本。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-07-03
            • 2022-01-26
            • 2012-01-28
            • 1970-01-01
            相关资源
            最近更新 更多