Neo4j中Cypher语句记录

时间:2022-06-01 19:37:50

本文主要是一些常用的Cypher,由于时间的关系,没有进行规整,这是散乱的记录一下,以便查询。


1、将csv文件(结点、关系)载入neo4j

(1)载入并显示全部

LOAD CSV FROM "file:///test.csv" AS line
RETURN *;

(2)将csv中 结点载入,使用头文件,(推荐这种方式)-Merge控制保证所有记录不重复
USING PERIODIC COMMIT 1000     (这个是每1000次作为一个事务提交)
LOAD CSV WITH HEADERS FROM "file:///test.csv" AS line
MERGE (p:person{id:line.id,name:line.name,age:line.age})

(3)将csv中 关系载入,使用头文件
LOAD CSV WITH HEADERS FROM "file:///relation.csv" AS line
match (from:person{id:line.from_id}),(to:person{id:line.to_id})
merge (from)-[r:rel{property1:line.property1,property2:line.property2}]->(to)


(4)同时导入具有3种关系的csv文件

LOAD CSV WITH HEADERS FROM "file:///PersonRel2_Format.csv" AS line
match (from:person{id:line.from_id}),(to:person{id:line.to_id})
merge (from)-[r:r1{name:line.relation1,degree:line.r1_degree,score:line.r1_score}]->(to)
merge (from)-[rr:r2{name:line.relation2,evaluate:line.r2_evaluate}]->(to)
merge (from)-[rrr:r3{name:line.relation3}]->(to)

(本博客关于csv文件导入的讲解不多,主要是语句,具体导入方法详见:http://blog.csdn.net/quiet_girl/article/details/71155442)



2、删除结点及关系

(1)删除所有结点和关系:

MATCH (n)
OPTIONAL MATCH (n)-[r]-()
DELETE n,r

(2)删除"name"值为“小兔子”的结点及其关系。
match (n)
where n.name="小兔子"
optional match (n)-[r]-()
delete n,r



3、查询结点和关系

(1)查询所有结点

START n=node(*)
return n;


(2)若需要返回2个节点及其之间的所有关系(like是pf1->pf2之间的其中一个关系)

MATCH (pf1)-[like:LIKES]->(pf2)
RETURN pf1,pf2;


4、创建结点和关系

MATCH (e:Customer),(cc:CreditCard) 
CREATE (e)-[r:DO_SHOPPING_WITH ]->(cc)
RETURN r(若不能正确返回,将RETURN r 替换为 RETURN e,cc即可)



5、关于索引

(1)建立索引(效率将会很大提高)
cypher建schema Index:

CREATE INDEX ON :Person(name);

(2)使用schema Index索引:
MATCH (p:Person {name: 'Stefan'}) RETURN p

MATCH (x:Person{name:"john", surname:"doe"})
USING INDEX x:Person(name)
USING INDEX x:Person(surname)

(3)删除索引:
DROP INDEX ON :Person(name)

(4)查看索引:
:schema


6、若涉及优化,可以使用neo4j import命令