跳到主要內容
Open In ColabOpen on GitHub

NebulaGraph

NebulaGraph 是一款開源、分散式、可擴展、極速的圖形資料庫,專為超大型圖形而建,延遲時間僅需毫秒。它使用 nGQL 圖形查詢語言。

nGQLNebulaGraph 的宣告式圖形查詢語言。它允許具表現力且有效率的圖形模式。nGQL 專為開發人員和營運專業人員設計。nGQL 是一種類似 SQL 的查詢語言。

此筆記本展示如何使用 LLM 提供 NebulaGraph 資料庫的自然語言介面。

設定

您可以執行以下腳本,以 Docker 容器啟動 NebulaGraph 叢集

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

其他選項包括

叢集執行後,我們可以為資料庫建立 SPACESCHEMA

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

# connect ngql jupyter extension to nebulagraph
%ngql --address 127.0.0.1 --port 9669 --user root --password nebula
# create a new space
%ngql CREATE SPACE IF NOT EXISTS langchain(partition_num=1, replica_factor=1, vid_type=fixed_string(128));
# Wait for a few seconds for the space to be created.
%ngql USE langchain;

建立結構描述,如需完整資料集,請參考此處

%%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":();
from langchain.chains import NebulaGraphQAChain
from langchain_community.graphs import NebulaGraph
from langchain_openai import ChatOpenAI
graph = NebulaGraph(
space="langchain",
username="root",
password="nebula",
address="127.0.0.1",
port=9669,
session_pool_size=30,
)

重新整理圖形結構描述資訊

如果資料庫的結構描述變更,您可以重新整理產生 nGQL 陳述式所需的結構描述資訊。

# graph.refresh_schema()
print(graph.get_schema)
Node properties: [{'tag': 'movie', 'properties': [('name', 'string')]}, {'tag': 'person', 'properties': [('name', 'string'), ('birthdate', 'string')]}]
Edge properties: [{'edge': 'acted_in', 'properties': []}]
Relationships: ['(:person)-[:acted_in]->(:movie)']

查詢圖形

我們現在可以使用圖形 cypher QA 鏈來詢問圖形問題

chain = NebulaGraphQAChain.from_llm(
ChatOpenAI(temperature=0), graph=graph, verbose=True
)
chain.run("Who played in The Godfather II?")


> Entering new NebulaGraphQAChain chain...
Generated nGQL:
MATCH (p:`person`)-[:acted_in]->(m:`movie`) WHERE m.`movie`.`name` == 'The Godfather II'
RETURN p.`person`.`name`
Full Context:
{'p.person.name': ['Al Pacino']}

> Finished chain.
'Al Pacino played in The Godfather II.'

此頁面是否對您有幫助?