Amygdaloideum
Amygdaloideum

Reputation: 4923

Cypher: find node based on multiple relationship attributes

I want to make a query that find recipes containing all ingredients the user passed (an unknown amount).

I can find recipes based on one ingredient with this query:

MATCH (r:Recipe)-[:CONTAINS]->(i:Ingredient {name: 'carrot'})
RETURN r

For example, how would I find all recipes containing each of the following ingredients; carrot, pineapple, celery, tomato, ginger?

Upvotes: 0

Views: 548

Answers (2)

Gabor Szarnyas
Gabor Szarnyas

Reputation: 5057

Represent the required ingredients as a list, and use the ALL predicate to check if a recipe has all ingredients in the list. The trick is that as long as you don't introduce new variables, you can use patterns in conditions:

So, patterns are not only expressions, they are also predicates. The only limitation to your pattern is that you must be able to express it in a single path. You can not use commas between multiple paths like you do in MATCH. You can achieve the same effect by combining multiple patterns with AND.

Note that you can not introduce new variables here. [...]

This query returns every recipe that has all the ingredients you listed:

MATCH (r:Recipe)
WHERE ALL(
  ingredient IN ['carrot', 'pineapple', 'celery', 'tomato', 'ginger']
  WHERE (r)-[:CONTAINS]->(:Ingredient {name: ingredient})
)
RETURN r

I guess you'll pass the user input as a parameter:

MATCH (r:Recipe)
WHERE ALL(
  ingredient IN { ingredients }
  WHERE (r)-[:CONTAINS]->(:Ingredient {name: ingredient})
)
RETURN r

Upvotes: 3

cybersam
cybersam

Reputation: 67044

If you install a 3.1 version of the APOC library, you can use the apoc.coll.containsAll function. For example:

MATCH (r:Recipe)-[:CONTAINS]->(ing:Ingredient)
WITH r, COLLECT(ing.name) AS names
WHERE apoc.coll.containsAll(names, {ingredients})
RETURN r;

(If you install a 3.0 version of the library, apoc.coll.containsAll would be a procedure, and the query above would have to be modified accordingly.)

Upvotes: 1

Related Questions