🔍 Code Extractor

function reset_collection

Maturity: 44

Deletes an existing ChromaDB collection and logs the operation, requiring an application restart to recreate the collection.

File:
/tf/active/vicechatdev/docchat/reset_collection.py
Lines:
14 - 37
Complexity:
simple

Purpose

This function is used to reset a ChromaDB vector database collection by deleting it completely. It's typically used during development, testing, or when you need to clear all stored embeddings and start fresh. The function connects to a ChromaDB HTTP server, attempts to delete the specified collection, and logs all operations. Note that it does not recreate the collection automatically - the application must be restarted for that to happen.

Source Code

def reset_collection():
    """Delete and recreate the ChromaDB collection"""
    try:
        # Connect to ChromaDB
        logger.info(f"Connecting to ChromaDB at {config.CHROMA_HOST}:{config.CHROMA_PORT}")
        client = chromadb.HttpClient(
            host=config.CHROMA_HOST,
            port=config.CHROMA_PORT
        )
        
        # Try to delete existing collection
        try:
            logger.info(f"Attempting to delete collection: {config.CHROMA_COLLECTION_NAME}")
            client.delete_collection(name=config.CHROMA_COLLECTION_NAME)
            logger.info(f"✓ Deleted collection: {config.CHROMA_COLLECTION_NAME}")
        except Exception as e:
            logger.info(f"Collection doesn't exist or couldn't be deleted: {e}")
        
        logger.info("Collection reset complete. Restart the app to create a new collection.")
        
    except Exception as e:
        logger.error(f"Failed to reset collection: {e}")
        import traceback
        logger.error(f"Traceback: {traceback.format_exc()}")

Return Value

This function does not return any value (implicitly returns None). It performs side effects by deleting a ChromaDB collection and logging the results.

Dependencies

  • chromadb
  • logging

Required Imports

import chromadb
import logging
import config

Conditional/Optional Imports

These imports are only needed under specific conditions:

import traceback

Condition: only used when an exception occurs during collection reset to log detailed error information

Optional

Usage Example

import chromadb
import logging

# Setup configuration
class config:
    CHROMA_HOST = 'localhost'
    CHROMA_PORT = 8000
    CHROMA_COLLECTION_NAME = 'my_collection'

# Setup logger
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

# Define the function
def reset_collection():
    try:
        logger.info(f"Connecting to ChromaDB at {config.CHROMA_HOST}:{config.CHROMA_PORT}")
        client = chromadb.HttpClient(
            host=config.CHROMA_HOST,
            port=config.CHROMA_PORT
        )
        try:
            logger.info(f"Attempting to delete collection: {config.CHROMA_COLLECTION_NAME}")
            client.delete_collection(name=config.CHROMA_COLLECTION_NAME)
            logger.info(f"✓ Deleted collection: {config.CHROMA_COLLECTION_NAME}")
        except Exception as e:
            logger.info(f"Collection doesn't exist or couldn't be deleted: {e}")
        logger.info("Collection reset complete. Restart the app to create a new collection.")
    except Exception as e:
        logger.error(f"Failed to reset collection: {e}")
        import traceback
        logger.error(f"Traceback: {traceback.format_exc()}")

# Call the function
reset_collection()

Best Practices

  • Ensure ChromaDB server is running and accessible before calling this function
  • This function will permanently delete all data in the specified collection - use with caution in production environments
  • The function requires a module-level 'logger' object to be configured before use
  • After calling this function, restart the application to recreate the collection with fresh data
  • Consider implementing a confirmation mechanism before calling this function to prevent accidental data loss
  • The function uses broad exception handling which may mask specific errors - consider more granular error handling for production use
  • Ensure the config module has all required attributes (CHROMA_HOST, CHROMA_PORT, CHROMA_COLLECTION_NAME) defined before calling

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_collection_creation 70.4% similar

    A diagnostic test function that verifies Chroma DB functionality by creating a test collection, adding a document, querying it, and cleaning up.

    From: /tf/active/vicechatdev/test_chroma_collections.py
  • function main_v58 67.8% similar

    Command-line interface function that orchestrates the cleaning of ChromaDB collections by removing duplicates and similar documents, with options to skip collections and customize the cleaning process.

    From: /tf/active/vicechatdev/chromadb-cleanup/main.py
  • function test_chroma_collections 65.2% similar

    A diagnostic function that tests connectivity to ChromaDB instances across multiple connection methods and lists all available collections with their metadata.

    From: /tf/active/vicechatdev/test_chroma_collections.py
  • function clean_collection 63.3% similar

    Cleans a ChromaDB collection by removing duplicate and similar documents using hash-based and similarity-based deduplication techniques, then saves the cleaned data to a new collection.

    From: /tf/active/vicechatdev/chromadb-cleanup/main.py
  • function save_data_to_chromadb 62.2% similar

    Saves a list of document dictionaries to a ChromaDB vector database collection, optionally including embeddings and metadata.

    From: /tf/active/vicechatdev/chromadb-cleanup/main copy.py
← Back to Browse