Graph Database Newbie Q- How to decide on the direction of a relation between 2 nodes

社会主义新天地 提交于 2019-12-22 18:32:31

问题


How do you decide the verb-direction of a relation ?

E.g I have a Country falling under a Sub REgion which in turn is under a Region. Which one would be better and are there any thumb rules on deciding the direction.

(Region)-[HAS]->(Sub Region)-[HAS]->(Country)

or

(Region)<-[BELONGS_TO]-(Sub Region)<-[BELONGS_TO]-(Country)

Regards San


回答1:


I agree with @InverFalcon that directionality is mostly a subjective decision. However, there may be (at least) one situation in which you might want to use a specific direction, especially if that will make an important use case faster.

This is related to the fact that often if you can make a Cypher pattern less specific (without affecting the output), then neo4j would have to do less work and your query would be faster.

For example, suppose your entire data model consists of 2 node labels and 2 relationship types, like below. (I use my own data model, since I don't know what your uses cases are.)

(:Person)-[:ACTED_IN]->(:Movie)
(:Person)-[:DIRECTED]->(:Movie)

In order to find the movies that an actor acted in, your query would have to look something like the following. (Notice that we have to specify the ACTED_IN type, because an outgoing relationship could also be of type DIRECTED. This means that neo4j has to explicitly test every outgoing relationship for its type):

MATCH (:Person {id: 123})-[:ACTED_IN]->(m:Movie)
RETURN m;

However, if your data model replaced the DIRECTED type with a DIRECTED_BY type that had opposite directionality, then it would look like this instead:

(:Person)-[:ACTED_IN]->(:Movie)
(:Person)<-[:DIRECTED_BY]-(:Movie)

With that tweak, your query could be simpler and faster (since neo4j would not have to test relationship types):

MATCH (:Person {id: 123})-->(m:Movie)
RETURN m;

And to be complete, notice that in the above 2 MATCH patterns we could actually remove the :Movie label, since in both data models the ACTED_IN end node will always have the Movie label.



来源:https://stackoverflow.com/questions/40531596/graph-database-newbie-q-how-to-decide-on-the-direction-of-a-relation-between-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!