Neo4j如何删除所有约束。

27

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

我知道我可以删除特定的约束条件。

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

然而在测试结束后,我想要清除所有约束作为拆卸的一部分。文档中找不到任何信息,但可以尝试这样:

DROP CONSTRAINT *

更新:我的测试环境。

正在编写一个基于 Promise 的 Node.js Cypher 客户端。我想测试在应用程序代码中定义唯一索引。


1
在测试期间,您想要完整的设置和拆卸,对吗?有一些方法可能会有所帮助。您更喜欢:使用具有删除整个数据库功能的完整服务器 DROP GRAPH;可编写脚本的轻量级服务器,可以在任何目录下托管图形 neo4jlite --serve ./test-graph.db;还是其他什么?您能描述一下您特定的测试设置吗? - akollegger
@AndreasKollegger 没错!我尝试了 DROP GRAPH 但是出现了语法错误。这个命令在哪个 Neo4J / CQL 版本中被支持? - AJcodez
1
抱歉,我应该澄清一下,这两种方法都是理论上的,但也是现实可能性。在事情要做和时间去做之间保持平衡的情况下,我试图了解我们应该在哪些方面投入更多的努力。 - akollegger
@akollegger DROP GRAPH 对我来说就可以了!现在我在测试运行之间清除数据库。https://github.com/aj0strow/neo4j/blob/master/lib/neo4j.js#L57 - AJcodez
3
好的,我会为您进行翻译。我从中提取出了一个功能请求,实际上是两个请求。请将将来的评论定向到 https://trello.com/c/OuGbPLt4 。 - akollegger
8个回答

43

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


不错 - 真是太棒了,而且很快! - anarche
这个库很不错,他们什么时候把这个东西加入核心啊 ;) - meawoppl

7
这是我在Python中处理此事的方法:
    s = connection.get_session()

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

感觉有些不舒服,我认为约束应该得到更好的支持。


不得不修改为“DROP CONSTRAINT”。谢谢。 - 0_0

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

1
呸,为什么这里需要混合使用HTTP和Session? - meawoppl

2

我知道楼主在询问如何通过编程方式进行测试,而这个答案并不能完全满足这种情况。但如果你只是想快速删除所有的约束条件而不用编写程序,你可以使用以下查询生成一个DROP CONSTRAINT命令列表:

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

然后,您可以快速从输出中删除管道,并将其粘贴回cypher-shell中以全部删除它们。如果您经常需要执行此操作,则可以轻松地使用shell脚本编写脚本。

2
如果你使用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`);`。 - Telmo Trooper

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

0
这是一个针对使用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

0

首先,您必须创建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']}")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接