Real-world examples of how to integrate TextMatch API into your applications
Help users find similar products by comparing descriptions. Perfect for recommendation engines and duplicate detection in marketplaces.
When a user views or purchases a product, automatically suggest similar items by comparing product descriptions. This increases engagement and helps users discover products they're likely to purchase.
// Find similar products based on user's viewed item
async function findSimilarProducts(viewedProductId) {
const viewedProduct = await Product.findById(viewedProductId);
const allProducts = await Product.find({
_id: { $ne: viewedProductId }
});
const similarities = [];
for (const product of allProducts) {
const response = await fetch('https://api.textmatch.com/v1/compare', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.TEXTMATCH_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
text1: viewedProduct.description,
text2: product.description
})
});
const result = await response.json();
if (result.similarity_score > 75) {
similarities.push({
product: product,
score: result.similarity_score,
confidence: result.confidence
});
}
}
// Sort by similarity score and return top 5
return similarities
.sort((a, b) => b.score - a.score)
.slice(0, 5);
}
Automatically identify and flag duplicate property listings to maintain a clean, unique inventory.
Real estate platforms often struggle with duplicate listings from different agents or property management companies. Use RoomMatch API to detect potential duplicates before they go live, maintaining data quality and user trust.
# Duplicate detection middleware for new listings
import requests
from typing import List, Dict
class DuplicateDetector:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://api.roommatch.com/v1"
async def check_for_duplicates(self, new_listing: Dict) -> List[Dict]:
# Get existing listings in the same area
existing_listings = await self.get_nearby_listings(
new_listing['latitude'],
new_listing['longitude']
)
duplicates = []
for existing in existing_listings:
response = requests.post(
f"{self.base_url}/compare",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"room1": new_listing['description'],
"room2": existing['description']
}
)
result = response.json()
if result['similarity_score'] > 80:
duplicates.append({
'existing_id': existing['id'],
'similarity_score': result['similarity_score'],
'confidence': result['confidence'],
'action': 'manual_review' if result['similarity_score'] > 90 else 'flag'
})
return duplicates
async def approve_listing(self, listing_id: str) -> bool:
duplicates = await self.check_for_duplicates(listing_id)
if not duplicates:
return True # No duplicates found, approve
high_confidence_duplicates = [
d for d in duplicates
if d['similarity_score'] > 90
]
if high_confidence_duplicates:
await self.flag_for_manual_review(listing_id, duplicates)
return False
await self.flag_as_potential_duplicate(listing_id, duplicates)
return False
Match properties based on interior design style and aesthetic preferences for design-focused applications.
Interior design apps and home decor platforms can use room similarity to help users find properties or rooms that match their aesthetic preferences. Great for mood board creation and style inspiration.
// Find rooms matching user's design preferences
class StyleMatcher {
constructor(apiKey) {
this.apiKey = apiKey;
}
async findSimilarStyles(userPreferences, availableRooms) {
const styleMatches = [];
// Create style preference description
const preferenceDescription = this.createStyleDescription(userPreferences);
for (const room of availableRooms) {
const response = await fetch('https://api.roommatch.com/v1/compare', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
room1: preferenceDescription,
room2: room.description
})
});
const result = await response.json();
if (result.similarity_score > 70) {
styleMatches.push({
room: room,
styleScore: result.similarity_score,
confidence: result.confidence
});
}
}
return styleMatches.sort((a, b) => b.styleScore - a.styleScore);
}
createStyleDescription(preferences) {
return `${preferences.style} style room with ${preferences.colors.join(', ')}
colors, featuring ${preferences.materials.join(', ')} materials and
${preferences.lighting} lighting with ${preferences.furniture} furniture`;
}
}
// Usage example
const matcher = new StyleMatcher('your-api-key');
const userPrefs = {
style: 'Scandinavian',
colors: ['white', 'light wood', 'soft gray'],
materials: ['natural wood', 'linen', 'wool'],
lighting: 'natural',
furniture: 'minimalist'
};
const matches = await matcher.findSimilarStyles(userPrefs, roomDatabase);
Build intelligent recommendation engines that learn from user behavior and preferences.
Combine user viewing history, saved properties, and room similarity scores to create personalized recommendations. The more users interact with your platform, the better the recommendations become.
# Advanced recommendation engine
class PropertyRecommendationEngine:
def __init__(self, api_key):
self.api_key = api_key
async def generate_recommendations(self, user_id, limit=10):
user_profile = await self.build_user_profile(user_id)
candidate_properties = await self.get_candidate_properties(user_id)
scored_properties = []
for property in candidate_properties:
# Calculate similarity to user's preferred style
similarity_score = await self.calculate_similarity(
user_profile['preferred_style'],
property['description']
)
# Apply user behavior weighting
behavior_weight = self.calculate_behavior_weight(
user_id,
property['id']
)
# Compute final recommendation score
final_score = (
similarity_score * 0.6 + # Room similarity weight
behavior_weight * 0.3 + # User behavior weight
property['popularity_score'] * 0.1 # Global popularity
)
scored_properties.append({
'property': property,
'score': final_score,
'similarity_score': similarity_score,
'behavior_weight': behavior_weight
})
# Return top recommendations
return sorted(scored_properties, key=lambda x: x['score'], reverse=True)[:limit]
async def calculate_similarity(self, user_style, property_description):
response = requests.post(
'https://api.roommatch.com/v1/compare',
headers={'Authorization': f'Bearer {self.api_key}'},
json={
'room1': user_style,
'room2': property_description
}
)
return response.json()['similarity_score']
Best practices for integrating RoomMatch API into your application
For large datasets, process comparisons in batches to optimize performance and stay within rate limits.
// Process 100 properties at a time
const batchSize = 100;
for (let i = 0; i < properties.length; i += batchSize)
Cache similarity scores to reduce API calls and improve response times for frequently compared rooms.
const cacheKey = `${room1_id}:${room2_id}`;
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
Implement robust error handling with exponential backoff for rate limits and temporary failures.
if (response.status === 429) {
await sleep(retryDelay * Math.pow(2, attempt));
return await retry(request);
Set up webhooks to receive notifications about batch processing completion and results.
POST /webhooks/roommatch
{
"event": "batch_complete",
"batch_id": "batch_123"
}
Start with our free plan and build something amazing