Match node with multiple properties in neo4j - neo4j

I'm having troubles with the current data model and was wondering if anyone could suggest a better way to structure my data.
My nodes labelled 'Person' have 5-10 properties each like: Name, Address, Nationality, Phone, Age... And there is no unique property I could use as an Index.
Since I don't want duplicates, every time I create a new person I use MERGE instead than CREATE. But the problem is that doing a MERGE where I'm matching 5-10 properties on a node slows down the queries enormously.
So would taking out the properties in each Person node as separate nodes labeled Address, Nationality, Phone, Age help the performance of my MERGE query? Any other possible solutions?
Thanks in advance!

How about generating a GUID/UUID that's unique for each person and using that as your ID for each Person? Then you could MERGE on that property quickly and use ON CREATE to set the other properties e.g.
MERGE (p:Person {id: 'abcd-efgh-...'})
ON CREATE SET p.name = "mark", p.address = "..."
Or if not then maybe a hash or combination of all those properties as your key e.g.
MERGE (p:Person {id: "name-address-nationality-phone"})
ON CREATE SET p.name = "...", p.address = "..."

Related

Is there a way to make a relation when creating a node, on a certain condition? Cypher 3.5

I am new to Neo4j and graph databases.
I am looking for a way create a node while connecting it to another node matching that has a field that matches a certain parameter.
Here's a diagram to get the idea:
Let's say my parameter is :params {friendNodeId: 2}
In my Cypher query, I would like to create my new node with its field name: "my brand new node". Then if there is a node having uniqueId = $params.friendNodeId create a relation between this node and my new node.
My approach is to optimize the entire process by running a single query and not having to make an unnecessary match in a second query to get the newly created node.
If you think that it doesn't make sense at all don't hesitate to come up with another proposition.
Thanks for your help.
From your example in the comments, if the node creation is mandatory, but the relationship creation is optional (depending on if there is a node that matches), then you can just move the CREATE to before your MATCH:
CREATE (new:Node {uId: 4})
SET new.name = "name 4"
WITH new
MATCH (other:Node {uId: $uniqueId})
CREATE (new)-[r:FRIEND]->(other)
RETURN r

Neo4j storing multiple values as property and matching nodes based on that property

I have a label Person with nodes that have certain properties (forename, surname etc.) and I have a label Company with nodes with certain properties (name, companyNumber etc.). Now I need to add property compNumber to the person nodes which will indicate in which companies that person works.
My question is: Is there a way to put multiple values in the property compNumber, for example
(:Person {forename:John, surname'Smith', compNumber:[001,002,003]})
and later make a relationship WORKS_AT if the property companyNumber in Company node matches one of the values in compNumber property?
Or, will a better approach to store compNumber values as separate nodes be like:
(:Person {forename:John, surname:Smith})-[:HAS_NUMBER]->(:Number {compNumber:001})
(:Person {forename:John, surname:Smith})-[:HAS_NUMBER]->(:Number {compNumber:002})
(:Person {forename:John, surname:Smith})-[:HAS_NUMBER]->(:Number {compNumber:003})
Yes, you can do that in the way you want it. In Neo4j you can set an array property with following command:
CREATE (:Person {forename:'John', surname:'Smith', compNumber:[1,2,3]});
You can search for specific nodes with the IN keyword:
MATCH (n:Person) WHERE 1 IN n.compNumber RETURN n;
Then you can create relations in the following way:
MATCH (n:Company) MATCH (p:Person) WHERE n.companyNumber IN p.compNumber MERGE (p)-[:WORKS_IN]->(n);
I think this solution should fit you needs.

Neo4j query node property.

