Skip to main content

Search Suggestions Guide

The Search Suggestions Engine provides contextual recommendations to help users discover related content and improve their search queries. This guide covers configuration, usage, and advanced features.

Overview

The Search Suggestions Engine offers several types of suggestions:

  • Related Queries: Similar searches that might be relevant
  • Spelling Corrections: Automatic correction of typos and misspellings
  • Synonyms: Alternative terms with similar meanings
  • Query Expansions: Broader or more specific versions of the query
  • Trending Topics: Currently popular search topics
  • Category Suggestions: Relevant categories or topics

Basic Usage

1. Initialize the Engine

from search_interface.suggestions import SearchSuggestionsEngine, SuggestionConfig

# Create configuration
config = SuggestionConfig(
use_related_queries=True,
use_spelling_corrections=True,
use_synonyms=True,
max_suggestions=8
)

# Initialize engine
engine = SearchSuggestionsEngine(config)

2. Get Suggestions

# Get suggestions for a query
query = "python tutorial"
suggestions = await engine.get_suggestions(query, user_id="user123")

print("Search suggestions:")
for suggestion in suggestions:
print(f"- {suggestion.text} ({suggestion.suggestion_type})")
print(f" Confidence: {suggestion.confidence:.2f}")
print(f" Reason: {suggestion.reason}")

3. Track Selections

# Track when user selects a suggestion
selected_suggestion = suggestions[0]
await engine.track_selection(selected_suggestion, user_id="user123")

Configuration Options

SuggestionConfig

config = SuggestionConfig(
# Suggestion types
use_related_queries=True, # Include related queries
use_spelling_corrections=True, # Include spelling corrections
use_synonyms=True, # Include synonym suggestions
use_query_expansions=True, # Include query expansions
use_trending_topics=True, # Include trending topics
use_category_suggestions=True, # Include category suggestions

# Suggestion limits
max_suggestions=8, # Maximum number of suggestions
min_query_length=2, # Minimum query length
max_query_length=100, # Maximum query length

# Scoring weights
related_weight=0.3, # Weight for related queries
spelling_weight=0.2, # Weight for spelling corrections
synonym_weight=0.2, # Weight for synonyms
expansion_weight=0.15, # Weight for query expansions
trending_weight=0.1, # Weight for trending topics
category_weight=0.05, # Weight for category suggestions

# Performance settings
cache_enabled=True, # Enable caching
cache_ttl_seconds=300, # Cache time-to-live
debounce_delay_ms=200, # Delay before processing

# Personalization
personalization_enabled=True, # Enable personalized suggestions
learning_rate=0.1, # Learning rate for personalization
history_retention_days=90, # Days to retain query history
)

Advanced Features

1. Custom Suggestion Sources

# Add custom suggestion sources
custom_sources = [
{
"name": "product_catalog",
"weight": 0.3,
"suggestions": [
"python course",
"python book",
"python video"
]
},
{
"name": "user_feedback",
"weight": 0.2,
"suggestions": [
"python best practices",
"python debugging",
"python testing"
]
}
]

await engine.add_custom_sources(custom_sources)

2. Contextual Suggestions

# Get suggestions with context
context = {
"category": "programming",
"language": "python",
"difficulty": "beginner",
"user_level": "intermediate"
}

suggestions = await engine.get_suggestions(
"tutorial",
user_id="user123",
context=context
)

3. Multi-language Support

# Configure multi-language support
config = SuggestionConfig(
supported_languages=["en", "es", "fr", "de"],
default_language="en",
language_detection=True
)

engine = SearchSuggestionsEngine(config)

# Get suggestions in specific language
suggestions = await engine.get_suggestions(
"tutorial",
user_id="user123",
language="es"
)

4. Real-time Suggestions

# Get real-time suggestions as user types
async def get_realtime_suggestions(query: str, user_id: str):
"""Get suggestions with real-time updates."""
suggestions = await engine.get_suggestions(query, user_id)

# Filter by confidence and relevance
filtered_suggestions = [
s for s in suggestions
if s.confidence > 0.5 and s.relevance_score > 0.7
]

return filtered_suggestions

Integration Examples

1. Search Interface Integration

class SearchInterface:
def __init__(self):
self.suggestions_engine = SearchSuggestionsEngine(SuggestionConfig())
self.query_history = []

async def on_query_submit(self, query: str, user_id: str):
"""Handle query submission with suggestions."""
# Store query in history
self.query_history.append(query)

# Get suggestions for next search
suggestions = await self.suggestions_engine.get_suggestions(
query, user_id
)

# Show suggestions to user
return {
"query": query,
"suggestions": suggestions,
"history": self.query_history[-5:] # Last 5 queries
}

2. Mobile App Integration

class MobileSearchInterface:
def __init__(self):
self.suggestions_engine = SearchSuggestionsEngine(SuggestionConfig())
self.cache = {}

async def get_suggestions(self, query: str, user_id: str):
"""Get suggestions optimized for mobile."""
# Check cache first
cache_key = f"{user_id}:{query}"
if cache_key in self.cache:
return self.cache[cache_key]

# Get suggestions
suggestions = await self.suggestions_engine.get_suggestions(query, user_id)

# Limit suggestions for mobile
mobile_suggestions = suggestions[:5]

# Cache for performance
self.cache[cache_key] = mobile_suggestions
return mobile_suggestions

3. Voice Search Integration

class VoiceSearchInterface:
def __init__(self):
self.suggestions_engine = SearchSuggestionsEngine(SuggestionConfig())

async def process_voice_input(self, transcribed_text: str, user_id: str):
"""Process voice input with suggestions."""
# Get suggestions for transcribed text
suggestions = await self.suggestions_engine.get_suggestions(
transcribed_text, user_id
)

# If confidence is low, suggest alternatives
if suggestions and suggestions[0].confidence < 0.8:
return {
"original": transcribed_text,
"suggestions": suggestions,
"needs_confirmation": True
}

return {
"original": transcribed_text,
"suggestions": suggestions,
"needs_confirmation": False
}

Performance Optimization

1. Caching

# Enable caching for better performance
config = SuggestionConfig(
cache_enabled=True,
cache_ttl_seconds=300, # 5 minutes
cache_max_size=1000 # Maximum cached entries
)

engine = SearchSuggestionsEngine(config)

2. Batch Processing

# Process multiple queries in batch
queries = ["python tutorial", "java course", "javascript guide"]
batch_suggestions = await engine.get_batch_suggestions(queries, user_id="user123")

for query, suggestions in batch_suggestions.items():
print(f"Query: {query}")
print(f"Suggestions: {[s.text for s in suggestions]}")

3. Async Processing

# Process suggestions asynchronously
async def process_suggestions_async(queries: List[str], user_id: str):
"""Process multiple queries asynchronously."""
tasks = [
engine.get_suggestions(query, user_id)
for query in queries
]

results = await asyncio.gather(*tasks)
return dict(zip(queries, results))

Analytics and Monitoring

1. Track Suggestion Performance

# Track suggestion metrics
await engine.track_suggestion_metrics(
query="python tutorial",
suggestions_shown=8,
suggestions_clicked=3,
user_id="user123"
)

2. Monitor Performance

# Get performance metrics
metrics = await engine.get_performance_metrics()

print("Suggestions performance:")
print(f"Average response time: {metrics['avg_response_time_ms']}ms")
print(f"Cache hit rate: {metrics['cache_hit_rate']:.2%}")
print(f"Total suggestions: {metrics['total_suggestions']}")
print(f"Click-through rate: {metrics['click_through_rate']:.2%}")

3. A/B Testing

# Test different configurations
config_a = SuggestionConfig(max_suggestions=5)
config_b = SuggestionConfig(max_suggestions=10)

# Run A/B test
test_results = await engine.run_ab_test(
config_a, config_b,
test_duration_days=7
)

print("A/B test results:")
print(f"Config A click rate: {test_results['config_a']['click_rate']:.2%}")
print(f"Config B click rate: {test_results['config_b']['click_rate']:.2%}")

Troubleshooting

Common Issues

  1. Slow Response Times

    • Enable caching
    • Reduce max_suggestions
    • Increase debounce_delay_ms
  2. Irrelevant Suggestions

    • Adjust scoring weights
    • Add more custom sources
    • Improve query history quality
  3. Memory Usage

    • Reduce cache_max_size
    • Decrease history_retention_days
    • Use batch processing

Debug Mode

# Enable debug mode for troubleshooting
config = SuggestionConfig(debug=True)
engine = SearchSuggestionsEngine(config)

# Get detailed debug information
suggestions = await engine.get_suggestions("python tutorial", user_id="user123")
print(f"Debug info: {suggestions[0].debug_info}")

Best Practices

  1. Start Simple: Begin with basic configuration and add features gradually
  2. Monitor Performance: Track response times and user engagement
  3. Test Regularly: Use A/B testing to optimize suggestions
  4. Update Sources: Keep suggestion sources current and relevant
  5. Handle Errors: Implement proper error handling and fallbacks
  6. Cache Strategically: Use caching to improve performance
  7. Personalize Gradually: Start with basic personalization and enhance over time

Next Steps