image-search-api / sdk /python /examples /search_examples.py
mbishu's picture
Initialize SDK and fix vector store issues
a475b1f
Raw History Blame Contribute Delete
5.74 kB
"""
Search Examples - Different ways to search your product catalog.
This example demonstrates various search methods and filtering options
available in the Image Search SDK.
"""
import sys
from pathlib import Path
# Add SDK to path
sdk_path = Path(__file__).parent.parent
sys.path.insert(0, str(sdk_path))
from image_search_sdk import ImageSearchClient, SearchOptions
def main():
print("Search Examples - Image Search SDK")
print("=" * 70)
# Initialize SDK (assuming already set up)
client = ImageSearchClient(
data_dir="./search_data",
vector_store_type="chromadb",
vector_store_config={"mode": "persistent", "path": "./search_data/vectors"}
)
# Connect to database (replace with your actual database)
client.connect_database(
connection_string="sqlite:///products.db",
table_name="products",
id_column="id",
title_column="title",
image_url_column="image_url"
)
# Example 1: Basic Text Search
print("\n" + "=" * 70)
print("EXAMPLE 1: Basic Text Search")
print("=" * 70)
results = client.search_by_text("running shoes", options=SearchOptions(top_k=5))
print(f"\nSearching for 'running shoes' - Found {len(results)} results:")
for i, result in enumerate(results, 1):
print(f"{i}. {result.product.title}")
print(f" Similarity: {result.similarity_score:.3f}")
if result.product.price:
print(f" Price: ${result.product.price:.2f}")
# Example 2: Text Search with Filters
print("\n" + "=" * 70)
print("EXAMPLE 2: Text Search with Category Filter")
print("=" * 70)
results = client.search_by_text(
"laptop",
options=SearchOptions(
top_k=10,
category="Electronics" # Filter by category
)
)
print(f"\nSearching for 'laptop' in Electronics - Found {len(results)} results:")
for i, result in enumerate(results[:3], 1): # Show top 3
print(f"{i}. {result.product.title}")
print(f" Category: {result.product.category}")
# Example 3: Image Search (by file path)
print("\n" + "=" * 70)
print("EXAMPLE 3: Search by Image File")
print("=" * 70)
# Assuming you have a local image file
image_path = "./sample_images/product.jpg"
if Path(image_path).exists():
results = client.search_by_image(
image_path,
options=SearchOptions(top_k=5)
)
print(f"\nSearching by image '{image_path}' - Found {len(results)} results:")
for i, result in enumerate(results, 1):
print(f"{i}. {result.product.title} (score: {result.similarity_score:.3f})")
else:
print(f"\nImage file not found: {image_path}")
print("Place a sample image at this path to test image search.")
# Example 4: Hybrid Search (combining image and text)
print("\n" + "=" * 70)
print("EXAMPLE 4: Combined Image + Text Search")
print("=" * 70)
print("\nNote: For hybrid search, use search_by_image and then filter results by text")
print("or use multiple search queries and combine results.")
# Example 5: Price Range Filtering
print("\n" + "=" * 70)
print("EXAMPLE 5: Search with Custom Filtering")
print("=" * 70)
results = client.search_by_text(
"smartphone",
options=SearchOptions(
top_k=20,
category="Electronics"
)
)
# Post-filter by price
affordable_results = [r for r in results if r.product.price and r.product.price < 500]
print(f"\nAffordable smartphones (< $500): {len(affordable_results)} results")
for i, result in enumerate(affordable_results[:3], 1):
print(f"{i}. {result.product.title}")
print(f" Price: ${result.product.price:.2f}")
print(f" Score: {result.similarity_score:.3f}")
# Example 6: Brand Filtering
print("\n" + "=" * 70)
print("EXAMPLE 6: Search with Brand Filter")
print("=" * 70)
results = client.search_by_text(
"wireless mouse",
options=SearchOptions(
top_k=10,
brand="Logitech" # Specific brand
)
)
print(f"\nLogitech wireless mouse products: {len(results)} results")
# Example 7: Getting Similar Products
print("\n" + "=" * 70)
print("EXAMPLE 7: Find Similar Products")
print("=" * 70)
# First, find a product
initial_results = client.search_by_text("leather wallet", options=SearchOptions(top_k=1))
if initial_results:
product = initial_results[0].product
print(f"\nBase product: {product.title}")
# Now find similar products (by searching with the same image)
if product.image_url:
similar_results = client.search_by_text(
product.title,
options=SearchOptions(
top_k=6, # Get 6 results (including the original)
category=product.category # Same category
)
)
print(f"\nSimilar products:")
for i, result in enumerate(similar_results[1:], 1): # Skip first (same product)
print(f"{i}. {result.product.title}")
print(f" Similarity: {result.similarity_score:.3f}")
# Show statistics
print("\n" + "=" * 70)
print("SYSTEM STATISTICS")
print("=" * 70)
stats = client.get_stats()
print(f"Total indexed products: {stats.get('total_vectors', 0):,}")
print(f"Vector store: {stats.get('store_type', 'N/A')}")
# Cleanup
client.close()
print("\nDone!")
if __name__ == "__main__":
main()