Search code examples
neo4jcypher

Is there a way to make something similar to SELECT inside FROM in Neo4j like in SQL?


I have to make a query that gives me the list of people who reposted the posts of someone whose posts are the most likable.

It HAS to be one query, but I can make it only through two queries. I've tried OPTIONAL MATCH, and the CALL clause, but it's still not working and I can't understand what exactly I'm doing wrong.

Here's my two queries:

1)

match (per1:Person)-[r1:LIKE]->(p:Post)<-[:CREATE]-(per2:Person)
return per2.name, count(r1) order by count(r1) desc limit 1

(I find that the author, whose posts get the biggest amount of likes, is Emily Douson, so I do the next step:)

2)

match (per:Person)-[:REPOST]->(p:Post)<-[:CREATE]-(per2: Person {name:"Emily Douson"})
return distinct per.name

The problem is that through OPTIONAL MATCH I can get the list of authors, but not the one author that I need to use.

My attempt to use CALL looked like:

call {
  match(per1:Person)-[r1:LIKE]->(p:Post)<-[:CREATE]-(per2:Person)
  return per2.FIO as personX, count(r1) as countL order by countL desc limit 1
}
with personX
match (per:Person)-[:REPOST]->(p:Post)<-[:CREATE]-(personX)
return distinct per.FIO

but I got the message:

Type mismatch: personX defined with conflicting type Boolean, Float, Integer, Number, Point, String, Duration, Date, Time, LocalTime, LocalDateTime, DateTime, List<Boolean>, List<Float>, List<Integer>, List<Number>, List<Point>, List<String>, List<Duration>, List<Date>, List<Time>, List<LocalTime>, List<LocalDateTime> or List<DateTime> (expected Node) (line 2, column 51 (offset: 212))
"match(per:Person)-[:REPOST]->(p:Post)<-[:CREATE]-(personX) return distinct per.FIO"

Solution

  • This should work:

    MATCH (:Person)-[r1:LIKE]->(:Post)<-[:CREATE]-(per2:Person)
    WITH per2, COUNT(r1) AS cnt
    ORDER BY cnt DESC
    LIMIT 1
    MATCH (per:Person)-[:REPOST]->(:Post)<-[:CREATE]-(per2)
    RETURN DISTINCT per.name
    

    Your first query needed to replace RETURN with WITH, so that the query did not end. And it also needed to pass per2 to the second MATCH.