Skip to content
Brian Underwood edited this page Aug 24, 2014 · 12 revisions

There are a few ways to find and return nodes.

find returns one ruby object or nil if none was found.

# Example, find by id (neo_id or defined by id_property)
Blog.find(4242)

find_by and find_by! behave as they do in ActiveRecord, returning the first object matching the criteria or either nil or an error in the case of find_by!

Blog.find_by(title: 'Neo4j.rb is awesome')

Basic querying

All of the following result in enumerable results:

# Find all blog models
Blog.all

# Limit results
Blog.where(title: 'neo4j')

# Order
Person.where(age: 30).order(age: :desc).limit(5)

You should use params method whenever dealing with user-submitted data in a where clause to prevent Cypher injection.

Student.where(age: '{age}', name: '{name}', home_town: '{home_town}').params(age: params[:age], name: params[:name], home_town: params[:home_town]).first
Student.query_as(:s).where("s.age < {age} AND s.name = {name} AND s.home_town = {home_town}").params(age: params[:age], name: params[:name], home_town: params[:home_town]).pluck(:s)

When using quotes within a where clause, you can use full cypher syntax. See http://docs.neo4j.org/chunked/stable/query-syntax.html.

Detailed querying

The ActiveNode.query_as and ActiveNode#query_as methods return Query objects which allow you to chain together query clauses and then determine how you'd like the results to be returned.

# Find all comments for any blog which have the world "pottery"
result = Blog.query_as(:blog).match("blog<-[:COMMENTS_ON]-(comment:Comment)").where(comment: {body: /pottery/}).pluck(:blog, :comment)
result.first.blog     # First blog
result.first.comment  # Comment

# Find all comment authors whose age is greater than 30
blog.query_as(:blog).match("blog<-[:COMMENTS_ON]-(:Comment)<-[:AUTHORED]-(author:Person)").where("author.age > 30").pluck(:author)

# You can even get start with basic query methods and then transfer to detailed querying
blog.where(title: 'neo4j').query_as(:blog).match("blog<--(comment:Comment)").where("comment.created_at >= '2014-07-09'").pluck(:comment)

Note that you can return/pluck with strings as well as use DISTINCT (i.e. .pluck('field1, DISTINCT field2')). When you return DISTINCT field the value will be available via the field name's method (without the DISTINCT).

For more information on Query objects, see the Neo4j::Core::Query documentation (LINK TO YARD DOCS NEEDED)

Orm_Adapter

You can also use the orm_adapter API, by calling #to_adapter on your class. See the API, https://github.com/ianwhite/orm_adapter

Cypher

Same as in neo4j-core, see Neo4j::Session.query

Clone this wiki locally