Is neo4j suitable for searching for paths of specific length

时间秒杀一切 提交于 2019-12-13 17:14:45

问题


I am a total newcommer in the world of graph databases. But let's put that on a side.

I have a task to find a cicular path of certain length (or of any other measure) from start point and back.

So for example, I need to find a path from one node and back which is 10 "nodes" long and at the same time has around 15 weights of some kind. This is just an example.

Is this somehow possible with neo4j, or is it even the right thing to use?

Hope I clarified it enough, and thank you for your answers.

Regards


回答1:


Neo4j is a good choice for cycle detection. If you need to find one path from n to n of length 10, you could try some query like this one:

MATCH p=(n:TestLabel {uuid: 1})-[rels:TEST_REL_TYPE*10]-(n)
RETURN p LIMIT 1

The match clause here is asking Cypher to find all paths from n to itself, of exactly 10 hops, using a specific relationship type. This is called variable length relationships in Neo4j. I'm using limit 1 to return only one path.

Resulting path can be visualized as a graph:

You can also specify a range of length, such as [*8..10] (from 8 to 10 hops away).

I'm not sure I understand what you mean with:

has around 15 weights of some kind

You can check relationships properties, such as weight, in variable length paths if you need to. Specific example in the doc here.

Maybe you will also be interested in shortestPath() and allShortestPaths() functions, for which you need to know the end node as well as the start one, and you can find paths between them, even specifying the length.




回答2:


Since you did not provide a data model, I will just assume that your starting/ending nodes all have the Foo label, that the relevant relationships all have the BAR type, and that your circular path relationships all point in the same direction (which should be faster to process, in general). Also, I gather that you only want circular paths of a specific length (10). Finally, I am guessing that you prefer circular paths with lower total weight, and that you want to ignore paths whose total weight exceed a bounding value (15). This query accomplishes the above, returning the matching paths and their path weights, in ascending order:

MATCH p=(f:Foo)-[rels:BAR*10]->(f)
WITH p, REDUCE(s = 0, r IN rels | s + r.weight) AS pathWeight
WHERE pathWeight <= 15
RETURN p, pathWeight
ORDER BY pathWeight;


来源:https://stackoverflow.com/questions/42987401/is-neo4j-suitable-for-searching-for-paths-of-specific-length

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