rig::neo4j(neo4j feature)在 Neo4j 原生向量索引上执行 Rig 向量搜索。如果嵌入保存在图节点上,并且你希望直接进行相似度搜索、不把向量搬到独立存储,可以使用它。
前置条件#
- Neo4j GenAI 插件。 Neo4j Aura 默认启用;自行管理的实例需要安装。
- 覆盖待搜索节点的向量索引。 使用 Cypher(
CREATE VECTOR INDEX ...)或下文的Neo4jClient::create_vector_index创建。Neo4j 在后台构建新索引,因此索引可能无法立即查询。
配置#
toml
[dependencies]
rig = { version = "=0.46.0", features = ["neo4j"] }
tokio = { version = "1", features = ["full"] }
anyhow = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"如果希望通过 client.graph 执行自己的 Cypher,或用 Neo4jClient::from_config 创建连接,还需要添加 neo4rs。
示例#
连接数据库,创建索引,插入带嵌入的文档,然后搜索:
rust
use rig::neo4j::{Neo4jClient, vector_index::IndexConfig};
use rig::prelude::*;
use serde::{Deserialize, Serialize};
use rig::providers::openai::{self, OpenAI};
use rig::vector_store::InsertDocuments;
#[derive(Embed, Clone, Serialize, Deserialize, Debug)]
struct Word {
id: String,
#[embed]
definition: String,
}
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let model = OpenAI::from_env()?.embedding(openai::TEXT_EMBEDDING_3_SMALL, None);
let client = Neo4jClient::connect("neo4j://localhost:7687", "neo4j", "password").await?;
// A vector index named "words" over the `embedding` property of `Word` nodes,
// as wide as the model's vectors.
client
.create_vector_index(IndexConfig::new("words"), "Word", model.capabilities().ndims)
.await?;
// Reuse the model that produced (or will produce) the stored embeddings.
let index = client.get_index(model.clone(), "words").await?;
let embeddings = EmbeddingsBuilder::new(model)
.document(Word { id: "doc0".into(), definition: "A flurbo is a green alien.".into() })?
.document(Word { id: "doc1".into(), definition: "A glarb-glarb is an ancient farming tool.".into() })?
.build()
.await?;
index.insert_documents(embeddings).await?;
let req = VectorSearchRequest::builder()
.query("What is a glarb-glarb?")
.samples(1)
.build();
for result in index.top_n::<Word>(req).await? {
println!("{:.3} {} {}", result.score, result.id, result.document.definition);
}
Ok(())
}工作原理#
Neo4jClient::connect(uri, user, password)打开连接。Neo4jClient::from_config(config)接收neo4rs::Config,可设置数据库名、TLS、连接池大小等;client.graph是底层neo4rs::Graph,供你执行自己的 Cypher。create_vector_index(config, node_label, ndims)在索引不存在时创建它,并尽力等待其上线。IndexConfig::new(name)默认使用embedding属性和余弦相似度;通过.embedding_property(..)和.similarity_function(..)修改。ndims必须与查询模型的向量维度相同:model.capabilities().ndims。get_index(model, index_name)为现有索引返回Neo4jVectorIndex。它从索引读取节点标签和嵌入属性;索引不存在时返回错误。insert_documents在索引对应标签下为每个嵌入创建一个节点,将文档字段平铺为节点属性,向量放入嵌入属性,参与嵌入的文本放入embedded_text。top_n::<T>(req)查询索引中最近的samples个节点,把每个节点(去掉嵌入后)反序列化为T。result.id是 Neo4j 内部节点 ID。top_n_ids仅返回 ID 和得分。
由于向量是普通节点属性,你可以在自己的 Cypher 中组合相似度搜索和图遍历。rig-neo4j 示例包含一个电影推荐图,为已有节点添加嵌入后执行查询。
注意
不要在 Neo4j 请求中设置 threshold:Rig 将它与节点上的 distance 属性比较,而不是与搜索得分比较。这会过滤掉所有不带该属性的节点结果。请自行根据 result.score 过滤。