← back to Watches

SEARCH_API_DOCS.md

424 lines

# Omega Watches - Advanced Search & Sort API Documentation

## 🚀 SQLite FTS5 Powered Search System

The Omega Watches system now features a comprehensive search and filtering system powered by SQLite FTS5, providing lightning-fast, deep search capabilities across all watch data.

## Base URL
```
http://45.61.58.125:7600
```

## 📚 Search Endpoints

### 1. Basic Full-Text Search
```http
GET /api/search/watches?q={query}&limit={limit}&offset={offset}
```

**Example:**
```bash
curl "http://45.61.58.125:7600/api/search/watches?q=speedmaster"
```

**Features:**
- Porter stemming for intelligent word matching
- Highlighted matches with `<mark>` tags
- Text snippets showing context

---

### 2. Advanced Search with Filters & Sort
```http
GET /api/advanced-search?q={query}&collection={collection}&minPrice={min}&maxPrice={max}&sort={sortType}&facets=true
```

**Parameters:**
- `q` - Full-text search query
- `collection` - Filter by collection name
- `reference` - Filter by reference number
- `yearFrom` / `yearTo` - Year range filter
- `minPrice` / `maxPrice` - Price range filter
- `minAppreciation` - Minimum appreciation rate
- `sort` - Sort options (see below)
- `facets` - Include facet counts (true/false)
- `highlight` - Include highlighted matches (true/false)
- `snippet` - Include text snippets (true/false)
- `limit` - Results per page (default: 50)
- `offset` - Pagination offset

**Sort Options:**
- `relevance` - FTS5 relevance ranking (default)
- `price_asc` - Price ascending
- `price_desc` - Price descending
- `year_asc` - Year ascending
- `year_desc` - Year descending
- `appreciation_desc` - Appreciation rate descending
- `name_asc` - Name alphabetical
- `name_desc` - Name reverse alphabetical

**Example:**
```bash
# Search Speedmaster, sorted by price descending, with facets
curl "http://45.61.58.125:7600/api/advanced-search?q=speedmaster&sort=price_desc&facets=true"

# Filter by collection and price range
curl "http://45.61.58.125:7600/api/advanced-search?collection=Seamaster&minPrice=5000&maxPrice=15000&sort=appreciation_desc"

# Year range with appreciation filter
curl "http://45.61.58.125:7600/api/advanced-search?yearFrom=1960&yearTo=1970&minAppreciation=100&sort=year_asc"
```

---

### 3. Multi-Field Search
```http
POST /api/advanced-search/multi-field
```

**Body:**
```json
{
  "fields": {
    "name": "speedmaster",
    "description": "chronograph",
    "collection": "racing"
  },
  "matchAll": false,  // false = OR logic, true = AND logic
  "sort": "relevance"
}
```

**Example:**
```bash
curl -X POST "http://45.61.58.125:7600/api/advanced-search/multi-field" \
  -H "Content-Type: application/json" \
  -d '{"fields": {"name": "speedmaster", "description": "moon"}}'
```

---

### 4. Smart Search (Typo Tolerance)
```http
GET /api/advanced-search/smart?q={query}
```

**Features:**
- Automatic typo correction
- Fuzzy matching with wildcards
- Search suggestions

**Example:**
```bash
curl "http://45.61.58.125:7600/api/advanced-search/smart?q=spedmaster"
```

---

### 5. Collection Search
```http
GET /api/search/collection/{collectionName}
```

**Example:**
```bash
curl "http://45.61.58.125:7600/api/search/collection/Speedmaster"
```

---

### 6. Price Range Search
```http
GET /api/search/price?min={minPrice}&max={maxPrice}
```

**Example:**
```bash
curl "http://45.61.58.125:7600/api/search/price?min=5000&max=10000"
```

---

### 7. Top Appreciating Watches
```http
GET /api/search/appreciation?limit={limit}
```

**Example:**
```bash
curl "http://45.61.58.125:7600/api/search/appreciation?limit=5"
```

---

### 8. Search Suggestions
```http
GET /api/search/suggestions?q={query}
```

**Example:**
```bash
curl "http://45.61.58.125:7600/api/search/suggestions?q=speed"
```

---

### 9. Analytics Dashboard
```http
GET /api/advanced-search/analytics
```

**Returns:**
- Total watches count
- Average price
- Price range (min/max)
- Top appreciating models
- Collection statistics
- Year distribution

**Example:**
```bash
curl "http://45.61.58.125:7600/api/advanced-search/analytics"
```

---

## 🎯 Faceted Search

When `facets=true` is included, the response includes aggregated counts for:

### Collections Facet
```json
"collections": [
  { "collection": "Speedmaster", "count": 4 },
  { "collection": "Seamaster", "count": 5 }
]
```

### Price Range Facets
```json
"priceRanges": [
  { "label": "Under $1,000", "min": 0, "max": 1000, "count": 2 },
  { "label": "$1,000 - $5,000", "min": 1000, "max": 5000, "count": 5 },
  { "label": "$5,000 - $10,000", "min": 5000, "max": 10000, "count": 6 }
]
```

### Decade Facets
```json
"decades": [
  { "decade": "1960s", "count": 8 },
  { "decade": "1970s", "count": 4 },
  { "decade": "1980s", "count": 3 }
]
```

---

## 🔥 Advanced Use Cases

### 1. Investment Grade Watches
Find watches with high appreciation potential:
```bash
curl "http://45.61.58.125:7600/api/advanced-search?minAppreciation=50&maxPrice=10000&sort=appreciation_desc"
```

### 2. Vintage Collection Search
Search vintage watches from specific era:
```bash
curl "http://45.61.58.125:7600/api/advanced-search?yearFrom=1957&yearTo=1970&collection=Speedmaster&sort=year_asc"
```

### 3. Budget-Friendly Options
Find affordable watches with good appreciation:
```bash
curl "http://45.61.58.125:7600/api/advanced-search?maxPrice=5000&minAppreciation=20&sort=price_asc"
```

### 4. Combined Text & Filter Search
Search with text and apply multiple filters:
```bash
curl "http://45.61.58.125:7600/api/advanced-search?q=chronograph&collection=Speedmaster&minPrice=5000&maxPrice=15000&sort=relevance&facets=true"
```

---

## 📊 Response Format

### Standard Search Response
```json
{
  "success": true,
  "query": "speedmaster",
  "filters": {
    "collection": "Speedmaster",
    "minPrice": 5000,
    "maxPrice": 15000,
    "yearFrom": null,
    "yearTo": null,
    "minAppreciation": null
  },
  "sort": "price_desc",
  "total": 4,
  "limit": 50,
  "offset": 0,
  "results": [
    {
      "id": "speedmaster-alaska",
      "name": "Speedmaster Alaska Project",
      "collection": "Speedmaster",
      "reference": "311.32.42.30.04.001",
      "year_introduced": 2008,
      "description": "Limited edition with special white dial...",
      "avg_price": 12500,
      "appreciation_rate": 45.5,
      "highlighted_name": "<mark>Speedmaster</mark> Alaska Project",
      "text_snippet": "...legendary <b>Speedmaster</b> designed for..."
    }
  ],
  "facets": {
    "collections": [...],
    "priceRanges": [...],
    "decades": [...]
  }
}
```

---

## 🚀 Performance Features

- **SQLite FTS5** - Full-text search with Porter tokenizer
- **Indexed Fields** - Fast queries on collection, price, year
- **WAL Mode** - Concurrent read operations
- **Result Highlighting** - Visual match indicators
- **Smart Caching** - 5-minute TTL on frequently accessed data
- **Pagination** - Efficient large result set handling

---

## 🔧 Database Structure

### Main Tables
- `watches` - Primary watch data with prices and appreciation
- `watches_fts` - FTS5 virtual table for text search
- `price_history` - Historical price tracking

### Indexes
- `idx_watches_collection` - Collection queries
- `idx_watches_price` - Price range queries
- `idx_price_history_watch` - Price history lookups

---

## 📝 Examples Collection

### Find Moonwatch Models
```bash
curl "http://45.61.58.125:7600/api/search/watches?q=moonwatch"
```

### Search Professional Chronographs
```bash
curl "http://45.61.58.125:7600/api/advanced-search?q=professional+chronograph&sort=year_desc"
```

### Seamaster Collection Under $10k
```bash
curl "http://45.61.58.125:7600/api/advanced-search?collection=Seamaster&maxPrice=10000&sort=price_asc"
```

### Top 5 Investment Watches
```bash
curl "http://45.61.58.125:7600/api/search/appreciation?limit=5"
```

### Analytics Overview
```bash
curl "http://45.61.58.125:7600/api/advanced-search/analytics"
```

---

## 🎨 Frontend Integration

### JavaScript Example
```javascript
// Advanced search with filters
async function searchWatches() {
  const params = new URLSearchParams({
    q: 'speedmaster',
    collection: 'Speedmaster',
    minPrice: 5000,
    maxPrice: 15000,
    sort: 'price_desc',
    facets: true,
    limit: 20
  });
  
  const response = await fetch(`/api/advanced-search?${params}`);
  const data = await response.json();
  
  console.log(`Found ${data.total} watches`);
  console.log('Facets:', data.facets);
  console.log('Results:', data.results);
}
```

### React Hook Example
```javascript
function useWatchSearch(query, filters, sort) {
  const [results, setResults] = useState([]);
  const [facets, setFacets] = useState({});
  
  useEffect(() => {
    const searchParams = new URLSearchParams({
      q: query,
      ...filters,
      sort,
      facets: true
    });
    
    fetch(`/api/advanced-search?${searchParams}`)
      .then(res => res.json())
      .then(data => {
        setResults(data.results);
        setFacets(data.facets);
      });
  }, [query, filters, sort]);
  
  return { results, facets };
}
```

---

## 🔐 Rate Limiting & Security

- Rate limiting ready (can be configured)
- Input validation on all parameters
- SQL injection protection via parameterized queries
- XSS protection in highlighted results

---

## 📈 Future Enhancements

- [ ] Saved searches with user accounts
- [ ] Search history tracking
- [ ] ML-powered recommendations
- [ ] Visual similarity search
- [ ] Export search results
- [ ] Real-time price alerts
- [ ] Batch search operations

---

## Support

For issues or questions about the search API:
- Check API health: `http://45.61.58.125:7600/api/health`
- View current data: `http://45.61.58.125:7600`

Last Updated: 2024
Version: 2.0.0