Class: Neo4j::Core::Query

Inherits:
Object
  • Object
show all
Includes:
Enumerable, QueryClauses, QueryFindInBatches
Defined in:
lib/neo4j-core/query.rb

Overview

Allows for generation of cypher queries via ruby method calls (inspired by ActiveRecord / arel syntax)

Can be used to express cypher queries in ruby nicely, or to more easily generate queries programatically.

Also, queries can be passed around an application to progressively build a query across different concerns

See also the following link for full cypher language documentation: docs.neo4j.org/chunked/milestone/cypher-query-lang.html

Defined Under Namespace

Classes: PartitionedClauses

Constant Summary collapse

DEFINED_CLAUSES =
{}
METHODS =

DELETE clause

Returns:

%w(start match optional_match using where create create_unique merge set on_create_set on_match_set remove unwind delete with return order skip limit)
BREAK_METHODS =
%(with)
CLAUSIFY_CLAUSE =
proc do |method|
  const_get(method.to_s.split('_').map(&:capitalize).join + 'Clause')
end
CLAUSES =
METHODS.map(&CLAUSIFY_CLAUSE)
EMPTY =

Returns a CYPHER query string from the object query representation

Examples:

Query.new.match(p: :Person).where(p: {age: 30})  # => "MATCH (p:Person) WHERE p.age = 30

Returns:

  • (String)

    Resulting cypher query string

' '
MEMOIZED_INSTANCE_VARIABLES =
[:response, :merge_params]

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from QueryFindInBatches

#find_each, #find_in_batches

Constructor Details

#initialize(options = {}) ⇒ Query

Returns a new instance of Query.



21
22
23
24
25
26
27
# File 'lib/neo4j-core/query.rb', line 21

def initialize(options = {})
  @session = options[:session] || Neo4j::Session.current

  @options = options
  @clauses = []
  @_params = {}
end

Instance Attribute Details

#clausesObject

Returns the value of attribute clauses.



19
20
21
# File 'lib/neo4j-core/query.rb', line 19

def clauses
  @clauses
end

Instance Method Details

#&(other) ⇒ Object



290
291
292
293
294
295
296
297
# File 'lib/neo4j-core/query.rb', line 290

def &(other)
  fail "Sessions don't match!" if @session != other.session

  self.class.new(session: @session).tap do |new_query|
    new_query.options = options.merge(other.options)
    new_query.clauses = clauses + other.clauses
  end.params(other._params)
end

#breakObject

Allows what’s been built of the query so far to be frozen and the rest built anew. Can be called multiple times in a string of method calls

Examples:

# Creates a query representing the cypher: MATCH (q:Person), r:Car MATCH (p: Person)-->q
Query.new.match(q: Person).match('r:Car').break.match('(p: Person)-->q')


148
149
150
# File 'lib/neo4j-core/query.rb', line 148

def break
  build_deeper_query(nil)
end

#clause?(method) ⇒ Boolean

Returns:

  • (Boolean)


308
309
310
311
312
313
# File 'lib/neo4j-core/query.rb', line 308

def clause?(method)
  clause_class = DEFINED_CLAUSES[method] || CLAUSIFY_CLAUSE.call(method)
  clauses.any? do |clause|
    clause.is_a?(clause_class)
  end
end

#copyObject



300
301
302
303
304
305
306
# File 'lib/neo4j-core/query.rb', line 300

def copy
  dup.tap do |query|
    MEMOIZED_INSTANCE_VARIABLES.each do |var|
      query.instance_variable_set("@#{var}", nil)
    end
  end
end

#count(var = nil) ⇒ Object



189
190
191
192
# File 'lib/neo4j-core/query.rb', line 189

def count(var = nil)
  v = var.nil? ? '*' : var
  pluck("count(#{v})").first
end

#create(*args) ⇒ Query

CREATE clause

Returns:



# File 'lib/neo4j-core/query.rb', line 81

