简体   繁体   中英

How to do nested queries in neo4j

Can't figure out how to do this in a good way in neo4j, so please help me.

I have Three types of objects: Person, Object, Opinion. I want to get a list of the latest opinions, the person who had the opinion, the object. This I can do, it's not difficult. My problem starts when I want to get the people that has opinions about the same objects in the same query.

This is the result I would like to have:

  1. Person: Berit, Object: cerials, Opinion: good
    • Person: Arne, Object: cerials, Opinion: good
    • Person: Albert, Object: cerials, Opinion: bad
  2. Person: Axel, cookbooks, awesome
    • Person: Arne, Object: cookbooks, Opinion: unnecessary
    • Person: Tove, Object: cookbooks, Opinion: bad
    • Person: Berit, Object: cookbooks, Opinion: bad

... And so on

You don't describe your relationship types, so I'll just make them up. Here is how you might start:

MATCH (target:Person)-[:HAS_OPINION]->(target_opinion:Opinion)-[:ON]->(object:Object)<-[:ON]-(other_opinion:Opinion)<-[:HAS_OPINION]-(other_person:Person)
WHERE target.id = {target_id}

The target could be based on id/name/whatever...

You could return the data in a couple of ways. It could be a denormalized result:

MATCH (target:Person)-[:HAS_OPINION]->(target_opinion:Opinion)-[:ON]->(object:Object)<-[:ON]-(other_opinion:Opinion)<-[:HAS_OPINION]-(other_person:Person)
WHERE target.id = {target_id}
RETURN target, target_opinion, object, other_opinion, other_person

Or you could return one target per row and collect all of the others up into an array of objects:

MATCH (target:Person)-[:HAS_OPINION]->(target_opinion:Opinion)-[:ON]->(object:Object)<-[:ON]-(other_opinion:Opinion)<-[:HAS_OPINION]-(other_person:Person)
WHERE target.id = {target_id}
RETURN
  target,
  target_opinion,
  object,
  collect({opinion: other_opinion, person: other_person}) AS others

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM