问题
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:
- Person: Berit, Object: cerials, Opinion: good
- Person: Arne, Object: cerials, Opinion: good
- Person: Albert, Object: cerials, Opinion: bad
- 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
回答1:
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
来源:https://stackoverflow.com/questions/33213191/how-to-do-nested-queries-in-neo4j