cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Return node with all nodes it's in relationship but some of the related nodes meet a condition

Hi,

I'm new to Neo4j so I might be doing it the wrong way!

I have a set of nodes called Recipe. Each Recipe is in a relationship with one or more Ingredient. Now I want to search for Recipes that contain a specific list of Ingredients.

For example, if my ingredient list in search criteria is "Asparagus", it must return "Scrambled Eggs with Asparagus" which contains Asparagus but also includes other ingredients that weren't in the search criteria.

I have this Cypher query and it returns the recipe correctly:

MATCH (n:Recipe)-[r:INGREDIENTS]->(m:Ingredient) where (m.name = 'Asparagus') return n,collect(r),collect(m);

3X_d_9_d914ae043942da388c0f2c0925d734506895a7d2.png

But my problem is that it only returns the Recipe node and the Asparagus node while I want it to return Recipe node with all of its ingredients. I tried "exists" but it returns the same result but slower!

Does anyone know what I can do?

Any help is much appreciated

1 ACCEPTED SOLUTION

mi stands for main Ingredients
si stands for second Ingredients

MATCH (mi:Ingredient)<-[:NEEDS]-(r:Recipe) WHERE mi.name IN ['Asparagus']
OPTIONAL MATCH (r)-[:NEEDS]->(si)
RETURN r AS recipe, collect(mi.name) + collect(si.name) AS ingredients

View solution in original post

2 REPLIES 2

mi stands for main Ingredients
si stands for second Ingredients

MATCH (mi:Ingredient)<-[:NEEDS]-(r:Recipe) WHERE mi.name IN ['Asparagus']
OPTIONAL MATCH (r)-[:NEEDS]->(si)
RETURN r AS recipe, collect(mi.name) + collect(si.name) AS ingredients

Perrrfect 🙂 Thanks

I think I didn't understand what OPTIONAL MATCH does when I was reading about it. Will go back to learn it