Search code examples
neo4jneography

Ways to remember and reuse previous query result in Neo4j


I am coding in Ruby using Neo4j with the gem Neography. When doing query, I use the method execute_neo4j_query provided by Neography. I am not sure about the best practice.

Suppose I use following code to fetch a user:

user1 = @neo.execute_neo4j_query("
      MATCH (user:User {user_id: '#{params[:user_id_1]}'})
      RETURN id(user)
      LIMIT 1
      ")

and to fetch another user similarly

user2 = @neo.execute_neo4j_query("
      MATCH (user:User {user_id: '#{params[:user_id_2]}'})
      RETURN id(user)
      LIMIT 1
      ")

Then I did some stuff with this two users.

Now I need to create an edge between this two users, so I did this

@neo.execute_neo4j_query("
      MATCH (user1:User {user_id: '#{params[:user_id_2]}'})
      MATCH (user2:User {user_id: '#{params[:user_id_2]}'})
      CREATE UNIQUE (user1)-[:FOLLOW]->(user2)
      ")

However, I believe such approach is not optimal, since I queried for the same two users twice.

My question is:

1) Is there a way to reuse previously queried results using Neography?

2) Is it recommended to use methods provided by Neography such as @neo.create_node other than using execute_neo4j_query directly? I choose the latter because I am not sure if the encapsulated methods can satisfy my task. So, if you can rewrite my above codes in native Neography code, it will be greatly appreciated.


Solution

    1. Don't use start anymore if you don't know why you would use it
    2. use the transactional cypher support in neography
    3. Use Parameters in your cypher queries, like MATCH (u:User {name:{name}}) RETURN u