本文共 2474 字,大约阅读时间需要 8 分钟。
Cypher是Neo4j图数据库的查询语言,提供了强大的数据处理能力。以下是一些实用的Cypher代码示例和优化技巧,帮助您更高效地处理数据。
可以通过Cypher轻松导入CSV文件,例如Inventory.csv:
LOAD CSV WITH HEADERS FROM "file:///Inventory.csv" AS rowMERGE (s:Store {name: row.store})MATCH (c:City {name: row.store})MERGE (s)-[:IN_CITY]-(:City {name: row.store}) WITH *MATCH (p:Product {sku: row.sku})MERGE (s)-[:INVENTORY]->(p) SET p.count = toInt(row.number) RETURN * 此外,也可以使用apoc.load.json导入JSON文件:
CALL apoc.load.json("reviews.json") YIELD value AS rowMATCH (c:Customer {customerid: toString(row.customerid)})MATCH (p:Product {sku: toString(row.sku)})MERGE (c)-[:REVIEWED]->(:Product {sku: row.sku}) SET :rating = round(toFloat(row.review)) RETURN * 请确保启用apoc.import.file.enabled=true。
Cypher提供了algo.unionFind函数,用于节点聚类:
CALL algo.unionFind(label:String, relationship:String, {weightProperty: 'weight', threshold: 0.42, defaultValue: 1.0, write: true, partitionProperty: 'partition'}) YIELD nodes, setCount, loadMillis, computeMillis, writeMillis 参数说明:
label:节点类别relationship:关系类别,可选weightProperty:权重属性threshold:边界值defaultValue:默认值(为空时填充)write:是否写入结果如果需要并发处理,可以设置concurrency限制:
CALL algo.unionFind.stream('User', 'FRIEND', {weightProperty: 'weight', defaultValue: 0.0, threshold: 1.0, concurrency: 1}) YIELD nodeId, setIdRETURN algo.getNodeById(nodeId).id AS user, setId 使用detach确保引用关系被删除:
MATCH (n) DETACH DELETE n
查询数据库元数据:
CALL apoc.meta.graph == call db.schema()
MATCH (n {name: "John"}) - [:friend] -> (friend)WITH n, count(friend) AS friendsCountWHERE friendsCount > 3RETURN n, friendsCount MATCH (n {name: 'John'}) - [:friend] -> (friend)WITH n, count(friend) AS friendsCountSET n.friendsCount = friendsCountRETURN n.friendsCount MATCH (p:Person) - [:ACTED_IN] -> (m:Movie)WITH p, count(*) AS appearances, collect(m.title) AS moviesWHERE appearances > 1RETURN p, appearances, movies
使用OPTIONAL处理不匹配情况:
MATCH (p:Person) - [:ACTED_IN]->(m:Movie)WITH p, OPTIONAL MATCH (m2:Movie) - [:ACTED_IN]->(p)RETURN p, COLLECT(m.title) AS movies
查询所有图算法:
CALL dbms.procedures() YIELD name, signature, descriptionWHERE name starts with "algo" RETURN name, signature, description
查询APOC插件:
CALL dbms.procedures() YIELD name, signature, descriptionWHERE name starts with "apoc" RETURN name, signature, description
通过这些示例,您可以高效地处理数据,优化数据库性能,并利用Cypher的强大功能进行数据分析。
转载地址:http://wzru.baihongyu.com/