Search code examples
rubyneo4jneo4j.rb

Neo4j.rb How to run Cypher query directly?


I want to run directly Cypher queries in rails don't want to use ORM style because I have long queries which I made on neo4j console and when I am trying to change into orm style its not behaving as expected

MATCH (n {name: 'MU1'})-[:connected_to*1..2 {status: 1}]->(sp:User),
      (sp)<-[:owner_of|house_mate]-(place:Place)-[:owner_of|house_mate]->(c:User)
WHERE NOT (n)-[:house_mate]-(place)
MATCH
  (place)-[tenant:owner_of|house_mate]->(u:User)
WITH DISTINCT place, type(tenant) AS type, u
WITH place, collect({type: type, u: u}) AS tenants
RETURN
   place,
   [tenant IN tenants WHERE tenant.type = 'owner_of'   | [tenant.u]][0] AS owner,
   [tenant IN tenants WHERE tenant.type = 'house_mate' | [tenant.u]] AS houseMatesArray

Neo4j.query and Neo4j._query etc

Any Help?

Edit: How to write it in ORM style may be I was doing something wrong?


Solution

  • Here is Query style as requested in comments. With a query like this, though, you don't get much benefit from this style unless maybe you're passing partial Query objects around. You probably want to stick to a Cypher query defined in a Ruby heredoc.

    Neo4j::ActiveBase.new_query
      .match(n: {name: 'MU1'})
      .match('(n)-[:connected_to*1..2 {status: ?}]->(sp:User)', 1)
      .match('(sp)<-[:owner_of|house_mate]-(place:Place)-[:owner_of|house_mate]->(c:User)')
      .where_not('(n)-[:house_mate]-(place)')
      .break
      .match('(place)-[tenant:owner_of|house_mate]->(u:User)')
      .with('DISTINCT place, type(tenant) AS type, u')
      .with(:place, tenants: 'collect({type: type, u: u})')
      .pluck(:place,
              owner: '[tenant IN tenants WHERE tenant.type = 'owner_of'   | [tenant.u]][0]',
              houseMatesArray: '[tenant IN tenants WHERE tenant.type = 'house_mate' | [tenant.u]]')
    

    You need the break in there to keep the match clauses from grouping, though that's because of a design decision that I've wanted to reverse for a while now.

    Also, I'm thinking that there should be a with_distinct method because DISTINCT (IIRC) applies to the whole set of columns.