# How to distinct cycles in path?

**URL:** <https://community.neo4j.com/t/how-to-distinct-cycles-in-path/68926>\
**Category:** Neo4j Graph Platform\
**Tags:** cypher\
**Created:** [July 20, 2024, 3:31pm UTC](https://community.neo4j.com/t/how-to-distinct-cycles-in-path/68926 "2024-07-20T15:31:35Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![vladlenmv](https://sea1.discourse-cdn.com/flex021/user_avatar/community.neo4j.com/vladlenmv/32/32212_2.png) [@vladlenmv](https://community.neo4j.com/u/vladlenmv)\
**Post date:** [July 20, 2024, 3:31pm UTC](https://community.neo4j.com/t/how-to-distinct-cycles-in-path/68926/1 "2024-07-20T15:31:35Z")

</div>

Hi everybody!

I'm trying to solve logistic task:  
airports, named LAX, LOS and etc. - nodes  
flights between aiports - relations with price

when I'm trying to find all paths between airports by query

```auto
MATCH path = (a:AIRPORT {IATA: 'LAX'})-[:FLIGHT*5]->(n:AIRPORT {IATA: 'LAS'}) 
RETURN path LIMIT 1 

```

as result I have

```auto
(:AIRPORT {IATA: "LAX"})-[:FLIGHT {price: 61.988831864862625}]->(:AIRPORT {IATA: "LAS"})-[:FLIGHT {price: 421.99489651923653}]->(:AIRPORT {IATA: "MIA"})-[:FLIGHT {price: 89.14919592013997}]->(:AIRPORT {IATA: "LAS"})-[:FLIGHT {price: 763.0517870927525}]->(:AIRPORT {IATA: "SEA"})-[:FLIGHT {price: 791.2622954267732}]->(:AIRPORT {IATA: "LAS"})

```

as you see on the way LAS-MIA-LAS - cycled way

how can I have path without cycles?

---

<div class="post-metadata">

**Author:** ![v2belleville](https://sea1.discourse-cdn.com/flex021/user_avatar/community.neo4j.com/v2belleville/32/29050_2.png) [@v2belleville](https://community.neo4j.com/u/v2belleville)\
**Post date:** [August 13, 2024, 7:03pm UTC](https://community.neo4j.com/t/how-to-distinct-cycles-in-path/68926/2 "2024-08-13T19:03:23Z")

</div>

First, you need to allow for 1 hop path with `[:FLIGHT*1..5]` otherwise, the path made of just the direct flight will never be matched.

Avoiding cycle means avoiding any node to be several times in the path, so you can use `apoc.coll.toSet` that returns only unique elements of a list and filter path when the unique list of nodes in the path equals the list of nodes in the path

`MATCH path = (a:AIRPORT {IATA: 'LAX'})-[:FLIGHT*1..5]->(n:AIRPORT {IATA: 'LAS'}) where apoc.coll.toSet(nodes(path))=nodes(path) RETURN [x in nodes(path)|x.IATA]`

["LAX", "LAS"]

Alternatively, you can also sort paths by length and get the shortest  
`MATCH path = (a:AIRPORT {IATA: 'LAX'})-[:FLIGHT*1..5]->(n:AIRPORT {IATA: 'LAS'}) with path,length(path) as len order by len limit 1 RETURN [x in nodes(path)|x.IATA]`  
["LAX", "LAS"]
