diff --git a/docs/extras/modules/data_connection/vectorstores/integrations/chroma.ipynb b/docs/extras/modules/data_connection/vectorstores/integrations/chroma.ipynb index d4f6944b630..1744d2d48c3 100644 --- a/docs/extras/modules/data_connection/vectorstores/integrations/chroma.ipynb +++ b/docs/extras/modules/data_connection/vectorstores/integrations/chroma.ipynb @@ -491,6 +491,73 @@ "source": [ "retriever.get_relevant_documents(query)[0]" ] + }, + { + "cell_type": "markdown", + "id": "275dbd0a", + "metadata": {}, + "source": [ + "### Filtering on metadata\n", + "\n", + "It can be helpful to narrow down the collection before working with it.\n", + "\n", + "For example, collections can be filtered on metadata using the get method." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "a5119221", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'source': 'some_other_source'}\n", + "{'ids': ['1'], 'embeddings': None, 'documents': ['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.'], 'metadatas': [{'source': 'some_other_source'}]}\n" + ] + } + ], + "source": [ + "# create simple ids\n", + "ids = [str(i) for i in range(1, len(docs) + 1)]\n", + "\n", + "# add data\n", + "example_db = Chroma.from_documents(docs, embedding_function, ids=ids)\n", + "docs = example_db.similarity_search(query)\n", + "print(docs[0].metadata)\n", + "\n", + "# update the source for a document\n", + "docs[0].metadata = {\"source\": \"some_other_source\"}\n", + "example_db.update_document(ids[0], docs[0])\n", + "print(example_db._collection.get(ids=[ids[0]]))" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "81600dc1", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'ids': ['1'],\n", + " 'embeddings': None,\n", + " 'documents': ['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.'],\n", + " 'metadatas': [{'source': 'some_other_source'}]}" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# filter collection for updated source\n", + "example_db.get(where={\"source\": \"some_other_source\"})" + ] } ], "metadata": { diff --git a/langchain/vectorstores/chroma.py b/langchain/vectorstores/chroma.py index 132da630e31..394a6026fac 100644 --- a/langchain/vectorstores/chroma.py +++ b/langchain/vectorstores/chroma.py @@ -16,6 +16,7 @@ from langchain.vectorstores.utils import maximal_marginal_relevance if TYPE_CHECKING: import chromadb import chromadb.config + from chromadb.api.types import ID, OneOrMany, Where, WhereDocument logger = logging.getLogger() DEFAULT_K = 4 # Number of Documents to return. @@ -316,17 +317,43 @@ class Chroma(VectorStore): """Delete the collection.""" self._client.delete_collection(self._collection.name) - def get(self, include: Optional[List[str]] = None) -> Dict[str, Any]: + def get( + self, + ids: Optional[OneOrMany[ID]] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Optional[List[str]] = None, + ) -> Dict[str, Any]: """Gets the collection. Args: - include (Optional[List[str]]): List of fields to include from db. - Defaults to None. + ids: The ids of the embeddings to get. Optional. + where: A Where type dict used to filter results by. + E.g. `{"color" : "red", "price": 4.20}`. Optional. + limit: The number of documents to return. Optional. + offset: The offset to start returning results from. + Useful for paging results with limit. Optional. + where_document: A WhereDocument type dict used to filter by the documents. + E.g. `{$contains: {"text": "hello"}}`. Optional. + include: A list of what to include in the results. + Can contain `"embeddings"`, `"metadatas"`, `"documents"`. + Ids are always included. + Defaults to `["metadatas", "documents"]`. Optional. """ + kwargs = { + "ids": ids, + "where": where, + "limit": limit, + "offset": offset, + "where_document": where_document, + } + if include is not None: - return self._collection.get(include=include) - else: - return self._collection.get() + kwargs["include"] = include + + return self._collection.get(**kwargs) def persist(self) -> None: """Persist the collection.