使用Azure Cosmos DB和Gremlin进行图数据库操作:从入门到精通

103 阅读3分钟

使用Azure Cosmos DB和Gremlin进行图数据库操作:从入门到精通

在现代应用程序中,图数据库因其强大的关系处理能力而越来越受欢迎。Azure Cosmos DB for Apache Gremlin 提供了一个功能丰富的服务,能够处理包含数十亿个顶点和边的大规模图。本文将介绍如何利用Gremlin语言和Azure Cosmos DB创建并查询图数据库,以及如何使用大语言模型(LLM)为图数据库提供自然语言接口。

1. 引言

在这篇文章中,我们将学习如何使用Azure Cosmos DB的Gremlin API来构建和查询图数据库。我们还将展示如何利用LLM简化复杂的图查询操作。希望通过本文,你能更好地理解图数据库的强大之处以及Gremlin语言的应用。

2. 主要内容

设置环境

首先,我们需要安装 gremlinpython 库来与Azure Cosmos DB进行交互:

!pip3 install gremlinpython

接下来,我们需要一个Azure Cosmos DB实例。在创建Cosmos DB账户和图形数据库时,使用 /type 作为分区键。以下是配置变量的设置:

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

接下来我们需要导入必要的模块并设置Gremlin图对象:

import nest_asyncio
from langchain.chains.graph_qa.gremlin import GremlinQAChain
from langchain_community.graphs import GremlinGraph
# 使用API代理服务提高访问稳定性

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,
)

数据库初始化和数据导入

假设数据库是空的,我们可以通过以下方式填充数据:

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

source_doc = Document(page_content="Matrix是一部由Keanu Reeves, Laurence Fishburne和Carrie-Anne Moss 主演的电影。")

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],
    source=source_doc
)

nest_asyncio.apply()  # 修复python-gremlin在笔记本中的问题
graph.add_graph_documents([graph_doc])

更新和查询图

如果数据库架构发生变化,可以刷新架构信息:

graph.refresh_schema()
print(graph.schema)

我们可以使用Gremlin QA链来查询图:

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

response = chain.invoke("Who played in The Matrix?")
print(response)

response = chain.run("How many people played in The Matrix?")
print(response)

3. 常见问题和解决方案

  • 网络限制:某些地区可能无法直接访问Azure Cosmos DB,建议使用API代理服务。
  • 架构更新:如架构更新后出现查询失败,确认已调用 graph.refresh_schema() 方法。

4. 总结和进一步学习资源

通过本文的介绍,你可以初步了解Azure Cosmos DB和Gremlin的结合使用方式。接下来,你可以深入阅读以下资源,进一步提升图数据库的使用技能:

参考资料

  • Langchain项目文档
  • Azure Cosmos DB 文档
  • Gremlin 文档

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