#create_unique(*args) ⇒ Query

CREATE UNIQUE clause

Returns:



# File 'lib/neo4j-core/query.rb', line 85

#delete(*args) ⇒ Query

DELETE clause

Returns:



105
# File 'lib/neo4j-core/query.rb', line 105

METHODS = %w(start match optional_match using where create create_unique merge set on_create_set on_match_set remove unwind delete with return order skip limit)

#eachObject



194
195
196
197
198
199
200
201
202
# File 'lib/neo4j-core/query.rb', line 194

def each
  response = self.response
  if response.is_a?(Neo4j::Server::CypherResponse)
    response.unwrapped! if unwrapped?
    response.to_node_enumeration
  else
    Neo4j::Embedded::ResultWrapper.new(response, to_cypher, unwrapped?)
  end.each { |object| yield object }
end

#execBoolean

Executes a query without returning the result

Returns:

  • (Boolean)

    true if successful

Raises:



213
214
215
216
217
# File 'lib/neo4j-core/query.rb', line 213

def exec
  response

  true
end

#limit(*args) ⇒ Query

LIMIT clause

Returns:



# File 'lib/neo4j-core/query.rb', line 57

#match(*args) ⇒ Query

MATCH clause

Returns:



# File 'lib/neo4j-core/query.rb', line 33

#merge(*args) ⇒ Query

MERGE clause

Returns:



# File 'lib/neo4j-core/query.rb', line 89

#on_create_set(*args) ⇒ Query

ON CREATE SET clause

Returns:



# File 'lib/neo4j-core/query.rb', line 93

#on_match_set(*args) ⇒ Query

ON MATCH SET clause

Returns:



# File 'lib/neo4j-core/query.rb', line 97

#optional_match(*args) ⇒ Query

OPTIONAL MATCH clause

Returns:



# File 'lib/neo4j-core/query.rb', line 37

#order(*args) ⇒ Query Also known as: order_by

ORDER BY clause

Returns:



# File 'lib/neo4j-core/query.rb', line 53

#params(args) ⇒ Object

Allows for the specification of values for params specified in query

Examples:

# Creates a query representing the cypher: MATCH (q: Person {id: {id}})
# Calls to params don't affect the cypher query generated, but the params will be
# Passed down when the query is made
Query.new.match('(q: Person {id: {id}})').params(id: 12)


159
160
161
162
163
# File 'lib/neo4j-core/query.rb', line 159

def params(args)
  @_params = @_params.merge(args)

  self
end

#pluck(*columns) ⇒ Object

Return the specified columns as an array. If one column is specified, a one-dimensional array is returned with the values of that column If two columns are specified, a n-dimensional array is returned with the values of those columns

Examples:

Query.new.match(n: :Person).return(p: :name}.pluck(p: :name) # => Array of names
Query.new.match(n: :Person).return(p: :name}.pluck('p, DISTINCT p.name') # => Array of [node, name] pairs


228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/neo4j-core/query.rb', line 228

def pluck(*columns)
  fail ArgumentError, 'No columns specified for Query#pluck' if columns.size.zero?

  query = return_query(columns)
  columns = query.response.columns

  case columns.size
  when 1
    column = columns[0]
    query.map { |row| row[column] }
  else
    query.map do |row|
      columns.map do |column|
        row[column]
      end
    end
  end
end

#remove(*args) ⇒ Query

REMOVE clause

Returns:



# File 'lib/neo4j-core/query.rb', line 69

#reorder(*args) ⇒ Object

Clears out previous order clauses and allows only for those specified by args



129
130
131
132
133
134
# File 'lib/neo4j-core/query.rb', line 129

def reorder(*args)
  query = copy

  query.remove_clause_class(OrderClause)
  query.order(*args)
end

#responseObject



174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/neo4j-core/query.rb', line 174

