flowchart TD
A[下载Neo4j] --> B{选择版本}
B -->|社区版| C[下载Community Edition]
B -->|企业版| D[下载Enterprise Edition]
C --> E[安装Neo4j]
D --> E
E --> F[启动Neo4j服务]
F --> G[访问Neo4j Browser]
// 创建关系 MATCH (p:Person), (m:Movie) WHERE p.name = 'Sandra Bullock' AND m.title IN ['Speed', 'Speed 2: Cruise Control'] CREATE (p)-[:ACTED_IN {role: CASE m.title WHEN 'Speed' THEN 'Annie Porter' WHEN 'Speed 2: Cruise Control' THEN 'Annie Porter' END}]->(m)
更新属性
1 2 3 4
// 更新电影属性 MATCH (m:Movie {title: 'The Matrix'}) SET m.tagline = 'Free your mind' RETURN m.title, m.tagline
删除节点和关系
1 2 3 4 5 6 7
// 删除关系 MATCH (p:Person {name: 'Keanu Reeves'})-[r:ACTED_IN]->(m:Movie {title: 'Speed 2: Cruise Control'}) DELETE r
// 删除节点(需先删除关联关系) MATCH (m:Movie {title: 'Speed 2: Cruise Control'}) DETACH DELETE m
数据导入与导出
导入CSV数据
1 2 3
// 从CSV导入电影数据 LOAD CSV WITH HEADERS FROM 'file:///movies.csv' AS row CREATE (:Movie {id: toInteger(row.movieId), title: row.title, year: toInteger(row.year)})
CSV文件示例(movies.csv):
1 2 3 4
movieId,title,year 1,The Shawshank Redemption,1994 2,The Godfather,1972 3,The Dark Knight,2008
# 使用Cypher导出结果为CSV MATCH (m:Movie) RETURN m.title, m.released ORDER BY m.released DESC LIMIT 100
高级功能与最佳实践
使用索引优化查询性能
1 2 3 4 5 6 7 8 9 10 11
// 创建索引 CREATE INDEX movie_title FOR (m:Movie) ON (m.title)
// 创建复合索引 CREATE INDEX person_name_born FOR (p:Person) ON (p.name, p.born)
// 查看索引 SHOW INDEXES
// 删除索引 DROP INDEX movie_title
事务处理
1 2 3 4 5 6 7 8 9 10 11 12 13
// 开始事务 BEGIN
// 执行多个操作 CREATE (m:Movie {title: 'The Matrix 4', released: 2021}) MATCH (p:Person {name: 'Keanu Reeves'}) MATCH (m:Movie {title: 'The Matrix 4'}) CREATE (p)-[:ACTED_IN {role: 'Neo'}]->(m)
// 提交事务 COMMIT // 或回滚事务 // ROLLBACK
常见性能优化技巧
使用参数化查询:防止Cypher查询缓存失效
1 2 3 4 5 6
// 不好的做法 MATCH (p:Person {name: 'Keanu Reeves'}) RETURN p
// 好的做法 - 使用参数 MATCH (p:Person {name: $name}) RETURN p // 参数: {name: 'Keanu Reeves'}
避免大型结果集:使用LIMIT限制结果数量
1 2
// 限制结果数量 MATCH (m:Movie) RETURN m LIMIT 10
使用EXPLAIN和PROFILE分析查询
1 2 3 4 5
// 查看查询计划 EXPLAIN MATCH (p:Person)-[:ACTED_IN]->(m:Movie) RETURN p.name, m.title
// 执行并分析查询 PROFILE MATCH (p:Person)-[:ACTED_IN]->(m:Movie) RETURN p.name, m.title
常见问题解答
连接问题
graph TD
A[连接失败] --> B{检查Neo4j服务}
B -->|未启动| C[启动服务]
B -->|已启动| D{检查连接配置}
D -->|配置错误| E[修改neo4j.conf]
D -->|配置正确| F{检查防火墙}
F -->|阻止连接| G[开放端口7474和7687]
# 定义查询函数 defget_movies(tx): result = tx.run("MATCH (m:Movie) RETURN m.title, m.released ORDER BY m.released DESC LIMIT 5") return [{"title": record["m.title"], "released": record["m.released"]} for record in result]
# 创建会话并执行查询 with driver.session() as session: movies = session.read_transaction(get_movies) for movie in movies: print(f"{movie['title']} ({movie['released']})")