Neo4j

202292172629

节点与关系都可以有属性,也就是KV对

创建关系的同时需要列出源节点与目标节点

CREATE ()-[:ACTED_IN {roles: ['Forrest'], performance: 5}]->()

neo4j 不强制要求schema

命名公约

Cypher

// 一个标签为Movie叫matrix的节点 有title released两个属性(matrix:Movie {title: 'The Matrix', released: 1997})// 一个类型为ACTED_IN叫role的关系 有 roles一个属性-[role:ACTED_IN {roles: ['Neo']}]->

语法

MATCH

// 创建一个节点CREATE (:Movie {title: 'The Matrix', released: 1997})// 创建节点与关系CREATE (cxk:Person {name: "蔡徐坤", playAge: "两年半"})-[:PLAYED_IN {name: "打"}]->(ball:Basketball {name: "篮球"})CREATE (cxk)-[:SING_IN {name: "rap"}]->(song:Song {name: "鸡你太美"})RETURN cxk,ball,song
// 查询所有标签为Person的节点MATCH (p:Person) RETURN p// 查询指定属性满足的节点MATCH (p:Person {name: "蔡徐坤"}) RETURN p// 查询指定节点关系MATCH (p:Person)-[:SING_IN]->(s:Song) RETURN p,s
// 创建新关系MATCH (p: Person)CREATE (p)-[:LIVE_IN]->(:Earth)// 不存在就创建 存在就更新 在大图里,这种操作需要扫描大量节点,即使加上索引或约束,仍有一定开销MERGE (p: Person {name: "蔡徐坤2号"})ON CREATE SET p.age = 18RETURN p// MERGE 关系MATCH (p: Person {name: "蔡徐坤2号"})MATCH (b: Basketball)MERGE (p)-[:PLAYED_IN]->(b)
// 查询身份证为xxx 的 PERSON 与 PERSON、THING拥有rytcx、yysj最多二度关系的图MATCH (p:PERSON  {fq_gmsfhm: "350500196306111518"})<-[:rytcx|yysj*..2]->(n) WHERE (n: PERSON OR n: THING)RETURN p,n// 查询身份证为xxx 的 PERSON到手机号为17750052235的THING之间的路径MATCH p=(n: PERSON {fq_gmsfhm: "350521195607060010"})-[*]->(m: THING {sjhm: "17750052235"})RETURN p

UNION

MATCH (p: Person)RETURN p as aUNIONMATCH (b: Basketball)RETURN b as a

WITH

在WITH中定义变量,只有这些变量,才会被传递到下一个查询中

MATCH (p: Person)WITH DISTINCT p.name AS name// RETURN p 找不到pRETURN name

CASE

MATCH (p: Person {name: "蔡徐坤"})RETURN CASE p.age    WHEN 18 THEN "两年半"    WHEN 20 THEN "四年半"    ELSE "UNKNOW"ENDMATCH (p: Person {name: "蔡徐坤"})WITH p,CASE p.age    WHEN p.age IS NULL THEN "UNKNOW"    WHEN p.age = 18 THEN "两年半"END AS aRETURN a

子查询

// 存在子查询MATCH (p: Person)WHERE exists((p)-[:PLAYED_IN]->(:Basketball))RETURN p// 结果返回子查询CALL {    MATCH (p: Person)    RETURN p as a    UNION    MATCH (b: Basketball)    RETURN b as a}RETURN a.name

索引

为提升图的遍历性能,某些情况下使用索引是有必要的

// 根据姓名创建索引CREATE INDEX cxk_index FOR (p: Person) ON (p.name)// 查看有哪些索引SHOW INDEXES

约束

// 强制要求字段唯一CREATE CONSTRAINT constraint_example_1 FOR (movie:Movie) REQUIRE movie.title IS UNIQUE// 查看有哪些约束SHOW CONSTRAINTS

参数

MATCH (p: Person {name: $name})

操作符

聚合操作符
// 去重MATCH (p: Person)RETURN DISTINCT p.name
属性操作符
RETURN p["name"] // 等同于p.name// 添加属性MATCH (p:Person {name: "蔡徐坤2号"})SET p+= {gender: "female"}
比较运算符
// betweenMATCH (n) WHERE 21 < n.age <= 30 RETURN n// 排序MATCH (p:Person)RETURN p ORDER BY p.name
使用正则表达式
MATCH (p:Person) WHERE p.name =~ '.徐.'RETURN p
日期时间操作
WITH date({year: 2022, month:9, day: 21}) AS a,duration({days: 9}) AS bRETURN a-b
列表操作
// 连接RETURN [1,2,3,4,5] + [6,7]// 包含RETURN 1 IN [1,2,3]// 切片RETURN [1,2,3,4,5][1..3]

空间数据类型

// 84坐标系WITH point({latitude: 24, longitude: 118}) AS p1,point({latitude: 25, longitude: 117}) AS p2RETURN point.distance(p1,p2)/1000 + 'km'// 笛卡尔坐标系WITH point({x:1,y:2}) AS p1, point({x:3,y:4}) AS p2RETURN point.distance(p1,p2)