Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/typesense/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,34 @@ def __init__(self, api_call: ApiCall):
self.api_call = api_call
self.collections: typing.Dict[str, Collection[TDoc]] = {}

def __contains__(self, collection_name: str) -> bool:
"""
Check if a collection exists in Typesense.

This method tries to retrieve the specified collection to check for its existence,
utilizing the Collection.retrieve() method but without caching non-existent collections.

Args:
collection_name (str): The name of the collection to check.

Returns:
bool: True if the collection exists, False otherwise.
"""
if collection_name in self.collections:
try: # noqa: WPS229, WPS529

self.collections[collection_name].retrieve() # noqa: WPS529
return True
except Exception:
self.collections.pop(collection_name, None)
return False

try: # noqa: WPS229, WPS529
Collection(self.api_call, collection_name).retrieve()
return True
except Exception:
return False

def __getitem__(self, collection_name: str) -> Collection[TDoc]:
"""
Get or create a Collection instance for a given collection name.
Expand Down
15 changes: 15 additions & 0 deletions tests/collections_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,3 +293,18 @@ def test_actual_retrieve(

response[0].pop("created_at")
assert response == expected


def test_actual_contains(
actual_collections: Collections,
delete_all: None,
create_collection: None,
) -> None:
"""Test that the Collections object can check if a collection exists in Typesense."""
# Test for existing collection
assert "companies" in actual_collections

# Test for non-existing collection
assert "non_existent_collection" not in actual_collections
# Test again
assert "non_existent_collection" not in actual_collections