使用LLMs将自然语言转化为NebulaGraph查询:快速上手指南

115 阅读3分钟
# 引言

随着数据规模的指数级增长,图数据库在处理复杂关系数据方面的优势日益凸显。NebulaGraph作为一种开源、分布式且高度可扩展的图数据库,以其毫秒级的查询延迟和对超大规模图数据的支持而备受关注。本文旨在演示如何使用大型语言模型(LLM)为NebulaGraph数据库提供自然语言接口,使得非技术用户也可以轻松查询数据。

# 主要内容

## 1. 环境搭建

首先,我们需要启动NebulaGraph集群。最简单的方法是通过Docker运行以下脚本:

```bash
curl -fsSL nebula-up.siwei.io/install.sh | bash

其他安装选项包括Docker Desktop扩展、NebulaGraph云服务,以及通过Kubernetes进行部署等。完成集群启动后,我们可以创建数据库的空间和模式。

2. 数据库设置

通过以下代码片段,我们将在Jupyter Notebook环境中连接并设置NebulaGraph:

%pip install --upgrade --quiet ipython-ngql
%load_ext ngql

# 连接到NebulaGraph
%ngql --address 127.0.0.1 --port 9669 --user root --password nebula
# 创建一个新的空间
%ngql CREATE SPACE IF NOT EXISTS langchain(partition_num=1, replica_factor=1, vid_type=fixed_string(128));
%ngql USE langchain;

3. 构建模式和插入数据

接下来,我们将创建标签和边并插入一些数据。这些数据将用于后续查询。

%%ngql
CREATE TAG IF NOT EXISTS movie(name string);
CREATE TAG IF NOT EXISTS person(name string, birthdate string);
CREATE EDGE IF NOT EXISTS acted_in();
CREATE TAG INDEX IF NOT EXISTS person_index ON person(name(128));
CREATE TAG INDEX IF NOT EXISTS movie_index ON movie(name(128));

%%ngql
INSERT VERTEX person(name, birthdate) VALUES "Al Pacino":("Al Pacino", "1940-04-25");
INSERT VERTEX movie(name) VALUES "The Godfather II":("The Godfather II");
INSERT VERTEX movie(name) VALUES "The Godfather Coda: The Death of Michael Corleone":("The Godfather Coda: The Death of Michael Corleone");
INSERT EDGE acted_in() VALUES "Al Pacino"->"The Godfather II":();
INSERT EDGE acted_in() VALUES "Al Pacino"->"The Godfather Coda: The Death of Michael Corleone":();

4. 执行自然语言查询

我们将使用LangChain库与NebulaGraph集成,通过自然语言查询数据库。以下是一个示例代码:

from langchain.chains import NebulaGraphQAChain
from langchain_community.graphs import NebulaGraph
from langchain_openai import ChatOpenAI

# 创建NebulaGraph实例
graph = NebulaGraph(
    space="langchain",
    username="root",
    password="nebula",
    address="127.0.0.1", # 使用API代理服务提高访问稳定性
    port=9669,
    session_pool_size=30,
)

# 使用QA链执行查询
chain = NebulaGraphQAChain.from_llm(
    ChatOpenAI(temperature=0), graph=graph, verbose=True
)

result = chain.run("Who played in The Godfather II?")
print(result)

常见问题和解决方案

  1. 无法连接到NebulaGraph

    • 确保Docker容器或其他服务正常运行。
    • 核实连接参数(IP地址、端口、用户名和密码)是否正确。
  2. 查询结果不准确

    • 检查数据库模式和数据是否正确创建。
    • 确认LLM模型配置和参数设置是否合理。

总结和进一步学习资源

通过这篇文章,我们体验了如何使用LLM将自然语言转化为NebulaGraph查询。对于进一步学习,推荐以下资源:

参考资料

  • NebulaGraph Documentation
  • LangChain Documentation
  • OpenAI API Documentation

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

---END---