Relating an entity to a relationship proper in Neo4j?

后端 未结 2 638
盖世英雄少女心
盖世英雄少女心 2021-01-21 12:42

I\'m attempting to use Neo4j to model the relationship between projects, staff, and project roles. Each project has a role called \"project manager\" and a role called \"direct

2条回答
  •  余生分开走
    2021-01-21 13:36

    Conceptually, a Neo4j graph is built based on two main types - nodes and relationships. Nodes can be connected with relationships. However, both nodes and relationships can have properties.

    To connect the Project and Staff nodes, the following Cypher statement can be used:

    CREATE (p:Project {name:"Project X"})-[:IS_DIRECTOR]->(director:Staff {firstName:"Jane"})
    

    This creates two nodes. The project node has a Label of type Project and the staff node has a Label of type Staff. Between these node there is a relationhip of type IS_DIRECTOR which indicates that Jane is the director of the project. Note that a relationship is always directed.

    So, to find all directors of all project the following can be used:

    MATCH (p:Project)-[:IS_DIRECTOR]->(director:Staff) RETURN director
    

    The other approach is to add properties to a more general relationship type:

    create (p:Project {name:"Project X"})<-[:MEMBER_OF {role:"Director"}]-(director:Staff {firstName:"Jane"})
    

    This shows how you can add properties to a relationship. Notice that the direction of the relationship was changed for the second example.

    To find all directors using the property based relationship the following can be used:

    MATCH (p:Project)<-[:MEMBER_OF {role:"Director"}]-(directors:Staff) RETURN directors
    

    To retrieve all role types (e.g. director) the following can be used:

    MATCH 
        (p:Project)-[r]->(s:Staff) 
    RETURN 
        r,       // The actual relationship 
        type(r), // The relationship type e.g. IS_DIRECTOR
        r.role   // If properties are available they can be accessed like this
    

    And, to get a unique list of role names COLLECT and DISTINCT can be used:

    MATCH 
        (p:Project)-[r]->(s:Staff) 
    RETURN 
        COLLECT(DISTINCT type(r)) // Distinct types
    

    Or, for properties on the relationship:

    MATCH 
        (p:Project)-[r]->(s:Staff) 
    RETURN 
        COLLECT(DISTINCT r.role) // The "role" property if that is used
    

    The COLLECT returns a list result and the DISTINCT keyword makes sure that there are no duplicates in the list.

提交回复
热议问题