To implement vector search, you must first create a vector index and insert vectors, then perform the search.
1. Create Index and Insert Data:
Use create_vector_index_nodes to initialize the index on a specific label and property, then use add_n to insert nodes with embeddings.
2. Execute Search:
Use vector_search_nodes to find the top-k nearest neighbors. You can use .value_map() to retrieve both the virtual metadata (like $id and $distance) and stored properties (like title).
// 1. Create index and insert vectors
write_batch()
.var_as(
"create_doc_index",
g().create_vector_index_nodes(
"Doc",
"embedding",
None::<&str>,
),
)
.var_as(
"doc_a",
g().add_n(
"Doc",
vec![
("title", PropertyValue::from("A")),
("embedding", PropertyValue::from(vec![1.0f32, 0.0, 0.0])),
],
),
)
.returning(["create_doc_index", "doc_a"]);
// 2. Node vector search
read_batch()
.var_as(
"doc_hits",
g().vector_search_nodes("Doc", "embedding", vec![1.0f32, 0.0, 0.0], 5, None)
.value_map(Some(vec!["$id", "$distance", "title"])),
)
.returning(["doc_hits"]);