Python Code Samples - Module 2: Basic Search Operations¶
This directory contains focused Python examples for basic search operations in Azure AI Search. Each file demonstrates a specific aspect of search functionality with clear, beginner-friendly code.
๐ Files Overview¶
Core Search Operations (Files 01-05)¶
01_simple_text_search.py- Basic text search and result handling02_phrase_search.py- Exact phrase matching with quotes03_boolean_search.py- Boolean operators (AND, OR, NOT)04_wildcard_search.py- Pattern matching with wildcards05_field_search.py- Field-specific and multi-field searches
Advanced Features (Files 06-08)¶
06_result_processing.py- Processing and formatting search results07_error_handling.py- Comprehensive error handling and validation08_search_patterns.py- Advanced search patterns and strategies
๐ฏ Complete Coverage Matrix¶
| Topic | Python | C# | JavaScript | REST | Description |
|---|---|---|---|---|---|
| Simple Text Search | โ | โ | โ | โ | Basic keyword searching |
| Phrase Search | โ | โ | โ | โ | Exact phrase matching |
| Boolean Search | โ | โ | โ | โ | AND, OR, NOT operators |
| Wildcard Search | โ | โ | โ | โ | Pattern matching with * |
| Field Search | โ | โ | โ | โ | Field-specific searches |
| Result Processing | โ | โ | โ | โ | Formatting and analysis |
| Error Handling | โ | โ | โ | โ | Robust error management |
| Search Patterns | โ | โ | โ | โ | Advanced strategies |
๐ Getting Started¶
โ ๏ธ CRITICAL FIRST STEP: Prerequisites Setup¶
Before running ANY Python examples, you MUST run the prerequisites setup:
# Navigate to the parent directory
cd ../
# Run the prerequisites setup script
python setup_prerequisites.py
What this does:
- ๐ Tests your Azure AI Search connection
- ๐๏ธ Creates the handbook-samples index with comprehensive schema
- ๐ Uploads 10 sample documents with rich content
- ๐งช Tests all search operations to ensure everything works
- ๐ Provides a summary of what's ready
Time Required: 5-10 minutes
Prerequisites¶
# Install required packages
pip install azure-search-documents python-dotenv
# Set environment variables
export AZURE_SEARCH_SERVICE_ENDPOINT="https://your-service.search.windows.net"
export AZURE_SEARCH_API_KEY="your-api-key"
export AZURE_SEARCH_INDEX_NAME="handbook-samples"
Quick Start¶
# 1. FIRST: Run prerequisites setup (from parent directory)
cd ../
python setup_prerequisites.py
# 2. THEN: Run Python examples
cd python/
python 01_simple_text_search.py
python 02_phrase_search.py
python 03_boolean_search.py
# ... and so on
๐ Learning Path¶
Beginner Path (Recommended Order)¶
- Start Here:
01_simple_text_search.py- Learn basic search concepts - Precision:
02_phrase_search.py- Understand exact matching - Logic:
03_boolean_search.py- Combine terms with operators - Flexibility:
04_wildcard_search.py- Pattern matching techniques - Targeting:
05_field_search.py- Search specific fields - Processing:
06_result_processing.py- Handle and format results - Safety:
07_error_handling.py- Robust error handling - Strategies:
08_search_patterns.py- Advanced search patterns
Quick Reference¶
- Need basic search? โ
01_simple_text_search.py - Want exact phrases? โ
02_phrase_search.py - Combining terms? โ
03_boolean_search.py - Partial matching? โ
04_wildcard_search.py - Specific fields? โ
05_field_search.py - Format results? โ
06_result_processing.py - Handle errors? โ
07_error_handling.py - Advanced patterns? โ
08_search_patterns.py
๐ก Key Concepts Covered¶
Search Types¶
- Simple Text Search: Basic keyword searching
- Phrase Search: Exact phrase matching with quotes
- Boolean Search: AND, OR, NOT operators
- Wildcard Search: Pattern matching with *
- Field Search: Targeting specific document fields
Result Handling¶
- Score Analysis: Understanding relevance scores
- Result Formatting: Display and export options
- Filtering: Score-based and custom filtering
- Sorting: By score, field, or custom criteria
Error Handling¶
- Input Validation: Query sanitization and validation
- HTTP Errors: Handling Azure Search API errors
- Fallback Strategies: Alternative queries when searches fail
- User-Friendly Messages: Converting technical errors
Search Patterns¶
- Progressive Search: From specific to broad strategies
- Fallback Search: Automatic strategy switching
- Multi-Field Search: Prioritized field searching
- Pattern Selection: Choosing the right approach
๐ง Code Structure¶
Each file follows a consistent structure:
"""
Module docstring explaining the concepts
"""
# Imports and setup
import os, sys, logging
from azure.search.documents import SearchClient
# Main class demonstrating the concept
class ConceptDemo:
def __init__(self, search_client=None):
# Initialize with search client
def main_method(self, params):
# Core functionality demonstration
def helper_methods(self):
# Supporting functionality
# Demonstration function
def demonstrate_concept():
# Show the concept in action
# Best practices function
def concept_best_practices():
# Guidelines and tips
# Main execution
if __name__ == "__main__":
demonstrate_concept()
concept_best_practices()
๐ฏ Usage Examples¶
Basic Search¶
from azure.search.documents import SearchClient
from azure.core.credentials import AzureKeyCredential
# Initialize client
search_client = SearchClient(
endpoint="https://your-service.search.windows.net",
index_name="your-index",
credential=AzureKeyCredential("your-api-key")
)
# Simple search
results = search_client.search(search_text="python programming")
for result in results:
print(f"Title: {result.get('title')}")
print(f"Score: {result['@search.score']}")
Using the Example Classes¶
# Import from any example file
from simple_text_search import SimpleTextSearch
# Initialize and use
search_ops = SimpleTextSearch()
results = search_ops.basic_search("machine learning", top=5)
search_ops.display_results(results)
๐ก๏ธ Error Handling¶
All examples include basic error handling:
try:
results = search_client.search(search_text=query)
# Process results
except HttpResponseError as e:
print(f"Search error: {e.status_code}")
except Exception as e:
print(f"Unexpected error: {str(e)}")
๐ Performance Tips¶
- Limit Results: Use
topparameter to limit result count - Select Fields: Use
selectto return only needed fields - Field Targeting: Use
search_fieldsfor specific field searches - Caching: Cache frequently used search results
- Error Handling: Implement proper error handling and retries
๐ Cross-Language Learning¶
These Python examples complement the other language implementations:
- C# Examples - .NET implementations with async/await patterns
- JavaScript Examples - Node.js and browser examples
- REST API Examples - Direct HTTP API calls for any language
- Interactive Notebooks - Jupyter examples for experimentation
๐ฏ Learning Approach:
- Sequential: Follow 01-08 in order for structured learning
- Cross-Language: Compare implementations across platforms
- Topic-Focused: Jump to specific search types as needed
- Interactive: Use notebooks for hands-on experimentation
๐ Next Steps¶
After working through these examples:
- โ Try modifying the queries and parameters
- ๐ง Implement your own search functionality
- ๐ Explore other language examples
- ๐ฏ Check out the interactive notebooks
- ๐ Move on to Module 3: Index Management
Happy Coding! ๐โจ