添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Neo4j 插件APOC使用示例(九)执行复杂cypher

  1. 独立运行多个cypher并将结果合并
  • 统计每一类label的数量:
CALL db.labels() yield label
CALL apoc.cypher.run("match (:`"+label+"`) return count(*) as count", null) yield value
return label, value.count as count


  • 统计每一类label的属性key:
CALL db.labels() yield label
CALL apoc.cypher.run("MATCH (n:`"+label+"`) RETURN keys(n) as keys LIMIT 1",null) yield value
RETURN label, value.keys as keys


2. 在set和remove中执行包含动态值的cyper

    • 假设数据为:
CREATE (:PERSON)
CREATE (:EVENT)
CREATE (:TAG)
CREATE (:LOCATION);
 
  • 下面的例子将label修改为只有首字母大写
CALL db.labels()
YIELD label
RETURN apoc.text.capitalize(toLower(label)) AS value;
  • 但这只是改变了返回的字符串,并没有修改数据库中node的label
  • 需要将原来的node设置为新label,并删除旧的label
MATCH (node)
WITH node, labels(node)[0] AS label
CALL apoc.cypher.doIt(
 "WITH $node AS node
 REMOVE node:" + label + "\n" +
 "SET node:" + apoc.text.capitalize(toLower(label)) + "\n" +
 "RETURN node",
 {node: node})
YIELD value
RETURN value;

3. 在movie DB上运行包含动态值的cypher

    • 查询每个label的node数量
CALL db.labels()
YIELD label
CALL apoc.cypher.run("MATCH (:" + label + ") RETURN count(*) AS count", {})
YIELD value
RETURN label, value.count AS count;
 
  • 查询每种关系的类型和数量
CALL db.relationshipTypes()
YIELD relationshipType
CALL apoc.cypher.run("MATCH ()-[:" + relationshipType + "]->() RETURN count(*) AS count", {})
YIELD value
RETURN relationshipType, value.count AS count;

4. 运行多个cypher语句,并将结果合并

CALL apoc.cypher.runMany(
 'CREATE (n:Node {name:$name});
 MATCH (n {name:$name})
 CREATE (n)-[:X {name:$name2}]->(n);',
 {name:"John", name2:"Doe"}
 


5. 运行嵌套的动态cypher,并将子查询的第一列返回

CALL db.labels()
YIELD label
RETURN label,
 apoc.cypher.runFirstColumnMany(
 "MATCH (n:`" + label + "`)
 WITH DISTINCT keys(n) AS keys
 RETURN DISTINCT apoc.coll.sort(keys)",
 {}) AS keys;

6. 运行单条cypher语句,并将子查询的第一列返回

CALL db.relationshipTypes()
YIELD relationshipType
RETURN relationshipType,
 apoc.cypher.runFirstColumnSingle("MATCH ()-[:" + relationshipType + "]->() RETURN count(*)", {}) AS count;

7. 根据条件执行cypher语句,进行读或者写操作

    • 将一跳或者两跳的邻居node中数目较多的一跳节点返回(when 类似于三目运算符,更复杂情况用apoc.case):
MATCH (start:Node)-[:REL]->(a)-[:REL]->(b)
WITH collect(distinct a) as aNodes, collect(distinct b) as bNodes
CALL apoc.when(
 size(aNodes) <= size(bNodes),
 'RETURN aNodes as resultNodes',
 'RETURN bNodes as resultNodes',
 {aNodes:aNodes, bNodes:bNodes})
YIELD value
RETURN value.resultNodes as resultNodes

8. 指定cypher运行时间,都时间后立即结束并将结果返回

CALL apoc.cypher.runTimeboxed(