Search code examples
neo4jneo4j.rb

Neo4j: How to filter out nodes from a list of IDs?


I am trying to "select all posts" and exclude specific nodes that are in an array of IDs (post authors). With SQL you can use NOT IN (1, 2, 3). How can I create a CYPHER query to do this?

Post  <-- author --  User
 - ID                 - ID

Solution

  • Mostly the same as SQL ;)

    MATCH (author)-[:author]->(post:Post)
    WHERE NOT(ID(author) IN {id_list})
    RETURN DISTINCT post
    

    Since you tagged the question as Neo4j.rb:

    User.as(:author).posts.where('NOT(ID(author) IN ?)', [1,2,3])
    

    In newer versions of Neo4j.rb:

    User.as(:author).posts.where_not('ID(author) IN ?', [1,2,3])
    

    You didn't mention what kind of ids, so I default to Neo4j IDs, but keep in mind that those can be recycled so they aren't for long term usage as reference.

    EDIT:

    Your comment made be realize that perhaps a better way to go about it is:

    User.where_not(id: ids).posts
    

    It should translate the id to whatever you use for id_property (uuid by default).