简体   繁体   English

如何用py2neo声明唯一的约束

[英]How to declare a unique contraint with py2neo

I need ot enforce a unique contraint on my graph database. 我需要在图形数据库上强制使用唯一约束。 I found the following method: 我发现以下方法:

graph.schema.create_uniqueness_constraint("Website", "url") 

But it yields the following error: 但这会产生以下错误:

graph.schema.create_uniqueness_constraint("Website", "url")
AttributeError: 'Schema' object has no attribute 'create_uniqueness_constraint' 

My import and graph instentiation is: 我的导入和图形说明是:

from py2neo import neo4j,node 
graph = neo4j.GraphDatabaseService("http://localhost:7474/db/data/") 

What am I doing wrong, and how can I fix it? 我在做什么错,该如何解决?

Also, what's the simplest, cleanest way to add a uniqueness constraint with py2neo? 另外,用py2neo添加唯一性约束的最简单,最干净的方法是什么?

I'm getting confused with the abundance of methods, which sometime seem to fail without reason (couldn't find a comprehensive tutorial on py2neo), and I start to feel like I would be better off writing raw Cypher queries... 我对大量的方法感到困惑,有时似乎无缘无故会失败(找不到关于py2neo的全面教程),而且我开始觉得我最好写原始的Cypher查询...

It looks like you're on py2neo version 1.x and reading the docs for version 2.0. 看来您使用的是py2neo版本1.x,并正在阅读版本2.0的文档。 In py2neo 2.0: 在py2neo 2.0中:

from py2neo import Graph
graph = Graph()
graph.schema.create_uniqueness_constraint('Website', 'url')

In py2neo 1.x, I'm not sure there's a method for creating uniqueness constraints. 在py2neo 1.x中,我不确定是否存在创建唯一性约束的方法。 You'll probably have to do: 您可能需要做:

from py2neo import neo4j
graph = neo4j.GraphDatabaseService("http://localhost:7474/db/data/") 
neo4j.CypherQuery(graph, 'CREATE CONSTRAINT ON (w:Website) ASSERT w.url IS UNIQUE;').run()

EDIT: Updates per the questions in the comments below. 编辑:根据以下评论中的问题进行更新。 OP is on py2neo 2.0. OP在py2neo 2.0上。

Neo4j doesn't allow you to create a uniqueness constraint without specifying a label. Neo4j不允许您​​在不指定标签的情况下创建唯一性约束。 However, this will be easy to accomplish in py2neo. 但是,这在py2neo中很容易实现。 You can use graph.node_labels to get a list of all the labels in your graph, then you can iterate over those and create a uniqueness constraint on each label with the given property: 您可以使用graph.node_labels来获取图形中所有标签的列表,然后可以对其进行迭代,并使用给定属性在每个标签上创建唯一性约束:

from py2neo import Graph
graph = Graph()

labels = graph.node_labels

for label in labels:
    graph.schema.create_uniqueness_constraint(label, 'url')

Note that this will fail with a py2neo.error.ConstraintViolationException if the constraint already exists; 注意,如果约束已经存在,将失败,并出现py2neo.error.ConstraintViolationException否则,将失败。 you might want to wrap it in a try-except: 您可能需要将其包装在try-except中:

for label in labels:
    try:
        graph.schema.create_uniqueness_constraint(label, 'url')
    except:
        pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM