Created
June 11, 2013 20:09
-
-
Save saterus/5760177 to your computer and use it in GitHub Desktop.
Neo4j.rb Unique Relationships
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Novel < Neo4j::Rails::Model | |
property :title, type: String, index: :exact | |
has_n(:authored_by).to(Author) | |
end | |
class Author < Neo4j::Rails::Model | |
property :name, type: String, index: :exact | |
has_n(:authored).from(Novel.authored_by) | |
end | |
dune = Novel.find(title: 'Dune') | |
frank = Author.find(name: 'Frank Herbert') | |
# create basic relationship (this works great) | |
dune.authored_by | |
#=> Node dir: outgoing, Storage 9456 node: 14 rel_type: Novel#authored_by outgoing 0/ incoming 0/ | |
dune.authored_by.count | |
#=> 0 | |
dune.authored_by << frank | |
#=> Node dir: outgoing, Storage 9456 node: 14 rel_type: Novel#authored_by outgoing 1/ incoming 0/ | |
dune.save | |
#=> true | |
dune.authored_by.count | |
#=> 1 | |
# create it again... (works great....) | |
dune.authored_by << frank | |
#=> Node dir: outgoing, Storage 9462 node: 14 rel_type: Novel#authored_by outgoing 1/ incoming 0/ | |
dune.save | |
#=> true | |
dune.authored_by.count | |
#=> 2 | |
# but that's not really right. an author can only write a novel once. | |
# i really wanted unique relationships between two nodes. | |
# i know cypher can do this with CREATE UNIQUE. | |
# clean this up | |
dune.authored_by_rels.destroy_all | |
#=> nil | |
# i had to do some digging through the docs, and then the specs, but | |
# i found something that looked promising. `create_unique_path`. | |
Neo4j::Cypher.query(dune, frank){|novel, author| novel.create_unique_path(author){|n,a| n > rel(:authored_by).as(:link) > a }; ret(:link) } | |
#=> "START v1=node(14),v2=node(15) WITH v1,v2 CREATE UNIQUE (v1)-[link:`authored_by`]->(v2) RETURN link" | |
# oh hey, that looks great. let's execute this query! | |
Neo4j.query(dune, frank){|novel, author| novel.create_unique_path(author){|n,a| n > rel(:authored_by).as(:link) > a }; ret(:link) } | |
#=> NoMethodError: undefined method `createRelationshipTo' for #<Novel:0x19c50523> | |
# oh no! what happened? everything was going great. the raw query looked good. | |
# *shutdown rails console* | |
# *fireup Neo4j Admin web console* | |
# *execute that query by hand* | |
# *creates link!* |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment