= Neo4j

This section walks you through setting up `Neo4jVectorStore` to store document embeddings and perform similarity searches.

link:https://neo4j.com[Neo4j] is an open-source NoSQL graph database.
It is a fully transactional database (ACID) that stores data structured as graphs consisting of nodes, connected by relationships.
Inspired by the structure of the real world, it allows for high query performance on complex data while remaining intuitive and simple for the developer.

The link:https://neo4j.com/docs/cypher-manual/current/indexes-for-vector-search/[Neo4j's Vector Search] allows users to query vector embeddings from large datasets.
An embedding is a numerical representation of a data object, such as text, image, audio, or document.
Embeddings can be stored on _Node_ properties and can be queried with the `db.index.vector.queryNodes()` function.
Those indexes are powered by Lucene using a Hierarchical Navigable Small World Graph (HNSW) to perform a k approximate nearest neighbors (k-ANN) query over the vector fields.

== Prerequisites

* A running Neo4j (5.15+) instance. The following options are available:
** link:https://hub.docker.com/_/neo4j[Docker] image
** link:https://neo4j.com/download/[Neo4j Desktop]
** link:https://neo4j.com/cloud/aura-free/[Neo4j Aura]
** link:https://neo4j.com/deployment-center/[Neo4j Server] instance
* If required, an API key for the xref:api/embeddings.adoc#available-implementations[EmbeddingModel] to generate the embeddings stored by the `Neo4jVectorStore`.

== Auto-configuration

[NOTE]
====
There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names.
Please refer to the https://docs.spring.io/spring-ai/reference/upgrade-notes.html[upgrade notes] for more information.
====

Spring AI provides Spring Boot auto-configuration for the Neo4j Vector Store.
To enable it, add the following dependency to your project's Maven `pom.xml` file:

[source,xml]
----
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-neo4j</artifactId>
</dependency>
----

or to your Gradle `build.gradle` build file.

[source,groovy]
----
dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-neo4j'
}
----

TIP: Refer to the xref:getting-started.adoc#dependency-management[Dependency Management] section to add the Spring AI BOM to your build file.

Please have a look at the list of xref:#neo4jvector-properties[Configuration Properties] for the vector store to learn about the default values and configuration options.

TIP: Refer to the xref:getting-started.adoc#artifact-repositories[Artifact Repositories] section to add Maven Central and/or Snapshot Repositories to your build file.

The vector store implementation can initialize the requisite schema for you, but you must opt-in by specifying the `initializeSchema` boolean in the appropriate constructor or by setting `...initialize-schema=true` in the `application.properties` file.

NOTE: this is a breaking change! In earlier versions of Spring AI, this schema initialization happened by default.

Additionally, you will need a configured `EmbeddingModel` bean. Refer to the xref:api/embeddings.adoc#available-implementations[EmbeddingModel] section for more information.

Now you can auto-wire the `Neo4jVectorStore` as a vector store in your application.

[source,java]
----
@Autowired VectorStore vectorStore;

// ...

List<Document> documents = List.of(
    new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")),
    new Document("The World is Big and Salvation Lurks Around the Corner"),
    new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2")));

// Add the documents to Neo4j
vectorStore.add(documents);

// Retrieve documents similar to a query
List<Document> results = vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());
----

[[neo4jvector-properties]]
=== Configuration Properties

To connect to Neo4j and use the `Neo4jVectorStore`, you need to provide access details for your instance.
A simple configuration can be provided via Spring Boot's `application.yml`:

[source,yaml]
----
spring:
  neo4j:
    uri: <neo4j instance URI>
    authentication:
      username: <neo4j username>
      password: <neo4j password>
  ai:
    vectorstore:
      neo4j:
        initialize-schema: true
        database-name: neo4j
        index-name: custom-index
        embedding-dimension: 1536
        distance-type: cosine
----

The Spring Boot properties starting with `spring.neo4j.*` are used to configure the Neo4j client:

[cols="2,5,1",stripes=even]
|===
|Property | Description | Default Value

| `spring.neo4j.uri` | URI for connecting to the Neo4j instance | `neo4j://localhost:7687`
| `spring.neo4j.authentication.username` | Username for authentication with Neo4j | `neo4j`
| `spring.neo4j.authentication.password` | Password for authentication with Neo4j | -
|===

Properties starting with `spring.ai.vectorstore.neo4j.*` are used to configure the `Neo4jVectorStore`:

[cols="2,5,1",stripes=even]
|===
|Property | Description | Default Value

