Neo4j 简明教程

Neo4j - Create Unique Constraint

在 Neo4j 数据库中,CQL CREATE 命令始终会创建新节点或关系,这意味着即使您使用相同的值,它也会插入新行。根据我们的应用程序要求的一些节点或关系,我们必须避免这种重复。为此,我们应使用一些数据库约束在节点或关系的一个或多个属性上创建规则。

In Neo4j database, CQL CREATE command always creates a new node or relationship which means even though you use the same values, it inserts a new row. As per our application requirements for some nodes or relationships, we have to avoid this duplication. For this, we should use some database constraints to create a rule on one or more properties of a node or relationship.

与 SQL 类似,Neo4j 数据库还支持节点或关系属性上的 UNIQUE(唯一)约束。UNIQUE 约束用于避免重复记录并强制执行数据完整性规则。

Like SQL, Neo4j database also supports UNIQUE constraint on node or relationship properties. UNIQUE constraint is used to avoid duplicate records and to enforce data integrity rule.

Create UNIQUE Constraint

Neo4j CQL 提供“CREATE CONSTRAINT”命令,用于针对节点或关系属性创建唯一约束。

Neo4j CQL provides "CREATE CONSTRAINT" command to create unique constraints on node or relationship properties.

Syntax

以下是 Neo4j 中创建 UNIQUE 约束的语法。

Following is the syntax to create a UNIQUE constraint in Neo4j.

MATCH (root {name: "Dhawan"})
CREATE UNIQUE (root)-[:LOVES]-(someone)
RETURN someone

Example

在继续示例之前,如以下所示创建 4 个节点。

Before proceeding with the example, create 4 nodes as shown below.

CREATE(Dhawan:player{id:001, name: "shikar Dhawan", YOB: 1995, POB: "Delhi"})
CREATE(Jonathan:player {id:002, name: "Jonathan Trott", YOB: 1981, POB: "CapeTown"})
CREATE(Sangakkara:player {id:003, name: "Kumar Sangakkara", YOB: 1977, POB: "Matale"})
CREATE(Rohit:player {id:004, name: "Rohit Sharma", YOB: 1987, POB: "Nagpur"})
CREATE(Virat:player {id:005, name: "Virat Kohli", YOB: 1988, POB: "Delhi"})

以下是使用 Neo4j 根据 id 属性创建 UNIQUE 约束的 Cypher 查询示例。

Following is a sample Cypher Query to create a UNIQUE constraint on the property id using Neo4j.

CREATE CONSTRAINT ON (n:player) ASSERT n.id IS UNIQUE

执行上述查询,执行以下步骤:

To execute the above query, carry out the following steps −

Step 1 - 打开 Neo4j Desktop App 并启动 Neo4j Server。使用 URL http://localhost:7474/ 打开 Neo4j 的内置浏览器应用,如下面的屏幕截图所示。

Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.

browser app

Step 2 - 在美元提示符中复制并粘贴所需的查询,并按播放按钮(执行查询)突出显示在下面的屏幕截图中。

Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.

create unique

Result

执行后,您将获得以下结果。

On executing, you will get the following result.

added constraint

Verification

现在,尝试添加具有冗余 id 值的另一个节点。在这里,我们尝试创建一个 id 为 002 的节点。

Now, try to add another node with a redundant id value. Here, we are trying to create a node with id 002.

CREATE (Jadeja:player {id:002, name: "Ravindra Jadeja", YOB: 1988, POB: "NavagamGhed"})

如果您执行此查询,您将获得以下屏幕截图中显示的错误消息。

If you execute this query, you will get an error message as shown in the following screenshot.

node label play