shivshankar
shivshankar

Reputation: 2135

cypher match query merge result set

I'm newer in CQL anyone help me to solve query to find list of followers with a flag if i also follow him. i'm trying like this way

MATCH (n:users_master)-[r:FOLLOW]->(m:users_master)
OPTIONAL MATCH (n:users_master)<-[r2:FOLLOW]-(m:users_master)   
CASE when EXISTS(r2) THEN n.flag= 1 ELSE n.flag=0 END  
where id(m)=35  
RETURN n

notice here i'd also like to add a virtual property flag in result set LIKE {"updated_at":"12/26/2016, 3:45:38 PM", "created_on":"12/26/2016, 3:45:38 PM", "last_name":"john", "first_name":"john", "email":"new@test", "facebook_id":"12341", "status":"Active", "id":35 "flag":1 }

Upvotes: 1

Views: 388

Answers (1)

InverseFalcon
InverseFalcon

Reputation: 30397

The EXISTS() function can be used to check for the existence of a pattern, and in your case can replace your OPTIONAL MATCH.

Also, variables in your patterns aren't needed if you aren't going to be using them, so you shouldn't need them on your relationships at all.

MATCH (n:users_master)-[:FOLLOW]->(m:users_master)
WHERE id(m)=35  
RETURN n, EXISTS( (n)<-[:FOLLOW]-(m) ) as flag

'flag' will be a separate column with a boolean on whether or not the follow is reciprocal.

As far as adding a 'virtual property', in Neo4j 3.1+, you can use Map Projection to add custom values to the map projection of returned nodes.

You could use this query with map projection to include the flag in the return of node properties:

MATCH (n:users_master)-[:FOLLOW]->(m:users_master)
WHERE id(m)=35  
RETURN n {.*, flag: EXISTS( (n)<-[:FOLLOW]-(m) ) }

EDIT

The map projection used in the query above was introduced and only works in Neo4j 3.1.x and up.

For versions 3.0.x, I don't believe there are many options for extracting all node properties to a map and adding a new value to that map before returning (SET clause is reserved for nodes, not maps).

You may need to install APOC procedures for a workaround, as it provides several helper procedures and functions, including map operations.

This should work after the relevant version of APOC is added to your Neo4j instance:

MATCH (n:users_master)-[:FOLLOW]->(m:users_master)
WHERE id(m)=35  
RETURN apoc.map.setKey(properties(n), 'flag', EXISTS( (n)<-[:FOLLOW]-(m) )) as n

Upvotes: 2

Related Questions