探索 Azure Cosmos DB for Apache Gremlin:轻松实现图形数据库查询

83 阅读2分钟

引言

Azure Cosmos DB for Apache Gremlin 是一项强大的图数据库服务,可用于存储巨大的图结构,具有毫秒级的查询延迟。本文将深入探讨如何利用现代语言模型(LLMs)为图数据库提供自然语言接口,并通过 Gremlin 查询语言进行查询。

主要内容

设置环境

首先,我们需要安装 gremlinpython 库。

!pip3 install gremlinpython

接下来,创建一个 Azure Cosmos DB 图形数据库实例。您可以在 Azure 上免费创建一个 Cosmos DB 图形数据库实例。创建帐户和图形时,使用 /type 作为分区键。

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

导入必要的库:

import nest_asyncio
from langchain.chains.graph_qa.gremlin import GremlinQAChain
from langchain_community.graphs import GremlinGraph
from langchain_community.graphs.graph_document import GraphDocument, Node, Relationship
from langchain_core.documents import Document
from langchain_openai import AzureChatOpenAI

# 使用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,
)

数据库初始化

假设您的数据库为空,我们可以使用 GraphDocuments 初始化数据。

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

# 处理 notebook 的异步问题
nest_asyncio.apply()

# 添加文档到 CosmosDB 图形数据库
graph.add_graph_documents([graph_doc])

刷新图结构信息

如果数据库的 schema 发生变化,可以刷新 schema 信息。

graph.refresh_schema()
print(graph.schema)

查询图形

使用 Gremlin QA Chain 提出自然语言问题。

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)

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

常见问题和解决方案

  • 问题:网络无法访问 API 端点?
    由于某些地区的网络限制,开发者可能需要考虑使用 API 代理服务来提高访问稳定性。

  • 问题:异步运行导致的错误?
    可以通过 nest_asyncio.apply() 来解决 notebook 环境下的异步问题。

总结和进一步学习资源

Azure Cosmos DB for Apache Gremlin 提供了一种强大的方式来存储和查询复杂的数据关系。结合 OpenAI 的自然语言处理能力,可以实现更直观的交互。建议阅读以下资源以获取更深入的理解:

参考资料

  1. Azure 官方文档
  2. Gremlin Language Reference

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

---END---