def response
  return @response if @response
  cypher = to_cypher

  @response = @session._query(cypher, merge_params, context: @options[:context])

  if !response.respond_to?(:error?) || !response.error?
    response
  else
    response.raise_cypher_error
  end
end

#return(*args) ⇒ Query

RETURN clause

Returns:



# File 'lib/neo4j-core/query.rb', line 77

#return_query(columns) ⇒ Object



247
248
249
250
251
252
# File 'lib/neo4j-core/query.rb', line 247

def return_query(columns)
  query = copy
  query.remove_clause_class(ReturnClause)

  query.return(*columns)
end

#set(*args) ⇒ Query

SET clause

Returns:



# File 'lib/neo4j-core/query.rb', line 65

#set_props(*args) ⇒ Object

Works the same as the #set method, but when given a nested array it will set properties rather than setting entire objects

Examples:

# Creates a query representing the cypher: MATCH (n:Person) SET n.age = 19
Query.new.match(n: :Person).set_props(n: {age: 19})


140
141
142
# File 'lib/neo4j-core/query.rb', line 140

def set_props(*args)
  build_deeper_query(SetClause, args, set_props: true)
end

#skip(*args) ⇒ Query Also known as: offset

SKIP clause

Returns:



# File 'lib/neo4j-core/query.rb', line 61

#start(*args) ⇒ Query

START clause

Returns:



# File 'lib/neo4j-core/query.rb', line 29

#to_aArray

Class is Enumerable. Each yield is a Hash with the key matching the variable returned and the value being the value for that key from the response

Returns:

  • (Array)

Raises:



# File 'lib/neo4j-core/query.rb', line 204

#to_cypherObject



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/neo4j-core/query.rb', line 260

def to_cypher
  cypher_string = PartitionedClauses.new(@clauses).map do |clauses|
    clauses_by_class = clauses.group_by(&:class)

    cypher_parts = CLAUSES.map do |clause_class|
      clause_class.to_cypher(clauses) if clauses = clauses_by_class[clause_class]
    end

    cypher_parts.compact!
    cypher_parts.join(EMPTY).tap(&:strip!)
  end.join EMPTY

  cypher_string = "CYPHER #{@options[:parser]} #{cypher_string}" if @options[:parser]
  cypher_string.tap(&:strip!)
end

#union_cypher(other, options = {}) ⇒ String

Returns a CYPHER query specifying the union of the callee object’s query and the argument’s query

Examples:

# Generates cypher: MATCH (n:Person) UNION MATCH (o:Person) WHERE o.age = 10
q = Neo4j::Core::Query.new.match(o: :Person).where(o: {age: 10})
result = Neo4j::Core::Query.new.match(n: :Person).union_cypher(q)

Parameters:

  • other (Query)

    Second half of UNION

  • options (Hash) (defaults to: {})

    Specify true to use UNION ALL

Returns:

  • (String)

    Resulting UNION cypher query string



286
287
288
# File 'lib/neo4j-core/query.rb', line 286

def union_cypher(other, options = {})
  "#{to_cypher} UNION#{options[:all] ? ' ALL' : ''} #{other.to_cypher}"
end

#unwind(*args) ⇒ Query

UNWIND clause

Returns:



# File 'lib/neo4j-core/query.rb', line 73

#unwrappedObject



165
166
167
168
# File 'lib/neo4j-core/query.rb', line 165

def unwrapped
  @_unwrapped_obj = true
  self
end

#unwrapped?Boolean

Returns:

  • (Boolean)


170
171
172
# File 'lib/neo4j-core/query.rb', line 170

def unwrapped?
  !!@_unwrapped_obj
end

#using(*args) ⇒ Query

USING clause

Returns:



# File 'lib/neo4j-core/query.rb', line 41

#where(*args) ⇒ Query

WHERE clause

Returns:



# File 'lib/neo4j-core/query.rb', line 45

#with(*args) ⇒ Query

WITH clause

Returns:



# File 'lib/neo4j-core/query.rb', line 49