GraphGists

使用 Cypher 和 Neo4j 的练习

创建脚本

完整图

查询

基本查询

  • 返回动物园中所有雄性动物。

match (n:Animal{sexo:"Macho"})
return n

结果

  • 返回年龄超过 40 岁的员工数量。

match(empleado:Empleado)
where empleado.edad > 40
return count(empleado) as `Cantidad empleados`

结果

中间查询

  • 返回与 Tadala 共用同一个兽医的所有动物。

Match(animal:Animal{name:"Tadala"})<-[:SE_ENCARGA_DE]-(veterinario:Empleado{puesto:"Veterinario"})
With veterinario
Match (veterinario)-[:SE_ENCARGA_DE]->(animal2:Animal)
Where animal2.name <> "Tadala"
Return animal2

结果

  • 返回名为 Clara 的员工负责的动物的后代。

Match (cuidador:Empleado{name:"Clara"})-[:SE_ENCARGA_DE]->(recinto:Recinto)<-[:HABITA]-(cria:Animal)-[:ES_HIJO_DE]->(animal:Animal)
Return distinct(cria)

结果

  • 返回没有分配兽医的后代。

Match (animal:Animal)<-[:ES_HIJO_DE]-(cria:Animal)
Where not (:Empleado{puesto:"Veterinario"})-[:SE_ENCARGA_DE]->(cria)
Return distinct(cria)

结果

高级查询

  • 返回由与照顾 Canela 的同一个饲养员照顾的动物,并且这些动物居住在不同的围场。也返回这些动物居住的围场。

match (animal:Animal{name:"Canela"})-[:HABITA]->(recinto:Recinto)<-[:SE_ENCARGA_DE]-(cuidador:Empleado{puesto:"Cuidador"})
with animal, recinto, cuidador
match (animal2:Animal)-[:HABITA]->(recinto2:Recinto)<-[:SE_ENCARGA_DE]-(cuidador)
where animal2.name <> "Canela"
and recinto <> recinto2
return distinct(animal2), recinto2

结果

  • 返回分组后的物种中具有伴侣、分配有兽医(其名称包含字母 'o')、且居住在可用状态围场中的动物的平均年龄。

match (recinto:Recinto)<-[:HABITA]-(animal:Animal)-[:ES_PAREJA_DE]->(animal2:Animal)-[:HABITA]->(recinto:Recinto)
where recinto.estado = "Disponible"
with animal, animal2
match (veterinario:Empleado{puesto:"Veterinario"})
where((animal)<-[:SE_ENCARGA_DE]-(veterinario)
or (animal2)<-[:SE_ENCARGA_DE]-(veterinario))
and veterinario.name CONTAINS 'o'
return distinct labels(animal)[1] as Especie, avg(animal.edad) as `Edad media`

结果