Andru
Andru

Reputation: 21

Neo4j Conditional query

In Neo4j graph I have 2 nodes with same label and 4 properties, I want the condition to check value of there properties are equal, and if any of 4 properties are equal I want to create relation between those 2 nodes as Similar_To , this relation should also contain property as percentage , depend on out of 4 properties of nodes how many properties are matching we are calculating percentage (If 1 value for 1 property matching then percentage is 25 ,if 2 then percentage is 50 if 3 then 75 and if 4 then 100) Want query for this ,Can I have 4 if conditions in my cypher query and How I can write it,Please reply

I tried

MATCH(n:Student),(m:Student)
WHERE id(n<>id(m) and (n.age=m.age OR n.marks=m.marks OR n.div=m.div OR n.weight=m.weight)
CREATE (n)-[:SIMILAR_TO{Percentage:25}]->(m) RETURN n,m

Will create relationship if value for any of 4 properties are equal, but percentage is always 25, I want percentage value depend on number of properties matching

Trying something like

WITH 0 as x
MATCH(n:Student),(m:Student)
WHERE id(n)<>id(m)
//If n.age=m.age then x=x+25
//If n.marks=m.marks then x=x+25
//If n.div=m.div then x=x+25  
//If n.weight=m.weight then x=x+25
if x<>0  then CREATE (n)-[:SIMILAR_TO{Percentage:x}]->(m)
RETURN n,m

But I don't know How to write those 4 If conditions

Upvotes: 2

Views: 94

Answers (1)

jose_bacoy
jose_bacoy

Reputation: 12704

Below query is generalized so even the nodes have > 4 properties, it can still get the percentage without changing the code. In other words, no need to hardcode +25 when properties are the same value.

  1. Get the students where studentA (n) is not the same with studentB (m).
  2. Assuming that node n has the same properties with m, get the counts (using reduce) where the properties of both n and m are equal
  3. Divide the count of similar properties into the total number of properties in n
  4. Create (or Merge) the relationship between n and m using the percentage of similarities between n and m based on properties
WITH ['age', 'div', 'marks', 'weight'] as props
MATCH (n:Student), (m:Student) WHERE n<m
WITH props, n, m, reduce(x=0, k in keys(n) | x + case when k in props and n[k]=m[k] then 1 else 0 end) as similarity
WITH props, n, m, 100*similarity/size(props) as percentage
MERGE (n)-[:SIMILAR_TO{Percentage:percentage}]->(m) 

References:

  1. reduce function https://neo4j.com/docs/cypher-manual/current/functions/list/#functions-reduce
  2. keys function https://neo4j.com/docs/cypher-manual/current/functions/list/#functions-keys

Upvotes: 2

Related Questions