How to add relation correctly to neo4j (cypher)? - neo4j

I tried add relation to neo4j and it doesn't work correctly... (this relations don't exist after executing script)...
my script (i run it in this way: Neo4jShell.bat -file gf.txt) :
CREATE (j1 { lc :1, ln: 'ln1' });
CREATE (j2 { lc :2, ln: 'ln2' });
CREATE (j3 { lc :3, ln: 'ln3' });
...
CREATE (p1 { pc : 1, pn : 'pn1'});
CREATE (p1 { pc : 2, pn : 'pn2'});
CREATE (p1 { pc : 3, pn : 'pn3'});
...
CREATE (j1)-[:F]->(p1);
CREATE (j2)-[:F]->(p2);
CREATE (j3)-[:F]->(p3);
Are you seeing any mistakes in my big script ?

Once you end your statement with a semicolon, you can't refer to the identifiers/nodes created in that statement anymore. It's not going to know what (j1) is, so it's going to create a new node (j1) with no properties.
Update:
Either remove your semicolons, or you'll need to MATCH the nodes again.

Related

How to verify if a node exist and if not exist then a created during an import of .csv to neo4j

I am importing some .cvs files for my database in neo4j, but I have the data of people in three different files, so when I import the data of the person from another file that has more data, I get an error when trying to import people nodes, because I already have other nodes with those dni (constraint) in my database.
So I want to create the new node or, if it exists, retrieve its pointer to create relationships with other nodes that I keep creating while I import.
I have tried several things on the internet but I still can't find the solution
Here my code:
LOAD CSV WITH HEADERS FROM 'file:/D:/ACCOUNT.csv' AS line FIELDTERMINATOR ';'
MERGE (persona :Persona { dni: line.DNI,
nombre: line.NOMBRE,
sexo: line.SEXO,
fechaNacimiento: line.FNACIMIENTO,
direccion: line.DIRECCION
})
I have tried with apoc and "with" but I still can't find the solution.
when this code finds another node with a person label and ID equal to the one entered, it gives me an error
To get this working, you'll have to understand how MERGE works. The statement
MERGE (persona :Persona { dni: line.DNI, nombre: line.NOMBRE, sexo: line.SEXO,
fechaNacimiento: line.FNACIMIENTO,direccion: line.DIRECCION
})
will create a new Persona node for every distinct combination of the above properties. So, for a node with the same dni, but with other values of other properties, this will fail. To fix this, you should try merging the nodes on the basis of their dni, and then set the properties like this:
MERGE (persona :Persona { dni: line.DNI })
ON CREATE
SET persona.nombre = line.NOMBRE,
persona.sexo = line.SEXO,
persona.fechaNacimiento = line.FNACIMIENTO,
persona.direccion = line.DIRECCION
The above query will ignore setting properties if a matching node is found. To set some properties when a match is found, use ON MATCH, like this:
MERGE (persona :Persona { dni: line.DNI })
ON CREATE
SET persona.nombre = line.NOMBRE,
persona.sexo = line.SEXO,
persona.fechaNacimiento = line.FNACIMIENTO,
persona.direccion = line.DIRECCION
ON MATCH
// Matching logic here

Creating multiple nodes in one neo4j CREATE statement

Create (sub:Subscription {name:"Paul",mobile:"8763xxxxx",email:"info#aliant.com"}),
Create (sub:Subscription {name:"Peter",mobile:"87638xxxxx",email:"info#aliant.com"}),
Create (sub:Subscription {name:"James",mobile:"87638xxxxx",email:"info#aliant.com"}),
Create (sub:Subscription {name:"Bill",mobile:"87638xxxxx",email:"info#aliant.com"})
Return sub;
I am very new to Neo4j/Cypher.....Why do I get an "unexpected "C" error on the second Create. I am using 2.3.2 community edition. The manual says this should would work...I also tried the parameter example section 12.1 in the manual it doesn't work either.
The commas are illegal - this form works:
Create (sub1:Subscription {name:"Paul",mobile:"8763xxxxx",email:"info#aliant.com"})
Create (sub2:Subscription {name:"Peter",mobile:"87638xxxxx",email:"info#aliant.com"})
Create (sub3:Subscription {name:"James",mobile:"87638xxxxx",email:"info#aliant.com"})
Create (sub4:Subscription {name:"Bill",mobile:"87638xxxxx",email:"info#aliant.com"})
Return sub1, sub2, sub3, sub4
If the you don't need a value back, then this will just create the nodes:
Create (:Subscription {name:"Paul",mobile:"8763xxxxx",email:"info#aliant.com"})
Create (:Subscription {name:"Peter",mobile:"87638xxxxx",email:"info#aliant.com"})
Create (:Subscription {name:"James",mobile:"87638xxxxx",email:"info#aliant.com"})
Create (:Subscription {name:"Bill",mobile:"87638xxxxx",email:"info#aliant.com"})
Try this:
UNWIND [{name:"Paul",mobile:"8763xxxxx",email:"info#aliant.com"}, {name:"Peter",mobile:"87638xxxxx",email:"info#aliant.com"}] as subscriptions
CREATE (sub:Subscription)
SET sub=subscriptions
Or this:
[Note: This syntax is deprecated in Neo4j version 2.3. It may be removed in a future major release. See the above code using UNWIND for how to achieve the same functionality.
]:
{
"subscriptions" : [ {
"name" : "A",
"email" : "a#b.c"
}, {
"name" : "B",
"email" : "x#y.z"
} ]
}
Create (sub:Subscription: {subscriptions}) Return sub
See, if that helps, or Refer this link.