I have database with entities person (name,age) and project (name).
can I query the database in cypher that specifies me it is person or project?
for example consider I have these two instances for each :
Node (name = Alice, age= 20)
Node (name = Bob, age = 31)
Node (name = project1)
Node (name = project2)
-I want to know, is there any way that I just say project1 and it tells me that this is a project.
-or I query Alice and it says me this is a person?
Thanks
So your use case is to search things by name, and those things can be of several types instead of a single type.
Just to note, in general, this is not what Neo4j is built for. Typically in Neo4j queries you know the type of the thing you're searching for, and you're exploring relationships between that thing (or things) to figure out associations or data derived from that.
That said, there are ways to do this, though it's worth going through the rest of your use cases and seeing if Neo4j is really the best tool for what you're trying to do
Whenever you're querying by a property, you either want a unique constraint on the label/property, or an index on the label/property. Note that you need a combination of a label and a property for this; you cannot blindly ask for a node with a property without specifying a label and get good performance, as it will have to do a scan of all nodes in your database (there are some older manual indexes in Neo4j, but I'm not sure if these will continue to be supported; the schema indexes are recommended by the developers).
There is a workaround to this, as Neo4j allows multiple labels on the same node. If you only expect to query certain types by name (for example, only projects and people), you might create a :Named label, and set that label on all :Project and :Person nodes (and any other labels where it should apply). You can then create an index on :Named.name. That way your query would be something like:
MATCH (n:Named)
WHERE n.name = 'blah'
WITH LABELS(n) as types
WITH FILTER(type in types WHERE type <> 'Named') as labels
RETURN labels
Keep in mind that you haven't specified if a name should be unique among node types, so it could be possible for a :Person or a :Project or multiple :Persons to have the same name, unsure how that affects what should happen on your end. If every named thing ought to have a unique name, you should create a unique constraint on :Named.name (though again, it's on you to ensure that every node you create that ought to be :Named has the :Named label applied on creation).
You should use node labels (like Person and Project) to represent node "types".
For example, to create a person and a project:
CREATE (:Person {name: 'Alice', age: 20})
CREATE (:Project {name: 'project1'})
To find the project(s) named 'Fred':
MATCH (p:Project {name: 'Fred'})
RETURN p;
To get a collection of the labels of node n, you can invoke the LABELS(n) function. You can then look in that collection to see if the label you are looking for is in there. For example, if your Cypher query somehow obtains a node n, then this snippet would return n if and only if it has the Person label:
.
.
.
WHERE 'Person' IN LABELS(n)
RETURN n;
[UPDATED]
If you want to find all nodes with the name property value of "Fred":
MATCH (n {name: 'Fred'})
...
If you want to find all relationships with the name property value of "Fred":
MATCH ()-[r {name: 'Fred'})-()
...
If you want to match both in a single query, you have many ways to do that, depending on your exact use case. For example, if you want a cartesian product of the matching nodes and relationships:
OPTIONAL MATCH (n {name: 'Fred'})
OPTIONAL MATCH ()-[r {name: 'Fred'})-()
...

How to use cypher to create a relationship between items in an array and another node

I would like to use cypher to create a relationship between items in an array and another node.
The result from this query was a list of empty nodes connected to each other.
MATCH (person:person),(preference:preference)
UNWIND person.preferences AS p
WITH p
WHERE NOT (person)-[:likes]->(preference) AND
p = preference.name CREATE (person)-[r:likes]->(preference)
Where person.preferences contains an array of preference names.
Obviously I am doing something wrong. I am new to neo4j and any help with above would be much appreciated.
Properties are attributes of a nodes while relationships involve one or two nodes. As such, it's not possible to create a relationship between properties of two nodes. You'd need to split the properties into their own collection of nodes, and then create a relationship between the respective nodes.
You can do all that in one statement - like so:
create (:Person {name: "John"})-[:LIKES]->(:Preference {food: "ice cream"})
For other people, you don't want to create duplicate Preferences, so you'd look up the preference, create the :Person node, and then create the relationship, like so:
match (preference:Preference {food: "ice cream"})
create (person:Person {name: "Jane"})
create (person)-[:LIKES]->(preference)
The bottom line for your use case is you'll need to split the preference arrays into a set of nodes and then create relationships between the people nodes and your new preference nodes.
One thing....
MATCH (person:person),(preference:preference)
Creates a Cartesian product (inefficient and causes weird things)
Try this...
// Get all persons
MATCH (person:person)
// unwind preference list, (table is now person | preference0, person | preference1)
UNWIND person.preferences AS p
// For each row, Match on prefrence
MATCH (preference:preference)
// Filter on preference column
WHERE preference.name=p
// MERGE instead of CREATE to "create if doesn't exist"
MERGE (person)-[:likes]->(preference)
RETURN person,preference
If this doesn't work, could you supply your sample data and noe4j version? (As far as I can tell, your query should technically work)

