notANerdDev
notANerdDev

Reputation: 1286

Neo4j Query - Find all nodes which satisfy a property condition and have relationship

I have a query which runs successfully:

match (n:A {tag_no:"N2203"})<-[:rel_a]-(v:B)-[:rel_b]->(r)<-[:rel_c]-(n) WHERE (v.invoice_date>="2012-08-01" AND v.invoice_date<"2016-02-01") with v, collect(r) as rs where all (x in rs where x.date<"2016-08-01") return count(v) as count;

I need to further filter this query.

I need to related r nodes with max(r.date) for each v, and find out how many of those nodes have a relationship with another node of type D

I'm trying this query, it throws a syntax error

match (n:A {tag_no:"N2203"})<-[:rel_a]-(v:B)-[:rel_b]->(r)<-[:rel_c]-(n) WHERE (v.invoice_date>="2012-08-01" AND v.invoice_date<"2016-02-01") with v, max(r.date) as date collect(r) as rs where (all (x in rs where x.date<"2016-08-01") AND filter(x in rs where x.date=date)[0]<-[:rel_c]-(d:D)) return count(v) as count;

I also tried many other combinations, but all throw some syntax error. All help is appreciated.

Upvotes: 1

Views: 768

Answers (1)

Gabor Szarnyas
Gabor Szarnyas

Reputation: 5057

The main issue is that query parser cannot now if filter(x in rs where x.date=date)[0] really is a node, so this is not allowed in the syntax. Fortunately, it's possible to work around this at the cost of some verbosity:

  • Use another WITH clause to introduce an alias (n) to the node variable. That will allow you to use the WHERE <pattern> syntax.
  • Also, you cannot introduce new variables in the WHERE clause, so just use (:D) instead of (d:D).

So the query will look like this (obviously, I have not tested it):

MATCH (n:A {tag_no:"N2203"})<-[:rel_a]-(v:B)-[:rel_b]->(r)<-[:rel_c]-(n)
WHERE v.invoice_date>="2012-08-01"
  AND v.invoice_date<"2016-02-01"
WITH
  v,
  max(r.date) AS date,
  collect(r) AS rs
WHERE all(x IN rs WHERE x.date<"2016-08-01")
WITH filter(x in rs where x.date=date)[0] AS n, v
WHERE (n)<-[:rel_c]-(:D)
RETURN count(v) AS count;

Upvotes: 1

Related Questions