mirror of
https://github.com/hwchase17/langchain
synced 2024-11-08 07:10:35 +00:00
align chroma vectorstore get with chromadb to enable where filtering (#6686)
allows for where filtering on collection via get - Description: aligns langchain chroma vectorstore get with underlying [chromadb collection get](https://github.com/chroma-core/chroma/blob/main/chromadb/api/models/Collection.py#L103) allowing for where filtering, etc. - Issue: NA - Dependencies: none - Tag maintainer: @rlancemartin, @eyurtsev - Twitter handle: @pappanaka
This commit is contained in:
parent
9ca3b4645e
commit
70f7c2bb2e
@ -491,6 +491,73 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"retriever.get_relevant_documents(query)[0]"
|
"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": {
|
"metadata": {
|
||||||
|
@ -16,6 +16,7 @@ from langchain.vectorstores.utils import maximal_marginal_relevance
|
|||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
import chromadb
|
import chromadb
|
||||||
import chromadb.config
|
import chromadb.config
|
||||||
|
from chromadb.api.types import ID, OneOrMany, Where, WhereDocument
|
||||||
|
|
||||||
logger = logging.getLogger()
|
logger = logging.getLogger()
|
||||||
DEFAULT_K = 4 # Number of Documents to return.
|
DEFAULT_K = 4 # Number of Documents to return.
|
||||||
@ -316,17 +317,43 @@ class Chroma(VectorStore):
|
|||||||
"""Delete the collection."""
|
"""Delete the collection."""
|
||||||
self._client.delete_collection(self._collection.name)
|
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.
|
"""Gets the collection.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
include (Optional[List[str]]): List of fields to include from db.
|
ids: The ids of the embeddings to get. Optional.
|
||||||
Defaults to None.
|
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:
|
if include is not None:
|
||||||
return self._collection.get(include=include)
|
kwargs["include"] = include
|
||||||
else:
|
|
||||||
return self._collection.get()
|
return self._collection.get(**kwargs)
|
||||||
|
|
||||||
def persist(self) -> None:
|
def persist(self) -> None:
|
||||||
"""Persist the collection.
|
"""Persist the collection.
|
||||||
|
Loading…
Reference in New Issue
Block a user