5

Here is my Neo4j Active Node

class User
include Neo4j::ActiveNode
  has_many :out, :following, type: :following, model_class: 'User'
end

john = User.find(:name => "John")
tom = User.find(:name => "Tom")

# create following relationship john --> tom
john.following << tom
# check count
john.following.count 
#=> 1

# again create the relationship 
john.following << tom
# again check count
john.following.count
#=> 2

I want to create unique relationship.

To avoid duplication we have to use create unique in creating relation cypher query.

Example:

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

refer: http://neo4j.com/docs/stable/query-create-unique.html

How can i do this in Neo4j.rb with Rails... ?

Thanks in advance..

Community
  • 1
  • 1
Raj Adroit
  • 3,828
  • 5
  • 31
  • 44

2 Answers2

6

Just as an update, you can now do the following:

For simple relationships, use unique:true:

class User
  include Neo4j::ActiveNode
  has_many :out, :following, type: :following, model_class: 'User', unique: true
end

For declared relationships, use creates_unique:

class Following
  include Neo4j::ActiveRel

  creates_unique

  from_class User
  to_class   User
end
mrstif
  • 2,736
  • 2
  • 27
  • 28
5

This is something we have an issue open for:

https://github.com/neo4jrb/neo4j/issues/473

For now I would suggest creating a method like this on the User model:

def create_unique_follower(other)
    Neo4j::Query.match(user: {User: {neo_id: self.neo_id}})
                .match(other: {User: {neo_id: other.neo_id}})
                .create_unique('user-[:following]->other').exec
end

EDIT: See mrstif's answer for an update

Brian Underwood
  • 10,746
  • 1
  • 22
  • 34
  • 1
    Just submitted the PR to add this to the gem. Check out https://github.com/neo4jrb/neo4j/pull/660. I'll merge it in sometime in the next few hours unless Brian points out mistakes. ;-) – subvertallchris Jan 07 '15 at 16:22