How to fetch pattern variable with node and relationships (if present)

How to fetch pattern variable with node and relationships (if present)



Suppose, we have the following data in neo4j DB ->



enter image description here



The java entity representation is as follows ->


@NodeEntity
public class Place
@Id
@GeneratedValue
private Long id;

private String name;


@NodeEntity
public class Monument
@Id
@GeneratedValue
private Long id;

private String name;


@NodeEntity
public class Person
@Id
@GeneratedValue
private Long id;

private String name;

@Relationship(type = "VISITED", direction = Relationship.OUTGOING)
private Monument monument;

@Relationship(type = "STAYS", direction = Relationship.OUTGOING)
private Place place;



Now, I want to fetch all persons also populating the linked place and monument, if present. This means, the cypher query will not only provide me List< Person> as result and the Monument and Place object should also be linked with each Person object, if the links are available (and otherwise null).
To clarify it further, for Person 'Ron', I should be able to see the monument he visited and the place he stays, without performing any more queries to fetch the relationships. Similarly, for Person 'April', I should be able to see where she stays, but will not know which monument she visited because there is no link there.



With my basic knowledge in Cypher Query language, I have tried but could not get the desired result.



MATCH
p=(place:Place)<-[STAYS]-(person:Person)-[VISITED]->(monument:Monument) RETURN p



MATCH p=(person:Person)-[STAYS]->(place:Place) RETURN p



MATCH p=(person:Person) RETURN p



I could not find a query where I get all of these.




1 Answer
1



You need to put the relations into optional matches, like this:


MATCH (person:Person)
OPTIONAL MATCH (person)-[:VISITED]->(monument)
OPTIONAL MATCH (person)-[:STAYS]->(place)
return person, place, monument



Otherwise, neo4j treats the relations in your query 1) as required, that's why 'Ron' will be the only result.





Thanks. It worked.
– ronojoy ghosh
Aug 23 at 18:12






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế