Nguyen Son
Nguyen Son

Reputation: 15

Condition checking in cypher (neo4j)

I run the following code. And I want to get "phone" property from USER_PHONE node if it exists relationship from my "u" node. but i cannot assign variable to get it. if I fix the first line to: (phone)<--(u:USER)-[:friend]-(p:USER)-[i:interested_in]->(p0:INTEREST{name:'Tiếng Anh'}). Then the return result is repeated twice for nodes that satisfy the condition if ((u)-->(:USER_PHONE)) in the case. Can someone help me?

    match (u:USER)-[:friend]-(p:USER)-[i:interested_in]->(p0:INTEREST{name:'Tiếng Anh'})
    return id(u), u.FB_ID, sum(toInteger(i.strength)*p.ai_pagerank2) as CII, 
    CASE u
      WHEN (u)-->(phone:USER_PHONE) THEN phone.phone
      ELSE NULL
    END as num_phone order by num_phone ASC limit 100

This is the error i got

PatternExpressions are not allowed to introduce new variables: 'phone'. (line 4, column 15 (offset: 183))
    "  WHEN (u)-->(phone:USER_PHONE) THEN phone.phone"

this is the error i got

Upvotes: 1

Views: 496

Answers (1)

jose_bacoy
jose_bacoy

Reputation: 12684

You can do "OPTIONAL MATCH". Here is a documentation about it: https://neo4j.com/docs/cypher-manual/current/clauses/optional-match/

match (u:USER)-[:friend]-(p:USER)-[i:interested_in]->(p0:INTEREST{name:'Tiếng Anh'})
with u, i, p
optional match (u)-->(userPhone:USER_PHONE)
return id(u), u.FB_ID, sum(toInteger(i.strength)*p.ai_pagerank2) as CII, 
userPhone.phone as num_phone order by num_phone ASC limit 100

You don't need to check phone if null since if the phone number does not exists, it will return null.

Upvotes: 1

Related Questions