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.

the order of OPTIONAL MATCH changes the result

hello, first thanks for the great work:

i'm in a scenario where i need to capture user profiles that have common likes in a specific user's preferences i tried using MATCH but i would like results to be returned even if one of the calls to MATCH fails i also tried OPTIONAL MATCH but when it doesn't I have an optional relation at the beginning of the query, nothing is returned, here is my example code:

MATCH (p:Profile)-->(pref:Preferences)
OPTIONAL MATCH (pref:Preferences)--(:Gender)<--(p2)
OPTIONAL MATCH (pref:Preferences)--(:AstrologicalSign)--(p2)
OPTIONAL MATCH (pref:Preferences)--(:MusicalStyle)--(p2)
OPTIONAL MATCH (pref:Preferences)--(:Religion)--(p2)
OPTIONAL MATCH (pref:Preferences)--(:Smoke)--(p2)
RETURN a
(ps: sorry if I wasn't clear, English is not my native language)
7 REPLIES 7

glilienfield
Ninja
Ninja

The return value of 'a' is not defined. Can you provide a data model and/or sample data? Can you explain what you are trying to achieve? What value(s) do you want returned?

Sorry,  correct query is:

MATCH (p:Profile)-->(pref:Preferences)
OPTIONAL MATCH (pref:Preferences)--(:Gender)<--(p2)
OPTIONAL MATCH (pref:Preferences)--(:AstrologicalSign)--(p2)
OPTIONAL MATCH (pref:Preferences)--(:MusicalStyle)--(p2)
OPTIONAL MATCH (pref:Preferences)--(:Religion)--(p2)
OPTIONAL MATCH (pref:Preferences)--(:Smoke)--(p2)
RETURN p2

My goal is to return all Profiles that have matches, even if some relationship doesn't exist on either side

In your data model, are all the p2 nodes in the query supposed to be the same node?  If so, are the Gender, AstrologicalSign, MusicalStyle, Religion, and Smoke all the types of nodes the path can traverse through, or are there other types you don’t want the path to go through?  

Yes, I would like to return the p2:Profile that has or does not match with:
Gender, AstrologicalSign, MusicalStyle, Religion and Smoke
but if I put optional match and there is no relation, p2 is null, I would like to avoid this

Is the p2:Profile the same for Gender, AstrologicalSign, MusicalStyle, Religion and Smoke, or are they different based on those labels? 

I am confused when you state "p2:Profile that has or does not match". What do you mean by "does not match", what do you expect if it does not match?

Optional Match will return a null value if a match is not found.  That is the behavior.  What behavior do you want?

I am sorry I am not clear on your objectives.

I'm working on a dating app, where Profiles can have Preferences, like Gender, MusicalStyle and others, it works great when all Preferences of Profile have matches, but a Profile can match Gender but not MusicalStyle, so I want to bring the result anyway.

I updated the problem