diff --git a/pinecone/control/pinecone.py b/pinecone/control/pinecone.py index b2b33fcc..7d6ce02e 100644 --- a/pinecone/control/pinecone.py +++ b/pinecone/control/pinecone.py @@ -544,6 +544,33 @@ def describe_index(self, name: str): return IndexModel(description) + def has_index(self, name: str) -> bool: + """Checks if a Pinecone index exists. + + :param name: The name of the index to check for existence. + :return: Returns `True` if the index exists, `False` otherwise. + + ### Example Usage + + ```python + import os + from pinecone import Pinecone + + api_key = os.environ.get("PINECONE_API_KEY") + pc = Pinecone(api_key=api_key) + + if pc.has_index("my_index_name"): + print("The index exists") + else: + print("The index does not exist") + ``` + """ + + if name in self.list_indexes().names(): + return True + else: + return False + def configure_index( self, name: str, @@ -737,12 +764,12 @@ def Index(self, name: str = "", host: str = "", **kwargs): pc = Pinecone(api_key=api_key) pc.create_index( - name='my-index', + name='my_index', dimension=1536, metric='cosine', spec=ServerlessSpec(cloud='aws', region='us-west-2') ) - index = pc.Index('my-index') + index = pc.Index('my_index') # Now you're ready to perform data operations index.query(vector=[...], top_k=10) diff --git a/tests/integration/control/serverless/test_has_index.py b/tests/integration/control/serverless/test_has_index.py new file mode 100644 index 00000000..11b96b78 --- /dev/null +++ b/tests/integration/control/serverless/test_has_index.py @@ -0,0 +1,18 @@ +from tests.integration.helpers import random_string + + +class TestHasIndex: + def test_index_exists_success(self, client, create_sl_index_params): + name = create_sl_index_params["name"] + client.create_index(**create_sl_index_params) + has_index = client.has_index(name) + assert has_index == True + + def test_index_does_not_exist(self, client): + name = random_string(8) + has_index = client.has_index(name) + assert has_index == False + + def test_has_index_with_null_index_name(self, client): + has_index = client.has_index("") + assert has_index == False