arslan
arslan

Reputation: 2224

How to find a list of nodes by two conditions in cypher?

I have 3 kinds of nodes: tag, city and place.

I want to write a query which takes 2 lists

 [tag1,tag2,....]

and

 [city1,city2,....].

I want to find a list of places located in one of these cities and order them from the one has as much tags as possible to the ones with fewer tags.

 MATCH (spot:Spot)-[:located_at]->(city:City ) 
 where city.id IN ["22","23"]
 with spot as sp,city as cy
 MATCH (sp:Spot)-[rels:tagged_by]->(tag:Tag)
 where tag.id IN ["16", "10151", "21"]
 with sp as fsp, tag
 RETURN fsp, tag,    count(distinct fsp.id) AS cnt
 order by cnt desc

I tried that query and somehow could not list the nodes and their tags.

Please help! Thanks in advance!

Upvotes: 0

Views: 277

Answers (3)

arslan
arslan

Reputation: 2224

I did it by the following. My mistake was not knowing to count relationships and not knowing proper using of aggregation.

 match (city:City)<-[]-(spot:Spot) 
 where city.id in ["22","23"] 
 match (spot)-[rel]->(tag:Tag) 
 where tag.id in ["16", "10151", "21"] 
 return spot, count(rel) as rel_count 
 order by rel_count desc limit 100

This worked as I wanted.

Upvotes: 1

Tomaž Bratanič
Tomaž Bratanič

Reputation: 6514

How I would approach this problem is.

MATCH (spot:Spot)-[:located_at]->(city:City)
RETURN city,spot,size(spot-[:tagged_by]->()) as tags order by tags desc

so now you get all the spots with the most tags. Obviously you can add filters how you want

MATCH (spot:Spot)-[:located_at]->(city:City) where city.name = "London"
RETURN city,spot,size(spot-[:tagged_by]->())  as tags order by tags desc

Upvotes: 0

Priyank Mehta
Priyank Mehta

Reputation: 2513

Try the subquery apporach:

Pick city - > find spots -> find tags for that spot

MATCH (city:City)
OPTIONAL MATCH (spot:Spot)-[:located_at]->(city) 
OPTIONAL MATCH (spot)-[rels:tagged_by]->(tag:Tag)
where city.id IN ["22","23"]
where tag.id IN ["16", "10151", "21"]
RETURN spot, tag, count(distinct fsp.id) AS cnt
order by cnt desc

Upvotes: 0

Related Questions