cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Storing decimal numbers or fractions as weights for using them in graph algorithms

Hello,

I am trying to compute decimal numbers using graph algorithms and store it in new edges that I create? My code

MATCH path = (a:person) -[:connected_to*]- (b:person)
 WHERE id(a) < id(b) 
 WITH a, b, length(path) as weight
 CREATE (a)-[e:co_authors]->(b)
 SET e.weight=1/weight

is setting 0 as a the e.weight and not 1/2 or 1/3 or whatever the algorithm finds. How can I work around this?

9 REPLIES 9

MuddyBootsCode
Graph Steward

You might to explicitly cast it to a float with toFloat(1/weight) maybe try that and see what it returns?

toFloat(1/weight) returns 0.0 - still 0

MuddyBootsCode
Graph Steward

What do you get from just returning length? Like:

MATCH path = (a:person) -- (:citation*) -- (b:person)
WHERE id(a) < id(b)
RETURN length(path)

Have you checked to make sure it's what you expect?

yes

MATCH path = (a:person) -[:connected_to*]- (b:person)
 WHERE id(a) < id(b) 
 WITH a, b, length(path) as weight
 RETURN weight

returns integers 1,2,3,...

Here is an example I ran on the sandbox on yelp:

MATCH path = (a:Business {id:"bFzdJJ3wp3PZssNEsyU23g"}) -[*2..3]- (b:Business {id:"45bWSZtniwPRiqlivpS8Og"})
 WHERE id(a) < id(b) 
 WITH a, b, length(path) as weight
 return toFloat(1/weight)

returns 0.0 when it should be 0.5

 return toFloat(weight)

returns 2 as expected.

MuddyBootsCode
Graph Steward

Maybe try to rewrite it:

MATCH path = (a:person) -[:connected_to*]- (b:person)
 WHERE id(a) < id(b) 
 WITH a, b, length(path) as weight
 CREATE (a)-[:co_authors {weight: toFloat(1/weight)}]->(b)

Sorry I'm not being much help, I'm at a loss at the moment. I'll sit down here in a bit and work on it some more.

Just realized and fixed - below code does the trick. Lesson relearnt: convert variables to float before using it in an expression whose output is float.

MATCH path = (a:person) -[:connected_to*]- (b:person)
 WHERE id(a) < id(b) 
 WITH a, b, tofloat(length(path)) as weight
 CREATE (a)-[:co_authors {weight: toFloat(1/weight)}]->(b)

You can use round function:

WITH 2 as precision
WITH a, b, toFloat(1/length(path)) as weight. 10^precision AS factor
RETURN round(factor * value)/factor AS value

again minor - but only the below worked for me

WITH a, b, toFloat(1/length(path)) as weight, 2 as precision
WITH a, b, weight, 10^precision AS factor
RETURN round(factor * value)/factor AS value