Making a relation in neo4j

I am not sure what I am doing wrong here, so here is how I create nodes
CREATE (urlnode_1:UrlNode {url:'url1', nodenumber:1})
CREATE (urlnode_2:UrlNode {url:'url2', nodenumber:2})
I create relations as follows
CREATE
(urlnode_1)-[:OutLink {anchor_text:['MY']}]->(urlnode_2)
Two nodes are created successfully first, now on running the code to create the relation, I would have liked the relation to exist between the two created nodes but it creates two new nodes say 3 and 4 and shows a relation between them. What am i doing wrong here?
To guide you the best way I can, let's sum up some Neo4j basics concerning node and relationships creation :
A node can have one or more labels, labels are meaned to group the nodes by domain (User, Speaker, Company, etc..see a label as a table name for e.g. ). A node can also have properties.
A relationship can have only ONE type, relationships are organizing the graph. Relationships can also have properties.
To create a node, you can use the CREATE writing clause :
CREATE (n:Person {firstname: 'John'})
The CREATE statement will not check if other nodes with same label and properties already exists, it will just create a new node
Relationships can also be created with the same clause :
MATCH (n:Person {firstname: 'John'}), (p:Person {firstname: 'Pierre'})
CREATE (n)-[:KNOWS]->(p)
A complete pattern can also be created in one go :
CREATE (n:Person {name:'Chris'})-[:KNOWS]->(p:Person {name:'Oliver'})
REMINDER : CREATE will not check for existing nodes.
--- AND NOW MERGE ---
MERGE will lazily check for existing nodes, see him as a MATCH OR CREATE clause :
MERGE (n:Person {firstname:'Fred'})
If the node with label Person and firstname Fred does not exist, the node will be created, otherwise nothing will happen. This is where come the handy ON MATCH and ON CREATE mentionned by #joslinm .
If you run this query multiple times after the node creation, your graph will not change, if you know the http protocol, you can say that MERGE is an indempotent request.
Be aware that, MERGE will ensure that an entire pattern exist in the database, by creating it if it does not already exist, meaning that if you do MERGE with a complete pattern, the entire pattern will be looked up for existence, not a single node :
Say a node with label Person and name property with value 'John' already exist in the db :
MERGE (n:Person {name:'John'})
will not affect the graph
However :
MERGE (n:Person {name:'John'})-[:KNOWS]->(:Person {name:'Nathalia'})
A new John node will be created, because the entire pattern does not exist.
It is recommended to use MERGE incrementally :
MERGE (n:Person {name:'John'})
MERGE (p:Person {name:'Nathalia'})
MERGE (n)-[:KNOWS]->(p)
If you want to know more about the MERGE clause, I can highly recommend you this wonderful article from Luanne on GraphAware : http://graphaware.com/neo4j/2014/07/31/cypher-merge-explained.html
Chris
If you create a relationship, a new one will get created every single time. They are not inherently unique. It sounds like you'd rather be merging the relationship; i.e., if they relationship is there, match it, if not, create it.
The merge syntax for it is as follows:
MERGE (a:Node)-[:LIKES]->(b:Node)
ON
MATCH SET a.msg = 'I matched!'
ON
CREATE SET a.msg = 'I created!'
RETURN a
You can try it out here: http://console.neo4j.org/
You'll notice that first the msg will be "I created!" then after it matches, it will be "I matched!"

Resources