Skip to content

Neo4j v3 Unique IDs

subvertallchris edited this page Sep 21, 2014 · 11 revisions

id_property (Primary Key)

The database generates unique IDs and they are accessible from all nodes and relationships using the neo_id method. These keys are somewhat volatile and may be reused or change throughout a database's lifetime, so they are unsafe to use within an application.

To work around this, you can define which key should act as primary key on Neo4j::ActiveNode classes instead of using the internal Neo4j ids. By default, ActiveNode will generate a unique ID using SecureRandom::uuid. The instance methods id and uuid will both point to this.

You can define a global or per-model generation methods if you do not want to use the default. Additionally, you can change the property that will be aliased to the id method. This can be done through Neo4j::Config, Rails configuration, or models themselves. For example see config/application.rb or model

Unique IDs are not generated for relationships or ActiveRel models because their IDs should not be used. To query for a relationship, generate a match based from nodes. If you find yourself in situations where you need relationship IDs, you probably need to define a new ActiceNode class!

Defining your own ID

The on parameter tells which method is used to generate the unique id.

class Person
  include Neo4j::ActiveNode
  id_property :personal_id, on: :phone_and_name

  property :name
  property :phone

  def phone_and_name
    self.name + self.phone # strange example ...      
  end
end

This will always add a unique constraint and index, so you should not do either again within your model.

Adding IDs to Existing Data

A migration task is in place if you have old or imported data in need of IDs. See the (add_id_property migration)[https://github.com/neo4jrb/neo4j/wiki/Neo4j-v3-Migrations#add_id_property].

Clone this wiki locally