MichaelE
MichaelE

Reputation: 767

Using LIMIT in Neo4j cypher subquery does not limit the amount of rows returned

I have a subquery where I need to get just the first row. Using LIMIT 1 in the subquery I thought I would get just just the first but I am still getting all the rows. This is my cypher snippet:

 WITH t,s
 CALL {
              WITH t,s
              MATCH (t)-[:PROVIDES]->(s)
              WITH t
              LIMIT 1
              RETURN t AS tech
            }
      
 RETURN   tech 

I am using Neo4j Desktop 4.5. I have also tried

RETURN t AS tech LIMIT 1

What am I doing wrong here? EDIT my reason for requiring the first tech only is that I actually need to assign that that tech to a job like so:

CREATE (tech)-[:ASSIGNED_TO]->(s)

The subquery is actually querying a list of multiple techs and just want to choose the first one based on the query.

Upvotes: 1

Views: 262

Answers (1)

jose_bacoy
jose_bacoy

Reputation: 12684

The first line "WITH t,s" is causing multiple rows and not inside the subquery "CALL". Your subquery CALL is correct to return one node t as tech but the entire query is doing a cartesian product with tech and t,s. Thus you are getting multiple values of tech. Below are suggested fixes.

Option#1: Simply return one tech value using LIMIT 1.

WITH t,s
 CALL {
              WITH t,s
              MATCH (t)-[:PROVIDES]->(s)
              RETURN t AS tech 
            }
      
 RETURN tech LIMIT 1

Option#2: Collect all values of tech [collect (tech)] then get the first item (index: 0) on that list. This will surely return one row of tech.

 WITH t,s
 CALL {
              WITH t,s
              MATCH (t)-[:PROVIDES]->(s)
              RETURN t AS tech
            }
      
 RETURN  collect(tech)[0] as tech 

Upvotes: 1

Related Questions