diff --git a/docs/extras/integrations/vectorstores/neo4jvector.ipynb b/docs/extras/integrations/vectorstores/neo4jvector.ipynb index 3250e05d23..d62cf693ab 100644 --- a/docs/extras/integrations/vectorstores/neo4jvector.ipynb +++ b/docs/extras/integrations/vectorstores/neo4jvector.ipynb @@ -10,7 +10,8 @@ "\n", "It supports:\n", "- approximate nearest neighbor search\n", - "- L2 distance and cosine distance\n", + "- Euclidean similarity and cosine similarity\n", + "- Hybrid search combining vector and keyword searches\n", "\n", "This notebook shows how to use the Neo4j vector index (`Neo4jVector`)." ] @@ -24,41 +25,11 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": null, "metadata": { "tags": [] }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Requirement already satisfied: neo4j in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (5.11.0)\n", - "Requirement already satisfied: pytz in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from neo4j) (2023.3)\n", - "Requirement already satisfied: openai in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (0.27.6)\n", - "Requirement already satisfied: requests>=2.20 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from openai) (2.31.0)\n", - "Requirement already satisfied: tqdm in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from openai) (4.66.1)\n", - "Requirement already satisfied: aiohttp in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from openai) (3.8.5)\n", - "Requirement already satisfied: charset-normalizer<4,>=2 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from requests>=2.20->openai) (3.2.0)\n", - "Requirement already satisfied: idna<4,>=2.5 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from requests>=2.20->openai) (3.4)\n", - "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from requests>=2.20->openai) (2.0.4)\n", - "Requirement already satisfied: certifi>=2017.4.17 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from requests>=2.20->openai) (2023.7.22)\n", - "Requirement already satisfied: attrs>=17.3.0 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from aiohttp->openai) (23.1.0)\n", - "Requirement already satisfied: multidict<7.0,>=4.5 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from aiohttp->openai) (6.0.4)\n", - "Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from aiohttp->openai) (4.0.3)\n", - "Requirement already satisfied: yarl<2.0,>=1.0 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from aiohttp->openai) (1.9.2)\n", - "Requirement already satisfied: frozenlist>=1.1.1 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from aiohttp->openai) (1.4.0)\n", - "Requirement already satisfied: aiosignal>=1.1.2 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from aiohttp->openai) (1.3.1)\n", - "Requirement already satisfied: tiktoken in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (0.4.0)\n", - "Requirement already satisfied: regex>=2022.1.18 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from tiktoken) (2023.8.8)\n", - "Requirement already satisfied: requests>=2.26.0 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from tiktoken) (2.31.0)\n", - "Requirement already satisfied: charset-normalizer<4,>=2 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from requests>=2.26.0->tiktoken) (3.2.0)\n", - "Requirement already satisfied: idna<4,>=2.5 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from requests>=2.26.0->tiktoken) (3.4)\n", - "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from requests>=2.26.0->tiktoken) (2.0.4)\n", - "Requirement already satisfied: certifi>=2017.4.17 in /home/tomaz/anaconda3/envs/myenv/lib/python3.11/site-packages (from requests>=2.26.0->tiktoken) (2023.7.22)\n" - ] - } - ], + "outputs": [], "source": [ "# Pip install necessary package\n", "!pip install neo4j\n", @@ -115,6 +86,7 @@ "outputs": [], "source": [ "loader = TextLoader(\"../../../state_of_the_union.txt\")\n", + "\n", "documents = loader.load()\n", "text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n", "docs = text_splitter.split_documents(documents)\n", @@ -179,16 +151,6 @@ "name": "stdout", "output_type": "stream", "text": [ - "--------------------------------------------------------------------------------\n", - "Score: 0.9077161550521851\n", - "Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n", - "\n", - "Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n", - "\n", - "One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n", - "\n", - "And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.\n", - "--------------------------------------------------------------------------------\n", "--------------------------------------------------------------------------------\n", "Score: 0.9077161550521851\n", "Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n", @@ -214,18 +176,36 @@ "We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.\n", "--------------------------------------------------------------------------------\n", "--------------------------------------------------------------------------------\n", - "Score: 0.891287088394165\n", - "A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \n", + "Score: 0.8867912292480469\n", + "And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \n", "\n", - "And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \n", + "As I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. \n", "\n", - "We can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. \n", + "While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice. \n", "\n", - "We’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. \n", + "And soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. \n", "\n", - "We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. \n", + "So tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together. \n", "\n", - "We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.\n", + "First, beat the opioid epidemic.\n", + "--------------------------------------------------------------------------------\n", + "--------------------------------------------------------------------------------\n", + "Score: 0.8866499662399292\n", + "Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. \n", + "\n", + "And as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up. \n", + "\n", + "That ends on my watch. \n", + "\n", + "Medicare is going to set higher standards for nursing homes and make sure your loved ones get the care they deserve and expect. \n", + "\n", + "We’ll also cut costs and keep the economy going strong by giving workers a fair shot, provide more training and apprenticeships, hire them based on their skills not degrees. \n", + "\n", + "Let’s pass the Paycheck Fairness Act and paid leave. \n", + "\n", + "Raise the minimum wage to $15 an hour and extend the Child Tax Credit, so no one has to raise a family in poverty. \n", + "\n", + "Let’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges.\n", "--------------------------------------------------------------------------------\n" ] } @@ -281,7 +261,7 @@ { "data": { "text/plain": [ - "['2f70679a-4416-11ee-b7c3-d46a6aa24f5b']" + "['064c7032-5093-11ee-8041-3b350f274873']" ] }, "execution_count": 10, @@ -328,15 +308,68 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Retriever options\n", + "## Hybrid search (vector + keyword)\n", "\n", - "This section shows how to use `Neo4jVector` as a retriever." + "Neo4j integrates both vector and keyword indexes, which allows you to use a hybrid search approach" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, + "outputs": [], + "source": [ + "# The Neo4jVector Module will connect to Neo4j and create a vector and keyword indices if needed.\n", + "hybrid_db = Neo4jVector.from_documents(\n", + " docs, \n", + " OpenAIEmbeddings(), \n", + " url=url, \n", + " username=username, \n", + " password=password,\n", + " search_type=\"hybrid\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To load the hybrid search from existing indexes, you have to provide both the vector and keyword indices" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "index_name = \"vector\" # default index name\n", + "keyword_index_name = \"keyword\" #default keyword index name\n", + "\n", + "store = Neo4jVector.from_existing_index(\n", + " OpenAIEmbeddings(),\n", + " url=url,\n", + " username=username,\n", + " password=password,\n", + " index_name=index_name,\n", + " keyword_index_name=keyword_index_name,\n", + " search_type=\"hybrid\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Retriever options\n", + "\n", + "This section shows how to use `Neo4jVector` as a retriever." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, "outputs": [ { "data": { @@ -344,7 +377,7 @@ "Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../modules/state_of_the_union.txt'})" ] }, - "execution_count": 13, + "execution_count": 15, "metadata": {}, "output_type": "execute_result" } @@ -365,7 +398,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 16, "metadata": {}, "outputs": [], "source": [ @@ -375,7 +408,7 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 17, "metadata": {}, "outputs": [], "source": [ @@ -386,7 +419,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 18, "metadata": {}, "outputs": [ { @@ -396,7 +429,7 @@ " 'sources': '../../modules/state_of_the_union.txt'}" ] }, - "execution_count": 16, + "execution_count": 18, "metadata": {}, "output_type": "execute_result" } @@ -432,7 +465,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.4" + "version": "3.8.8" } }, "nbformat": 4, diff --git a/libs/langchain/langchain/vectorstores/neo4j_vector.py b/libs/langchain/langchain/vectorstores/neo4j_vector.py index 01ee7b27b1..06f262eae7 100644 --- a/libs/langchain/langchain/vectorstores/neo4j_vector.py +++ b/libs/langchain/langchain/vectorstores/neo4j_vector.py @@ -1,5 +1,6 @@ from __future__ import annotations +import enum import logging import uuid from typing import ( @@ -20,13 +21,44 @@ from langchain.vectorstores.base import VectorStore from langchain.vectorstores.utils import DistanceStrategy DEFAULT_DISTANCE_STRATEGY = DistanceStrategy.COSINE - -distance_mapping = { +DISTANCE_MAPPING = { DistanceStrategy.EUCLIDEAN_DISTANCE: "euclidean", DistanceStrategy.COSINE: "cosine", } +class SearchType(str, enum.Enum): + """Enumerator of the Distance strategies.""" + + VECTOR = "vector" + HYBRID = "hybrid" + + +DEFAULT_SEARCH_TYPE = SearchType.VECTOR + + +def _get_search_index_query(search_type: SearchType) -> str: + type_to_query_map = { + SearchType.VECTOR: ( + "CALL db.index.vector.queryNodes($index, $k, $embedding) YIELD node, score " + ), + SearchType.HYBRID: ( + "CALL { " + "CALL db.index.vector.queryNodes($index, $k, $embedding) " + "YIELD node, score " + "RETURN node, score UNION " + "CALL db.index.fulltext.queryNodes($keyword_index, $query, {limit: $k}) " + "YIELD node, score " + "WITH collect({node:node, score:score}) AS nodes, max(score) AS max " + "UNWIND nodes AS n " + "RETURN n.node AS node, (n.score / max) AS score " # We use 0 as min + "} " + "WITH node, max(score) AS score ORDER BY score DESC LIMIT $k " # dedup + ), + } + return type_to_query_map[search_type] + + def check_if_not_null(props: List[str], values: List[Any]) -> None: for prop, value in zip(props, values): if not value: @@ -82,9 +114,11 @@ class Neo4jVector(VectorStore): self, embedding: Embeddings, *, + search_type: SearchType = SearchType.VECTOR, username: Optional[str] = None, password: Optional[str] = None, url: Optional[str] = None, + keyword_index_name: Optional[str] = "keyword", database: str = "neo4j", index_name: str = "vector", node_label: str = "Chunk", @@ -153,12 +187,14 @@ class Neo4jVector(VectorStore): self.embedding = embedding self._distance_strategy = distance_strategy self.index_name = index_name + self.keyword_index_name = keyword_index_name self.node_label = node_label self.embedding_node_property = embedding_node_property self.text_node_property = text_node_property self.logger = logger or logging.getLogger(__name__) self.override_relevance_score_fn = relevance_score_fn self.retrieval_query = retrieval_query + self.search_type = search_type # Calculate embedding dimension self.embedding_dimension = len(embedding.embed_query("foo")) @@ -263,6 +299,39 @@ class Neo4jVector(VectorStore): except IndexError: return None + def retrieve_existing_fts_index(self) -> Optional[str]: + """ + Check if the fulltext index exists in the Neo4j database + + This method queries the Neo4j database for existing fts indexes + with the specified name. + + Returns: + (Tuple): keyword index information + """ + + index_information = self.query( + "SHOW INDEXES YIELD name, type, labelsOrTypes, properties, options " + "WHERE type = 'FULLTEXT' AND (name = $keyword_index_name " + "OR (labelsOrTypes = [$node_label] AND " + "properties = [$text_node_property])) " + "RETURN name, labelsOrTypes, properties, options ", + params={ + "keyword_index_name": self.keyword_index_name, + "node_label": self.node_label, + "text_node_property": self.text_node_property, + }, + ) + # sort by index_name + index_information = sort_by_index_name(index_information, self.index_name) + try: + self.keyword_index_name = index_information[0]["name"] + self.text_node_property = index_information[0]["properties"][0] + node_label = index_information[0]["labelsOrTypes"][0] + return node_label + except IndexError: + return None + def create_new_index(self) -> None: """ This method constructs a Cypher query and executes it @@ -282,10 +351,23 @@ class Neo4jVector(VectorStore): "node_label": self.node_label, "embedding_node_property": self.embedding_node_property, "embedding_dimension": self.embedding_dimension, - "similarity_metric": distance_mapping[self._distance_strategy], + "similarity_metric": DISTANCE_MAPPING[self._distance_strategy], } self.query(index_query, params=parameters) + def create_new_keyword_index(self) -> None: + """ + This method constructs a Cypher query and executes it + to create a new full text index in Neo4j. + """ + fts_index_query = ( + f"CREATE FULLTEXT INDEX {self.keyword_index_name} " + f"FOR (n:`{self.node_label}`) ON EACH " + f"[n.`{self.text_node_property}`]" + ) + + self.query(fts_index_query) + @property def embeddings(self) -> Embeddings: return self.embedding @@ -299,6 +381,7 @@ class Neo4jVector(VectorStore): metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, create_id_index: bool = True, + search_type: SearchType = SearchType.VECTOR, **kwargs: Any, ) -> Neo4jVector: if ids is None: @@ -309,13 +392,13 @@ class Neo4jVector(VectorStore): store = cls( embedding=embedding, + search_type=search_type, **kwargs, ) - - # Check if the index already exists + # Check if the vector index already exists embedding_dimension = store.retrieve_existing_index() - # If the index doesn't exist yet + # If the vector index doesn't exist yet if not embedding_dimension: store.create_new_index() # If the index already exists, check if embedding dimensions match @@ -328,6 +411,17 @@ class Neo4jVector(VectorStore): f"Vector index dimension: {embedding_dimension}" ) + if search_type == SearchType.HYBRID: + fts_node_label = store.retrieve_existing_fts_index() + # If the FTS index doesn't exist yet + if not fts_node_label: + store.create_new_keyword_index() + else: # Validate that FTS and Vector index use the same information + if not fts_node_label == store.node_label: + raise ValueError( + "Vector and keyword index don't index the same node label" + ) + # Create unique constraint for faster import if create_id_index: store.query( @@ -429,6 +523,7 @@ class Neo4jVector(VectorStore): return self.similarity_search_by_vector( embedding=embedding, k=k, + query=query, ) def similarity_search_with_score( @@ -444,11 +539,13 @@ class Neo4jVector(VectorStore): List of Documents most similar to the query and score for each """ embedding = self.embedding.embed_query(query) - docs = self.similarity_search_with_score_by_vector(embedding=embedding, k=k) + docs = self.similarity_search_with_score_by_vector( + embedding=embedding, k=k, query=query + ) return docs def similarity_search_with_score_by_vector( - self, embedding: List[float], k: int = 4 + self, embedding: List[float], k: int = 4, **kwargs: Any ) -> List[Tuple[Document, float]]: """ Perform a similarity search in the Neo4j database using a @@ -478,12 +575,14 @@ class Neo4jVector(VectorStore): self.retrieval_query if self.retrieval_query else default_retrieval ) - read_query = ( - "CALL db.index.vector.queryNodes($index, $k, $embedding) " - "YIELD node, score " - ) + retrieval_query - - parameters = {"index": self.index_name, "k": k, "embedding": embedding} + read_query = _get_search_index_query(self.search_type) + retrieval_query + parameters = { + "index": self.index_name, + "k": k, + "embedding": embedding, + "keyword_index": self.keyword_index_name, + "query": kwargs["query"], + } results = self.query(read_query, params=parameters) @@ -517,7 +616,7 @@ class Neo4jVector(VectorStore): List of Documents most similar to the query vector. """ docs_and_scores = self.similarity_search_with_score_by_vector( - embedding=embedding, k=k + embedding=embedding, k=k, **kwargs ) return [doc for doc, _ in docs_and_scores] @@ -596,6 +695,8 @@ class Neo4jVector(VectorStore): cls: Type[Neo4jVector], embedding: Embeddings, index_name: str, + search_type: SearchType = DEFAULT_SEARCH_TYPE, + keyword_index_name: Optional[str] = None, **kwargs: Any, ) -> Neo4jVector: """ @@ -607,9 +708,17 @@ class Neo4jVector(VectorStore): the `index_name` definition. """ + if search_type == SearchType.HYBRID and not keyword_index_name: + raise ValueError( + "keyword_index name has to be specified " + "when using hybrid search option" + ) + store = cls( embedding=embedding, index_name=index_name, + keyword_index_name=keyword_index_name, + search_type=search_type, **kwargs, ) @@ -630,6 +739,20 @@ class Neo4jVector(VectorStore): f"Vector index dimension: {embedding_dimension}" ) + if search_type == SearchType.HYBRID: + fts_node_label = store.retrieve_existing_fts_index() + # If the FTS index doesn't exist yet + if not fts_node_label: + raise ValueError( + "The specified keyword index name does not exist. " + "Make sure to check if you spelled it correctly" + ) + else: # Validate that FTS and Vector index use the same information + if not fts_node_label == store.node_label: + raise ValueError( + "Vector and keyword index don't index the same node label" + ) + return store @classmethod diff --git a/libs/langchain/tests/integration_tests/vectorstores/test_neo4jvector.py b/libs/langchain/tests/integration_tests/vectorstores/test_neo4jvector.py index 6af4291a49..4a6a9a3abf 100644 --- a/libs/langchain/tests/integration_tests/vectorstores/test_neo4jvector.py +++ b/libs/langchain/tests/integration_tests/vectorstores/test_neo4jvector.py @@ -3,7 +3,7 @@ import os from typing import List from langchain.docstore.document import Document -from langchain.vectorstores import Neo4jVector +from langchain.vectorstores.neo4j_vector import Neo4jVector, SearchType from langchain.vectorstores.utils import DistanceStrategy from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings @@ -26,7 +26,7 @@ def drop_vector_indexes(store: Neo4jVector) -> None: all_indexes = store.query( """ SHOW INDEXES YIELD name, type - WHERE type = "VECTOR" + WHERE type IN ["VECTOR", "FULLTEXT"] RETURN name """ ) @@ -331,3 +331,142 @@ def test_neo4jvector_prefer_indexname_insert() -> None: Document(page_content="foo", metadata={}), ] drop_vector_indexes(existing_index) + + +def test_neo4jvector_hybrid() -> None: + """Test end to end construction with hybrid search.""" + text_embeddings = FakeEmbeddingsWithOsDimension().embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + docsearch = Neo4jVector.from_embeddings( + text_embeddings=text_embedding_pairs, + embedding=FakeEmbeddingsWithOsDimension(), + url=url, + username=username, + password=password, + pre_delete_collection=True, + search_type=SearchType.HYBRID, + ) + output = docsearch.similarity_search("foo", k=1) + assert output == [Document(page_content="foo")] + + drop_vector_indexes(docsearch) + + +def test_neo4jvector_hybrid_deduplicate() -> None: + """Test result deduplication with hybrid search.""" + text_embeddings = FakeEmbeddingsWithOsDimension().embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + docsearch = Neo4jVector.from_embeddings( + text_embeddings=text_embedding_pairs, + embedding=FakeEmbeddingsWithOsDimension(), + url=url, + username=username, + password=password, + pre_delete_collection=True, + search_type=SearchType.HYBRID, + ) + output = docsearch.similarity_search("foo", k=3) + assert output == [ + Document(page_content="foo"), + Document(page_content="bar"), + Document(page_content="baz"), + ] + + drop_vector_indexes(docsearch) + + +def test_neo4jvector_hybrid_retrieval_query() -> None: + """Test custom retrieval_query with hybrid search.""" + text_embeddings = FakeEmbeddingsWithOsDimension().embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + docsearch = Neo4jVector.from_embeddings( + text_embeddings=text_embedding_pairs, + embedding=FakeEmbeddingsWithOsDimension(), + url=url, + username=username, + password=password, + pre_delete_collection=True, + search_type=SearchType.HYBRID, + retrieval_query="RETURN 'moo' AS text, score, {test: 'test'} AS metadata", + ) + output = docsearch.similarity_search("foo", k=1) + assert output == [Document(page_content="moo", metadata={"test": "test"})] + + drop_vector_indexes(docsearch) + + +def test_neo4jvector_hybrid_retrieval_query2() -> None: + """Test custom retrieval_query with hybrid search.""" + text_embeddings = FakeEmbeddingsWithOsDimension().embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + docsearch = Neo4jVector.from_embeddings( + text_embeddings=text_embedding_pairs, + embedding=FakeEmbeddingsWithOsDimension(), + url=url, + username=username, + password=password, + pre_delete_collection=True, + search_type=SearchType.HYBRID, + retrieval_query="RETURN node.text AS text, score, {test: 'test'} AS metadata", + ) + output = docsearch.similarity_search("foo", k=1) + assert output == [Document(page_content="foo", metadata={"test": "test"})] + + drop_vector_indexes(docsearch) + + +def test_neo4jvector_missing_keyword() -> None: + """Test hybrid search with missing keyword_index_search.""" + text_embeddings = FakeEmbeddingsWithOsDimension().embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + docsearch = Neo4jVector.from_embeddings( + text_embeddings=text_embedding_pairs, + embedding=FakeEmbeddingsWithOsDimension(), + url=url, + username=username, + password=password, + pre_delete_collection=True, + ) + try: + Neo4jVector.from_existing_index( + embedding=FakeEmbeddingsWithOsDimension(), + url=url, + username=username, + password=password, + index_name="vector", + search_type=SearchType.HYBRID, + ) + except ValueError as e: + assert str(e) == ( + "keyword_index name has to be specified when " "using hybrid search option" + ) + drop_vector_indexes(docsearch) + + +def test_neo4jvector_hybrid_from_existing() -> None: + """Test hybrid search with missing keyword_index_search.""" + text_embeddings = FakeEmbeddingsWithOsDimension().embed_documents(texts) + text_embedding_pairs = list(zip(texts, text_embeddings)) + Neo4jVector.from_embeddings( + text_embeddings=text_embedding_pairs, + embedding=FakeEmbeddingsWithOsDimension(), + url=url, + username=username, + password=password, + pre_delete_collection=True, + search_type=SearchType.HYBRID, + ) + existing = Neo4jVector.from_existing_index( + embedding=FakeEmbeddingsWithOsDimension(), + url=url, + username=username, + password=password, + index_name="vector", + keyword_index_name="keyword", + search_type=SearchType.HYBRID, + ) + + output = existing.similarity_search("foo", k=1) + assert output == [Document(page_content="foo")] + + drop_vector_indexes(existing)