18.6. Creating unique nodes
In many use cases, a certain level of uniqueness is desired among entities. You could for instance imagine that only one user with a certain e-mail address may exist in a system. If multiple concurrent threads naively try to create the user, duplicates will be created. There are three main strategies for ensuring uniqueness, and they all work across High Availability and single-instance deployments.
By using a single thread, no two threads will even try to create a particular entity simultaneously. On High Availability, an external single-threaded client can perform the operations on the cluster.
Get or create
The preferred way to get or create a unique node is to use unique constraints and Cypher. See the section called “Get or create unique node using Cypher and unique constraints” for more information.
entity uniqueness can be guaranteed using a legacy index. Here the legacy index acts as the lock and will only lock the smallest part needed to guaranteed uniqueness across threads and transactions.
See the section called “Get or create unique node using a legacy index” for how to do this using the core Java API. When using the REST API, see Section 21.21, “Unique Indexing”.
While this is a working solution, please consider using the preferred the section called “Get or create” instead.
By using explicit, pessimistic locking, unique creation of entities can be achieved in a multi-threaded environment. It is most commonly done by locking on a single or a set of common nodes.
See the section called “Pessimistic locking for node creation” for how to do this using the core Java API.