Sorting neo4j by relationship if relationship exist

273 views Asked by At

I am currently developing a social app that requires to filter user by keyword. I am using neo4j database.

I already have the feature but having a problem to filter by relationship first.

For example, user A follows user F. The search result should show F first (If exist), then other users.

The result is sorted username alphabetically, but now I need to sort by relationship first then username.

My current query: Get all users by username keyword, sort by username.

    MATCH (u:User {userId:{userId}}), (su:User)
    WHERE NOT (u)<-[:BLOCK]-(su)
    AND su.username =~ {keyword}
    RETURN SU
    ORDER BY su.username

My reference: https://neo4j.com/docs/developer-manual/current/cypher/clauses/order-by/

1

There are 1 answers

0
Mohamad Raziman Md Dom On

Already found the solution:

MATCH (u:User {userName:{userId}}), (su:User {userStatus:1}) 
WHERE NOT (u)<-[:BLOCK]-(su) 
AND su.userName =~ {keyword}
OR su.displayName =~ {keyword}
RETURN
CASE WHEN EXISTS((u)-[:FOLLOW]-(su)) THEN true
END AS isFollow,  su
ORDER BY isFollow, LOWER(su.userName) ASC, LOWER(su.displayName) ASC

This query will order by relationship, username, then display name. If anyone has a better answer and better performance, please let me know.