1ManStartup
1ManStartup

Reputation: 3826

Neo4J Cypher: Count How Many Attributes/Properties in each node matched my query

For example, lets say my query is:

match (u:User) Where u.LivesIn:'Los Angeles' OR u.From:'Miami' OR u.Status:'Single' OR u.Job:'Artist'}) return u

How would I change my query so I can display a column that counts how many attributes matched my query.

For my query above, lets say I returned the following Users:

> User1, Los Angeles, Miami, Single, Artist, (4 attributes matched query
> so show a 4 in column)
> 
> User2, Los Angeles, Miami, Married, Artist, (3 attributes matched
> query so display 3 in column)
> User3, Los Angeles, New York, Married, Dancer, (1 attributes matched
> query so display 1 in column)

Im using this to build a sort of ranking system

Im trying to get This:

u.UserID     u.MatchingAttributes

User1        4

User2        3

User3        1

Also as a bonus if you can please show how to do this with relationships also. Thanks.

Upvotes: 0

Views: 1637

Answers (2)

Nicole White
Nicole White

Reputation: 7800

You could use a bunch of CASE statements:

MATCH (u:User)
WITH u.UserID AS User, CASE WHEN u.LivesIn = 'Los Angeles' THEN 1 ELSE 0 END AS c1,
                       CASE WHEN u.From = 'Miami' THEN 1 ELSE 0 END AS c2,
                       CASE WHEN u.Status = 'Single' THEN 1 ELSE 0 END AS c3,
                       CASE WHEN u.Job = 'Artist' THEN 1 ELSE 0 END AS c4
RETURN User, c1 + c2 + c3 + c4 AS Matching

Upvotes: 2

Sumeet Sharma
Sumeet Sharma

Reputation: 2583

Suppose you graph is modelled as

enter image description here

Now you can name the relationships to something suitable. The sole purpose of the graph model i pasted is to just demostrate the matching strategy thats why i have skipped naming the relationships suitably and adding node labels.

Now what you can do is

match (u:User)-[r]-(m) where m.name in ['LA','Miami','Single','Artist'] return u,count(m) as count

{Assuming above the m other nodes (other than the User labelled nodes) have name attribs in them }

Upvotes: 1

Related Questions