Neo4j
Since Camel 4.10
Only producer is supported
The Neo4j component provides support for Neo4j graph database.
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-neo4j</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI format
neo4j:name[?options]
Where name is the database name.
The operation option of the endpoint, or the CamelNeo4jOperation header, selects the operation, such as neo4j:test?operation=RETRIEVE_NODES. The header, when set, wins over the option, so one endpoint can also run several operations. Without either, the producer fails.
Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The Neo4j component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
The Cypher variable that the generated queries bind the node to, such as u in MATCH (u:User). It is not stored in the database. Required by CREATE_NODE, RETRIEVE_NODES, DELETE_NODE and CREATE_VECTOR_INDEX. CREATE_VECTOR uses e when not set. | String | ||
The shared configuration of the component. Each endpoint starts from a copy of it. | Neo4jConfiguration | ||
The URI of the Neo4j server that the driver connects to, such as neo4j://localhost:7687 or bolt://localhost:7687 (the neo4j+s and bolt+s schemes use TLS). The producer also needs credentials: kerberosAuthTicket, token, or username and password. Required unless the driver option is set, which wins over this option and the credentials. | String | ||
Whether DELETE_NODE deletes the nodes with DETACH DELETE, which also deletes their relationships. When false, deleting a node that still has relationships fails. | false | boolean | |
The number of dimensions of the vectors in the vector index, set as vector.dimensions by CREATE_VECTOR_INDEX. It must be the length of the embedding vectors. Required by CREATE_VECTOR_INDEX. | Integer | ||
The label of the nodes. CREATE_NODE gives it to the new node, RETRIEVE_NODES and DELETE_NODE match the nodes that have it, and CREATE_VECTOR_INDEX indexes the nodes that have it. Required by these operations. CREATE_VECTOR gives it to the node it creates, and uses Embedding when not set. | String | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
The number of nearest neighbours that VECTOR_SIMILARITY_SEARCH asks the vector index for. The nodes that score below minScore are then left out, so the result can have fewer. | 3 | int | |
The lowest similarity score that a node needs to be in the result of VECTOR_SIMILARITY_SEARCH. Neo4j gives scores from 0 to 1, where 1 is the most similar, so 0 keeps all the nodes that the vector index returns. | 0 | double | |
The operation to perform. The CamelNeo4jOperation header, when set, wins over this option. Enum values:
| Neo4Operation | ||
Deprecated Cypher Query. Deprecation note: Not used: RETRIEVE_NODES_AND_UPDATE_WITH_CYPHER_QUERY and ADD_OR_DELETE_NODE_WITH_CYPHER_QUERY take the Cypher query from the message body. | String | ||
The similarity function of the vector index that CREATE_VECTOR_INDEX creates, set as vector.similarity_function. It decides how VECTOR_SIMILARITY_SEARCH scores the nodes. Enum values:
| cosine | Neo4jSimilarityFunction | |
The name of the vector index that CREATE_VECTOR_INDEX creates (unless an index with this name already exists), DROP_VECTOR_INDEX drops and VECTOR_SIMILARITY_SEARCH queries. Required by these operations. | String | ||
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | |
Autowired The Neo4j Driver to use. When set, databaseUrl and the credentials are not used. Autowired when the registry has a single Driver. | Driver | ||
The Kerberos ticket, encoded in Base64, for Kerberos authentication. It wins over token, username and password. | String | ||
The password for basic authentication, used together with username. | String | ||
The realm for basic authentication, used only together with username and password. When not set, the driver sends no realm. | String | ||
The token for bearer authentication, such as a token of a single sign-on provider. It wins over username and password. | String | ||
The user name for basic authentication, used together with password when neither kerberosAuthTicket nor token is set. | String |
Endpoint Options
The Neo4j endpoint is configured using URI syntax:
neo4j:name
With the following path and query parameters:
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The Cypher variable that the generated queries bind the node to, such as u in MATCH (u:User). It is not stored in the database. Required by CREATE_NODE, RETRIEVE_NODES, DELETE_NODE and CREATE_VECTOR_INDEX. CREATE_VECTOR uses e when not set. | String | ||
The URI of the Neo4j server that the driver connects to, such as neo4j://localhost:7687 or bolt://localhost:7687 (the neo4j+s and bolt+s schemes use TLS). The producer also needs credentials: kerberosAuthTicket, token, or username and password. Required unless the driver option is set, which wins over this option and the credentials. | String | ||
Whether DELETE_NODE deletes the nodes with DETACH DELETE, which also deletes their relationships. When false, deleting a node that still has relationships fails. | false | boolean | |
The number of dimensions of the vectors in the vector index, set as vector.dimensions by CREATE_VECTOR_INDEX. It must be the length of the embedding vectors. Required by CREATE_VECTOR_INDEX. | Integer | ||
The label of the nodes. CREATE_NODE gives it to the new node, RETRIEVE_NODES and DELETE_NODE match the nodes that have it, and CREATE_VECTOR_INDEX indexes the nodes that have it. Required by these operations. CREATE_VECTOR gives it to the node it creates, and uses Embedding when not set. | String | ||
The number of nearest neighbours that VECTOR_SIMILARITY_SEARCH asks the vector index for. The nodes that score below minScore are then left out, so the result can have fewer. | 3 | int | |
The lowest similarity score that a node needs to be in the result of VECTOR_SIMILARITY_SEARCH. Neo4j gives scores from 0 to 1, where 1 is the most similar, so 0 keeps all the nodes that the vector index returns. | 0 | double | |
The operation to perform. The CamelNeo4jOperation header, when set, wins over this option. Enum values:
| Neo4Operation | ||
Deprecated Cypher Query. Deprecation note: Not used: RETRIEVE_NODES_AND_UPDATE_WITH_CYPHER_QUERY and ADD_OR_DELETE_NODE_WITH_CYPHER_QUERY take the Cypher query from the message body. | String | ||
The similarity function of the vector index that CREATE_VECTOR_INDEX creates, set as vector.similarity_function. It decides how VECTOR_SIMILARITY_SEARCH scores the nodes. Enum values:
| cosine | Neo4jSimilarityFunction | |
The name of the vector index that CREATE_VECTOR_INDEX creates (unless an index with this name already exists), DROP_VECTOR_INDEX drops and VECTOR_SIMILARITY_SEARCH queries. Required by these operations. | String | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Autowired The Neo4j Driver to use. When set, databaseUrl and the credentials are not used. Autowired when the registry has a single Driver. | Driver | ||
The Kerberos ticket, encoded in Base64, for Kerberos authentication. It wins over token, username and password. | String | ||
The password for basic authentication, used together with username. | String | ||
The realm for basic authentication, used only together with username and password. When not set, the driver sends no realm. | String | ||
The token for bearer authentication, such as a token of a single sign-on provider. It wins over username and password. | String | ||
The user name for basic authentication, used together with password when neither kerberosAuthTicket nor token is set. | String |
Message Headers
The Neo4j component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelNeo4jOperation (producer) Constant: | The operation to perform. It wins over the operation option. Enum values:
| String | |
CamelNeo4jMatchProperties (producer) Constant: | The properties that RETRIEVE_NODES and DELETE_NODE match the nodes on, as a JSON object of property names and values. A node matches when all the properties are equal. A property name has letters, digits and underscores, and does not start with a digit. Without this header, or with an empty object, all the nodes with the label match, so DELETE_NODE deletes them all. | String | |
CamelNeo4jQueryResult (producer) Constant: | The text of the Cypher query that the operation ran, set by CREATE_NODE, DELETE_NODE, ADD_OR_DELETE_NODE_WITH_CYPHER_QUERY, CREATE_VECTOR_INDEX, DROP_VECTOR_INDEX and CREATE_VECTOR. | String | |
CamelNeo4jQueryResultNodesCreated (producer) Constant: | The number of nodes that the query created. Set by the operations that set CamelNeo4jQueryResult. | Integer | |
CamelNeo4jQueryResultNodesDeleted (producer) Constant: | The number of nodes that the query deleted. Set by the operations that set CamelNeo4jQueryResult. | Integer | |
CamelNeo4jQueryResultContainsUpdates (producer) Constant: | Whether the query changed the database: created or deleted nodes, relationships, indexes or constraints, set properties, or added or removed labels. Set by the operations that set CamelNeo4jQueryResult. | Boolean | |
CamelNeo4jQueryResultRelationshipsCreated (producer) Constant: | The number of relationships that the query created. Set by the operations that set CamelNeo4jQueryResult. | Integer | |
CamelNeo4jQueryResultRelationshipsDeleted (producer) Constant: | The number of relationships that the query deleted. Set by the operations that set CamelNeo4jQueryResult. | Integer | |
CamelNeo4jQueryResultRetrieveSize (producer) Constant: | The number of records that RETRIEVE_NODES, RETRIEVE_NODES_AND_UPDATE_WITH_CYPHER_QUERY or VECTOR_SIMILARITY_SEARCH retrieved. | Integer | |
CamelNeo4jQueryResultListNeo4jNodes (producer) Constant: | The records that RETRIEVE_NODES, RETRIEVE_NODES_AND_UPDATE_WITH_CYPHER_QUERY or VECTOR_SIMILARITY_SEARCH retrieved, as the Records of the Neo4j driver, with all their columns. | List | |
CamelNeo4jVectorEmbeddingId (producer) Constant: | The id of the node that CREATE_VECTOR creates when the body is not a Neo4jEmbedding. A random UUID when not set. | String | |
| Constant: | Deprecated Label for the Node - used when inserting from Embeddings. Deprecation note: Not used: the producer does not read this header. CREATE_VECTOR takes the label of the node from the label option, and Embedding when the option is not set. | String |
Message Body
The message body at each side of the Neo4j component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Producer input |
| What the operation of the operation option or the CamelNeo4jOperation header needs: CREATE_NODE the properties of the node as a Map or as JSON text (bytes, a stream, a POJO or no body fail); the two Cypher operations the query as text (bytes or a stream are read as text); CREATE_VECTOR a Neo4jEmbedding, or the text with the float[] vector in the CamelLangChain4jEmbeddingsVector header; VECTOR_SIMILARITY_SEARCH a Neo4jEmbedding, a float[], or a List or an array of numbers (text or no body fail). The other operations do not use the body.
|
Producer output |
| RETRIEVE_NODES, RETRIEVE_NODES_AND_UPDATE_WITH_CYPHER_QUERY and VECTOR_SIMILARITY_SEARCH give a List of Maps (empty when none), the properties of each node found, with the Records of the driver in the CamelNeo4jQueryResultListNeo4jNodes header. A record of a Cypher query whose first column is not a node is a Map of its columns, and VECTOR_SIMILARITY_SEARCH adds the score of each node under the score key. The other operations leave the body unchanged, with the counts in the CamelNeo4jQueryResult headers.
|
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Graph database usage - simple operations
Create a Node
To create a node in a database named test, define the body as a string containing the JSON body. Use the operation CREATE_NODE. The URI endpoint should contain also specify the label and the alias. A message without a body fails with an InvalidPayloadException.
var body = "{\"name\": \"Alice\", \"email\": \"alice@example.com\", \"age\": 30}";
Exchange result = fluentTemplate.to("neo4j:test?alias=u1&label=User")
.withBodyAs(body, String.class)
.withHeader("CamelNeo4jOperation", Neo4Operation.CREATE_NODE)
.request(Exchange.class); Create a Node with properties
To create a node in a database named test with properties, define the body as a Map containing the properties and values. Use the operation CREATE_NODE. The URI endpoint should contain also specify the label and the alias.
Map<String, Object> params = Map.of(
"name", "Bob",
"email", "bob@example.com",
"age", 25);
Exchange result = fluentTemplate.to("neo4j:test?alias=u2&label=User")
.withBodyAs(params, Map.class)
.withHeader("CamelNeo4jOperation", Neo4Operation.CREATE_NODE)
.request(Exchange.class); Retrieve Node
To retrieve a node in a database named test. Define the header CamelNeo4jMatchProperties as a JSON object with the properties to match. Use the operation RETRIEVE_NODES. The URI endpoint should also specify the label and the alias. The response is a List of Map<String, Object>. Each map represents the list of properties of a single node.
Exchange result = fluentTemplate.to("neo4j:test?alias=u&label=User")
.withHeader("CamelNeo4jOperation", Neo4Operation.RETRIEVE_NODES)
.withHeader("CamelNeo4jMatchProperties", "{\"name\": \"Alice\"}")
.request(Exchange.class); To retrieve all nodes with label=User, use the same request without specifying any CamelNeo4jMatchProperties.
Exchange result = fluentTemplate.to("neo4j:test?alias=u&label=User")
.withHeader("CamelNeo4jOperation", Neo4Operation.RETRIEVE_NODES)
.request(Exchange.class); Delete Node
To delete a node in a database named test. Define the header CamelNeo4jMatchProperties as a JSON object with the properties to match. Use the operation DELETE_NODE. The URI endpoint should also specify the label and the alias.
Exchange result = fluentTemplate.to("neo4j:test?alias=u&label=User")
.withHeader("CamelNeo4jOperation", Neo4Operation.DELETE_NODE)
.withHeader("CamelNeo4jMatchProperties", "{\"name\": \"Alice\"}")
.request(Exchange.class); Delete Node with relationships
If a node has relationships, it won’t be deleted unless we either delete the relationships or delete it with detached relationships. To delete a node with detached relationships, set the option detachRelationship to true.
Exchange result = fluentTemplate.to("neo4j:test?alias=u&label=User&detachRelationship=true")
.withHeader("CamelNeo4jOperation", Neo4Operation.DELETE_NODE)
.withHeader("CamelNeo4jMatchProperties", "{\"name\": \"Alice\"}")
.request(Exchange.class); The operations in a route
In a route, the operation option or the CamelNeo4jOperation header selects the operation. The first route below creates a node from a JSON body, and the second finds the nodes whose name is the message body:
- route:
from:
uri: direct:createUser
steps:
- setHeader:
name: CamelNeo4jOperation
expression:
constant:
expression: CREATE_NODE
- to:
uri: neo4j:test
parameters:
alias: u1
label: User
- route:
from:
uri: direct:findUser
steps:
- setHeader:
name: CamelNeo4jOperation
expression:
constant:
expression: RETRIEVE_NODES
- setHeader:
name: CamelNeo4jMatchProperties
expression:
simple:
expression: '{"name": "${body}"}'
- to:
uri: neo4j:test
parameters:
alias: u
label: User
- log:
message: "Found: ${body}" Graph database usage - use Cypher Queries
Create / Delete Nodes with a Cypher query
To create or delete nodes with a Cypher query in a database named test, set the Cypher query in the body. Use the operation ADD_OR_DELETE_NODE_WITH_CYPHER_QUERY. The operation can be used too to create multiple nodes and relationships between nodes.
var cypherQuery = "CREATE (u3:User {name: 'Charlie', email: 'charlie@example.com', age: 35})";
Exchange result = fluentTemplate.to("neo4j:test")
.withHeader("CamelNeo4jOperation", Neo4Operation.ADD_OR_DELETE_NODE_WITH_CYPHER_QUERY)
.withBodyAs(cypherQuery, String.class)
.request(Exchange.class); var cypherQuery = "MATCH (u:User {name: 'Bob'}) DELETE u";
Exchange result = fluentTemplate.to("neo4j:test")
.withHeader("CamelNeo4jOperation", Neo4Operation.ADD_OR_DELETE_NODE_WITH_CYPHER_QUERY)
.withBodyAs(cypherQuery, String.class)
.request(Exchange.class); Retrieve / Update nodes with a Cypher query
To retrieve or update nodes with Cypher Query in a database named test, set the Cypher query in the body. Use the operation RETRIEVE_NODES_AND_UPDATE_WITH_CYPHER_QUERY.
The operation is the same as ADD_OR_DELETE_NODE_WITH_CYPHER_QUERY, except that it returns a list of retrieved or updated nodes represented as Map<String, Object>.
When the first column that the query returns is a node, each Map holds the properties of that node. Otherwise, such as for MATCH (u:User) RETURN u.name AS name, u.age AS age or a count(*), each Map holds the columns of one record by name, such as {name=Ethan, age=41}. The CamelNeo4jQueryResultListNeo4jNodes header has the records of the Neo4j driver, with all their columns.
var cypherQuery = "MATCH "
+ "(u:User {name: 'Ethan'})"
+ "SET u.age=41 "
+ "RETURN u";
Exchange result = fluentTemplate.to("neo4j:test")
.withBodyAs(cypherQuery, String.class)
.withHeader("CamelNeo4jOperation", Neo4Operation.RETRIEVE_NODES_AND_UPDATE_WITH_CYPHER_QUERY)
.request(Exchange.class); Vector database embeddings usage
Create a vector index
To use Neo4j as a Vector database, we must create first a vector index for a label.
To create a vector index in a database named test, use the operation CREATE_VECTOR_INDEX. The URI endpoint should also specify the label, the alias, the vector index name and the dimension of embeddings.
Exchange result = fluentTemplate.to("neo4j:test?vectorIndexName=movieIdx&alias=m&label=Movie&dimension=2")
.withHeader("CamelNeo4jOperation", Neo4Operation.CREATE_VECTOR_INDEX)
.request(Exchange.class); Drop a vector index
To drop a vector index in a database named test, use the operation DROP_VECTOR_INDEX. The URI endpoint should contain also specify the vector index name.
Exchange result = fluentTemplate.to("neo4j:test?vectorIndexName=movieIdx")
.withHeader("CamelNeo4jOperation", Neo4Operation.DROP_VECTOR_INDEX)
.request(Exchange.class); Create a vector
To create a vector in a database named test, use the operation CREATE_VECTOR. The URI endpoint should also specify the label, the alias and the vector index name. Put the vector array in the CamelLangChain4jEmbeddingsVector header, and the corresponding text in the body. The id can be generated by Camel Neo4j.
Camel Neo4j will create the node and store the vector as an embedding property, the text as text property and the id`as `id property.
float[] vectorExchange result = fluentTemplate.to("neo4j:test?vectorIndexName=myIndex&label=Test&alias=t")
.withHeader("CamelNeo4jOperation", Neo4Operation.CREATE_VECTOR)
.withHeader("CamelNeo4jVectorEmbeddingId", "1")
.withHeader("CamelLangChain4jEmbeddingsVector", new float[] { 10.8f, 10.6f })
.withBody("Hello World!")
.request(Exchange.class); Similarity search
To perform a similarity search using vectors in a database named test, use the operation VECTOR_SIMILARITY_SEARCH. The URI endpoint should also specify the label, the alias and the vector index name.
The body is the vector to search for: a Neo4jEmbedding, a float[], or a List or an array of numbers, such as a List<Double>. Another body, such as text, or a message without a body, fails with an InvalidPayloadException.
The result is a List of Map<String, Object>: the properties of each node found, and its similarity score as a Double under the score key (it replaces a property of the node named score). The CamelNeo4jQueryResultListNeo4jNodes header has the records of the Neo4j driver, with the node and score columns.
List.of() vectorExchange result = fluentTemplate.to("neo4j:test?vectorIndexName=myIndex&label=Test&alias=t")
.withHeader("CamelNeo4jOperation", Neo4Operation.VECTOR_SIMILARITY_SEARCH)
.withBody(List.of(0.75f, 0.65f))
.request(Exchange.class); Generate Embeddings with Langchain4j-embeddings
You can generate embeddings with an Embedding Models using the camel Lancghain4j Embeddings components. Camel Neo4j introduces a DataType neo4j:embeddings that automates the transformations of the Lancghain4j embeddings to Neo4j vectors.
The label option sets the label of the nodes that CREATE_VECTOR creates (Embedding when it is not set). The deprecated CamelNeo4jLabel header is not used.
-
Java
-
YAML
from("direct:in")
.to("langchain4j-embeddings:test")
.setHeader("CamelNeo4jOperation").constant(Neo4Operation.CREATE_VECTOR)
.transformDataType(new DataType("neo4j:embeddings"))
.to("neo4j:neo4j?vectorIndexName=myIndex&label=Test"); - route:
from:
uri: direct:in
steps:
- to:
uri: langchain4j-embeddings:test
- setHeader:
name: CamelNeo4jOperation
expression:
constant:
expression: CREATE_VECTOR
- transformDataType:
toType: neo4j:embeddings
- to:
uri: neo4j:neo4j
parameters:
vectorIndexName: myIndex
label: Test Similarity Search for LangChain4j RAG
You can enhance the Camel LangChain4j chat RAG experience by integrating Neo4j similarity search with Camel Neo4j DataTypes.
To achieve this, use the neo4j:embeddings DataType to generate embeddings from the prompt. These embeddings will then be utilized for the similarity search operation.
Next, use the neo4j:rag DataType to convert the retrieved embeddings into a List<String> for RAG. This list can be directly used with the LangChain4jRagAggregatorStrategy from the LangChain4j chat component. Each element is the text property of a node: a value of another type, such as a number, is converted to a String, and a node without the property gives an empty String.
| The retrieved embeddings must be ingested in Neo4j as LangChain4j embeddings. |
-
Java
-
YAML
from("direct:search")
.to("langchain4j-embeddings:test")
.transformDataType(new DataType("neo4j:embeddings"))
.setHeader("CamelNeo4jOperation", constant(Neo4Operation.VECTOR_SIMILARITY_SEARCH))
.to("neo4j:neo4j?vectorIndexName=myIndex&label=Test")
.transformDataType(new DataType("neo4j:rag")); - route:
from:
uri: direct:search
steps:
- to:
uri: langchain4j-embeddings:test
- transformDataType:
toType: neo4j:embeddings
- setHeader:
name: CamelNeo4jOperation
expression:
constant:
expression: VECTOR_SIMILARITY_SEARCH
- to:
uri: neo4j:neo4j
parameters:
vectorIndexName: myIndex
label: Test
- transformDataType:
toType: neo4j:rag