neo4j知识图谱构建代码示例
时间: 2024-12-28 21:29:09 浏览: 14
### 使用 Neo4j 构建知识图谱的代码示例
#### 创建节点和关系
为了展示如何使用 Neo4j 来构建一个简单的关系型知识图谱,下面提供了一个 Python 脚本的例子。此脚本利用 `py2neo` 库来连接到 Neo4j 数据库并执行 Cypher 查询语句。
```python
from py2neo import Graph, Node, Relationship
# 连接到本地运行的 Neo4j 实例
graph = Graph("bolt://localhost:7687", auth=("neo4j", "password"))
# 清除已有数据(仅用于测试环境)
graph.run("MATCH (n) DETACH DELETE n")
# 定义一些用户节点
users = [
{"name": "Alice"},
{"name": "Bob"},
{"name": "Charlie"}
]
# 插入用户节点至图数据库中
for user_data in users:
user_node = Node("User", **user_data)
graph.create(user_node)
# 同样定义商品节点
products = [
{"title": "Book A"},
{"title": "Movie B"},
{"title": "Game C"}
]
# 将商品节点加入图数据库
for product_data in products:
product_node = Node("Product", **product_data)
graph.create(product_node)
# 建立购买行为之间的关联
alice = next(graph.nodes.match("User", name="Alice"))
book_a = next(graph.nodes.match("Product", title="Book A"))
purchase_relationship = Relationship(alice, "BOUGHT", book_a)
graph.create(purchase_relationship)
bob = next(graph.nodes.match("User", name="Bob"))
movie_b = next(graph.nodes.match("Product", title="Movie B"))
purchase_relationship = Relationship(bob, "BOUGHT", movie_b)
graph.create(purchase_relationship)
charlie = next(graph.nodes.match("User", name="Charlie"))
game_c = next(graph.nodes.match("Product", title="Game C"))
purchase_relationship = Relationship(charlie, "BOUGHT", game_c)
graph.create(purchase_relationship)
```
这段代码展示了怎样通过编程方式向 Neo4j 中添加实体(即用户和产品),并通过建立两者间的 “购买” 关系形成基本的知识网络结构[^3]。
阅读全文