|`spring.ai.vectorstore.neo4j.initialize-schema`| Whether to initialize the required schema | `false`
|`spring.ai.vectorstore.neo4j.database-name` | The name of the Neo4j database to use | `neo4j`
|`spring.ai.vectorstore.neo4j.index-name` | The name of the index to store the vectors | `spring-ai-document-index`
|`spring.ai.vectorstore.neo4j.embedding-dimension` | The number of dimensions in the vector | `1536`
|`spring.ai.vectorstore.neo4j.distance-type` | The distance function to use | `cosine`
|`spring.ai.vectorstore.neo4j.label` | The label used for document nodes | `Document`
|`spring.ai.vectorstore.neo4j.embedding-property` | The property name used to store embeddings | `embedding`
|===

The following distance functions are available:

* `cosine` - Default, suitable for most use cases. Measures cosine similarity between vectors.
* `euclidean` - Euclidean distance between vectors. Lower values indicate higher similarity.

== Manual Configuration

Instead of using the Spring Boot auto-configuration, you can manually configure the Neo4j vector store. For this you need to add the `spring-ai-neo4j-store` to your project:

[source,xml]
----
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-neo4j-store</artifactId>
</dependency>
----

or to your Gradle `build.gradle` build file.

[source,groovy]
----
dependencies {
    implementation 'org.springframework.ai:spring-ai-neo4j-store'
}
----

TIP: Refer to the xref:getting-started.adoc#dependency-management[Dependency Management] section to add the Spring AI BOM to your build file.

Create a Neo4j `Driver` bean.
Read the link:https://neo4j.com/docs/java-manual/current/client-applications/[Neo4j Documentation] for more in-depth information about the configuration of a custom driver.

[source,java]
----
@Bean
public Driver driver() {
    return GraphDatabase.driver("neo4j://<host>:<bolt-port>",
            AuthTokens.basic("<username>", "<password>"));
}
----

Then create the `Neo4jVectorStore` bean using the builder pattern:

[source,java]
----
@Bean
public VectorStore vectorStore(Driver driver, EmbeddingModel embeddingModel) {
    return Neo4jVectorStore.builder(driver, embeddingModel)
        .databaseName("neo4j")                // Optional: defaults to "neo4j"
        .distanceType(Neo4jDistanceType.COSINE) // Optional: defaults to COSINE
        .embeddingDimension(1536)                      // Optional: defaults to 1536
        .label("Document")                     // Optional: defaults to "Document"
        .embeddingProperty("embedding")        // Optional: defaults to "embedding"
        .indexName("custom-index")             // Optional: defaults to "spring-ai-document-index"
        .initializeSchema(true)                // Optional: defaults to false
        .batchingStrategy(new TokenCountBatchingStrategy()) // Optional: defaults to TokenCountBatchingStrategy
        .build();
}

// This can be any EmbeddingModel implementation
@Bean
public EmbeddingModel embeddingModel() {
    return new OpenAiEmbeddingModel(new OpenAiApi(System.getenv("OPENAI_API_KEY")));
}
----

== Metadata Filtering

You can leverage the generic, portable xref:api/vectordbs.adoc#metadata-filters[metadata filters] with Neo4j store as well.

For example, you can use either the text expression language:

[source,java]
----
vectorStore.similaritySearch(
    SearchRequest.builder()
        .query("The World")
        .topK(TOP_K)
        .similarityThreshold(SIMILARITY_THRESHOLD)
        .filterExpression("author in ['john', 'jill'] && 'article_type' == 'blog'").build());
----

or programmatically using the `Filter.Expression` DSL:

[source,java]
----
FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(SearchRequest.builder()
    .query("The World")
    .topK(TOP_K)
    .similarityThreshold(SIMILARITY_THRESHOLD)
    .filterExpression(b.and(
        b.in("author", "john", "jill"),
        b.eq("article_type", "blog")).build()).build());
----

NOTE: Those (portable) filter expressions get automatically converted into the proprietary Neo4j `WHERE` link:https://neo4j.com/developer/cypher/filtering-query-results/[filter expressions].

For example, this portable filter expression:

[source,sql]
----
author in ['john', 'jill'] && 'article_type' == 'blog'
----

is converted into the proprietary Neo4j filter format:

[source,text]
----
node.`metadata.author` IN ["john","jill"] AND node.`metadata.'article_type'` = "blog"
----

== Accessing the Native Client

The Neo4j Vector Store implementation provides access to the underlying native Neo4j client (`Driver`) through the `getNativeClient()` method:

[source,java]
----
Neo4jVectorStore vectorStore = context.getBean(Neo4jVectorStore.class);
Optional<Driver> nativeClient = vectorStore.getNativeClient();

if (nativeClient.isPresent()) {
    Driver driver = nativeClient.get();
    // Use the native client for Neo4j-specific operations
}
----

The native client gives you access to Neo4j-specific features and operations that might not be exposed through the `VectorStore` interface.
