Search code examples
neo4jgraph-databases

Assign value to relationship in Neo4j


Is there a way to assign a value to a relationship in Neo4j?

Say I have a couple of "people"-nodes with bidirectional relationship FRIENDS between people. What if I want to put a value on the quality of friendships, is that possible? E.g. Paul is 0.54 friends with Alice. Alice is 0.91 friends with Chestirecat.

Thanks.


Solution

  • With Neo4j the generic name of a value assigned to a relationship is called property.

    When creating relationships you can add a property as such

    CREATE (n:People)-[r:Friends { quality: 5 }]-(m:People)
    

    You can also change the value of a property with set

    MATCH (m:People{ name: 'Mary' })-[r:Friends]-(m:People{ name: 'John' })
    SET r.quality= 6
    RETURN n;
    

    To create a weighted friendship between Alice and Paul with a weight of 0.54 use the following CREATE:

    CREATE (n:People { Name: 'Paul' } )-[r:Friends { quality: 0.54 }]->(m:People { Name: 'Alice' });
    

    enter image description here

    and to create a weighted friendship between Alice and Paul when the Alice node already exists with a weight of 0.91 use the following CREATE:

    MATCH (n:People { Name: 'Alice' } )  
      CREATE (n)-[r:Friends { quality: 0.91 }]->(m:People { Name: 'Chestirecat' });
    

    enter image description here

    and to add a Friends relationship between Alice and Paul use the following CREATE:

    MATCH (n:People { Name: 'Alice' } ), (m:People { Name: 'Paul' })  
      CREATE (n)-[r:Friends { quality: 0.62 }]->(m);
    

    enter image description here