Skip to content

Commit b02f552

Browse files
committed
fix(collections): correct logic in exists() method
- fix existing condition in `Collections.exists()` method - add tests to verify collection existence checking - ensure proper return when collection is in cache
1 parent 47285fc commit b02f552

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

src/typesense/collections.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,17 +61,28 @@ def __contains__(self, collection_name: str) -> bool:
6161
"""
6262
Check if a collection exists in Typesense.
6363
64+
This method tries to retrieve the specified collection to check for its existence,
65+
utilizing the Collection.retrieve() method but without caching non-existent collections.
66+
6467
Args:
6568
collection_name (str): The name of the collection to check.
6669
6770
Returns:
6871
bool: True if the collection exists, False otherwise.
6972
"""
73+
if collection_name in self.collections:
74+
try:
75+
self.collections[collection_name].retrieve()
76+
return True
77+
except Exception:
78+
self.collections.pop(collection_name, None)
79+
return False
80+
7081
try:
71-
all_collections = self.retrieve()
82+
Collection(self.api_call, collection_name).retrieve()
83+
return True
7284
except Exception:
7385
return False
74-
return any(coll["name"] == collection_name for coll in all_collections)
7586

7687
def __getitem__(self, collection_name: str) -> Collection[TDoc]:
7788
"""

tests/collections_test.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,3 +293,16 @@ def test_actual_retrieve(
293293

294294
response[0].pop("created_at")
295295
assert response == expected
296+
297+
298+
def test_actual_contains(
299+
actual_collections: Collections,
300+
delete_all: None,
301+
create_collection: None,
302+
) -> None:
303+
"""Test that the Collections object can check if a collection exists in Typesense."""
304+
# Test for existing collection
305+
assert "companies" in actual_collections
306+
307+
# Test for non-existing collection
308+
assert "non_existent_collection" not in actual_collections

0 commit comments

Comments
 (0)