Create a relationship only if a similar one exist - neo4j

I have a linked list such that every node has a 'next' relation pointed to the next node, the first node has another relation : 'first' which pointed to it from some category. I'm trying to write a delete function that uses cypher to do so but I keep getting this error :
Received an unexpected HTTP status when executing the request.
The query was: MATCH (c:Cat {id:{id}})-[:Post]->(p:Post{id:{pid}})
My try :
gclient.Cypher
.Match("(c:Cat {id:{id}})-[:Post]->(p:Post{id:{pid}})")
.Match("(p)-[nn:next]->(np:Post)")
.OptionalMatch("(c)-[old:first]->(p)")
.OptionalMatch("(ppost:Post)-[pn:next]->(p)")
.WithParams((new
{
id = catId,
pid = postId
}))
.Create("(ppost)-[:next]->(np)")
.With("old, p, c, np")
.Where("old IS NOT NULL")
.Create("(c)-[:first]->(np)")
.With("p, old")
.Delete("old")
.Delete("p")
.ExecuteWithoutResults();

Neo4j Relationships not showing connecting lines in the graph

I created the following nodes and relationship in neo4j
CREATE (United_States:Citizenship { type : “Naturalized”})
CREATE (United_States:Citizenship { type : “Native_Born”})
CREATE (uid:Person { unique_id: 'A23AF39D-BEED-4FFC-B080-1362920FA7A8', id_type: '128bit_UUID' })
MATCH (uid:Person),(Native_Born:Citizenship) WHERE uid:Person="A23AF39D-BEED-4FFC-B080-1362920FA7A8" CREATE (uid) <- [ r:PersonUniqueIdentifier ] -> (Native_Born)
CREATE (fn:Person { first_name:'Willie', id_type:'128bit_UUID'})
CREATE (ln:Person { last_name:'Armstrong', id_type:'128bit_UUID'}))
CREATE CONSTRAINT ON (uid:Person) ASSERT Person.unique_id IS UNIQUE
CREATE INDEX ON :Person(unique_id)
I do not see the 'PersonUniqueIdentifier' Relation between the Citizenship node and id:Person node on the graph.
Screen shot of graph
Firstly, I would make a habit of doing the indexes/constraints first. There's not a lot of data here, but if you add an index after adding the data, it will need to go through all your nodes first. Also, creating a constraint also adds an index for you, so no need for that line. It seems like you're mixing up variables here, so refactoring a bit:
CREATE CONSTRAINT ON (person:Person) ASSERT person.unique_id IS UNIQUE
Also your Citizenship CREATEs are using the same variable name. I don't know if that would necessarily cause a problem, but it's simpler to do this anyway:
CREATE (:Citizenship { type : “Naturalized”}), (:Citizenship { type : “Native_Born”})
This statement looks fine to me (though, again, you could lose the variable if you wanted to):
CREATE (person:Person { unique_id: 'A23AF39D-BEED-4FFC-B080-1362920FA7A8', id_type: '128bit_UUID' })
Here there are a few problems. Here's how I would refactor it:
MATCH (person:Person),(citizenship:Citizenship)
WHERE
person.unique_id="A23AF39D-BEED-4FFC-B080-1362920FA7A8",
citizenship.type = 'Native_Born'
CREATE (person)-[:HAS_CITIZENSHIP]->(citizenship)
I'm not really sure what you want to do here. It seems like you want to create one person, so I would do this:
CREATE (:Person { first_name:'Willie', id_type: '128bit_UUID', last_name:'Armstrong'})

py2neo create function creating duplicate nodes

I have a Neo4j database containing information on Congressmen. The problem I'm having is if there is a vacant position. When this happens I am using the same key:value in the "Congressmen" index. I tried the code below because in the py2neo documentation it states that the add function is idempotent
#Check if we have any vacancies and if so if they match the one that we currently want to add
query="start n=node:Congressmen('website:N/A') return n"
result= cypher.execute(graph_db, query.encode('utf-8', errors='ignore'))
#Match what we already have
if str(result[0]) != "[]":
#create is idempotent so will only create a new node if properties are different
rep, = graph_db.create({"name" : userName, "website" : web, "district" : int(district), "state" : child[2].text, "party" : child[4].text, "office" : child[5].text, "phone" : child[6].text, "house" : "House of Representatives"})
cong = graph_db.get_or_create_index(neo4j.Node, "Congressmen")
# add the node to the index
cong.add("website", web, rep)
When I checked the interface after running the code 3 times I have duplicate nodes.
Is it possible to prevent the nodes from duplicating and still be able to index them using the same key/value?
The Index.add method is certainly idempotent: the same entity can only be added once to a particular entry point. The GraphDatabaseService.create method is not however. Each time you run the create method, a new node is created and each run of add appends that new node to the index. You probably want to use the Index.add_if_none, Index.create_if_none or Index.get_or_create method instead.

Resources