Matt Larsuma
Matt Larsuma

Reputation: 1519

Neo4j match a random single node of a certain type of nodes

I have a node for groups and that users are members of. I would like to auto-assign a User to a Group at random when they register. Is there a way to randomly MATCH a single node of a certain type.

MATCH (g:Group) return g

The above will give me all groups. To create the relationship I would do the following:

MATCH (u:User {id: <ID>}), (g:Group {id: <ID>}) CREATE (u)-[r:MEMBER_OF]->(g) RETURN type(r)

But I would like to do something like this:

CREATE(u:User {
  id: apoc.create.uuid(), 
  firstName: $firstName, 
  username: $username, 
  phoneNumber: $phoneNumber, 
  createdAt: datetime(),
  updatedAt: datetime(),
  role: 'USER'
  }
)
  WITH u
  MATCH (g:Group)
  //
  CREATE (u)-[:MEMBER_OF]->(g)
  return u

where I would match a random group and then create the MEMBER_OF relationship. Eventually there may be other considerations, but for now I would love to just randomly select a group and then create the relationship.

Upvotes: 0

Views: 106

Answers (1)

cybersam
cybersam

Reputation: 66967

You can use the apoc function apoc.coll.randomItem to pick out a random node from a collection of all the Group nodes:

MATCH (x:Group)
WITH datetime() AS dt, apoc.coll.randomItem(COLLECT(x)) AS g
CREATE (u:User {
  id: apoc.create.uuid(), 
  firstName: $firstName, 
  username: $username, 
  phoneNumber: $phoneNumber, 
  createdAt: dt,
  updatedAt: dt,
  role: 'USER'
})-[:MEMBER_OF]->(g)
RETURN u

Upvotes: 1

Related Questions