Cameron Tinker
Cameron Tinker

Reputation: 9789

Neo4jClient create relationship with attribute and update it later

I have a Friend relationship class for Neo4jClient that I want to use for managing friends on my social networking website. Rather than create a separate relationship for each possible friend status, (requested, accepted, denied, blocked), I have added a property to my friend relationship class. However, when the class is serialized using Neo4jClient, it does not create the Status property on the relationship.

Here is my relationship class:

/// <summary>
/// Friendship relationship - User is a friend of a User with a Status of REQUESTED, ACCEPTED, DENIED, BLOCKED
/// </summary>
public class Friend : Relationship, IRelationshipAllowingSourceNode<User>,
    IRelationshipAllowingTargetNode<User>
{
    public static readonly string TypeKey = "FRIEND";

    public string Status { get; set; }

    public Friend(NodeReference targetNode)
        : base(targetNode)
    { }

    public override string RelationshipTypeKey
    {
        get { return TypeKey; }
    }
}

Here is my code for creating the relationship:

client.CreateRelationship(user, Friend(requestedUser) { Status = "REQUESTED" });

I want to be able to later query all Friend relationships and return different sets based on the Status property. I also want to be able to update the Status property on Friend relationships. Please advise on what should be done to properly add the Status property.

Upvotes: 1

Views: 1543

Answers (1)

Cameron Tinker
Cameron Tinker

Reputation: 9789

After further research, I have found that you need to provide a payload class to the inherited generic Relationship class like so:

/// <summary>
/// Friendship relationship - User is a friend of a User with a Status of REQUESTED, ACCEPTED, DENIED, BLOCKED
/// </summary>
public class Friend : Relationship<FriendPayload>, IRelationshipAllowingSourceNode<User>,
    IRelationshipAllowingTargetNode<User>
{
    public static readonly string TypeKey = "FRIEND";

    public Friend(NodeReference targetNode)
        : base(targetNode)
    { }

    public override string RelationshipTypeKey
    {
        get { return TypeKey; }
    }
}

Here is the payload class:

public class FriendPayload
{
    public string Status { get; set; }
}

This should allow you to add properties to your relationships. From there, you can use Cypher to get a particular relationship/node based on the property in the relationship. You can also use Cypher to update the relationship property like so:

START n=node(1) MATCH n-[r:FRIEND]-e WHERE e.Name = "Bob" SET r.Status = "ACCEPTED";

Note: You can also use an index based lookup for your start node.

I will try and write a basic getting started tutorial for Neo4jClient on my blog compiling all of my findings into one place now that I've figured out the basics.

Upvotes: 3

Related Questions