Skip to content

Commit 1d0b686

Browse files
authored
Add has_index() (#385)
## Problem Currently, users can not easily check if an index exists or not. The .names() iterator on the list_indexes response object is not super discoverable. ## Solution Add has_index() which internally calls describe_index() and returns true if the index exists, false otherwise. ## Type of Change - [X] New feature (non-breaking change which adds functionality) ## Test Plan Added integration tests. --- - To see the specific tasks where the Asana app for GitHub is being used, see below: - https://app.asana.com/0/0/1207972900637843
1 parent 3d20906 commit 1d0b686

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

pinecone/control/pinecone.py

+29-2
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,33 @@ def describe_index(self, name: str):
544544

545545
return IndexModel(description)
546546

547+
def has_index(self, name: str) -> bool:
548+
"""Checks if a Pinecone index exists.
549+
550+
:param name: The name of the index to check for existence.
551+
:return: Returns `True` if the index exists, `False` otherwise.
552+
553+
### Example Usage
554+
555+
```python
556+
import os
557+
from pinecone import Pinecone
558+
559+
api_key = os.environ.get("PINECONE_API_KEY")
560+
pc = Pinecone(api_key=api_key)
561+
562+
if pc.has_index("my_index_name"):
563+
print("The index exists")
564+
else:
565+
print("The index does not exist")
566+
```
567+
"""
568+
569+
if name in self.list_indexes().names():
570+
return True
571+
else:
572+
return False
573+
547574
def configure_index(
548575
self,
549576
name: str,
@@ -737,12 +764,12 @@ def Index(self, name: str = "", host: str = "", **kwargs):
737764
738765
pc = Pinecone(api_key=api_key)
739766
pc.create_index(
740-
name='my-index',
767+
name='my_index',
741768
dimension=1536,
742769
metric='cosine',
743770
spec=ServerlessSpec(cloud='aws', region='us-west-2')
744771
)
745-
index = pc.Index('my-index')
772+
index = pc.Index('my_index')
746773
747774
# Now you're ready to perform data operations
748775
index.query(vector=[...], top_k=10)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from tests.integration.helpers import random_string
2+
3+
4+
class TestHasIndex:
5+
def test_index_exists_success(self, client, create_sl_index_params):
6+
name = create_sl_index_params["name"]
7+
client.create_index(**create_sl_index_params)
8+
has_index = client.has_index(name)
9+
assert has_index == True
10+
11+
def test_index_does_not_exist(self, client):
12+
name = random_string(8)
13+
has_index = client.has_index(name)
14+
assert has_index == False
15+
16+
def test_has_index_with_null_index_name(self, client):
17+
has_index = client.has_index("")
18+
assert has_index == False

0 commit comments

Comments
 (0)