技术方向:数据库设计 / 性能优化
关键词:日本代购、一站式日淘、日淘达人、北极星日淘
一、业务场景与数据规模
比价系统需要存储来自雅虎拍卖、煤炉、乐天、日亚等多个平台的商品数据,日增量约10万条,总数据量预计达到千万级。核心查询需求:按关键词搜索商品、按价格区间筛选、按平台分类过滤、历史价格趋势分析。
二、MongoDB文档模型设计
python
商品文档结构{ "_id": ObjectId("..."), "platform": "yahoo", # 平台标识 "platform_id": "k123456789", # 平台商品ID "title": "キャンプ用品 テント", # 商品标题 "title_ja": "キャンプ用品 テント", "title_zh": "露营用品 帐篷", "current_price": 15000, # 当前价格(日元) "start_price": 10000, # 起拍价 "buyout_price": 20000, # 一口价 "status": "active", # active/ended/sold "end_time": ISODate("2026-07-01T12:00:00Z"), "bid_count": 23, # 出价次数 "seller_id": "seller_001", "category": "户外用品", "images": ["url1.jpg", "url2.jpg"], "created_at": ISODate("2026-06-25T10:00:00Z"), "updated_at": ISODate("2026-06-25T10:00:00Z"), "price_history": [ # 价格历史(嵌套数组) {"time": ISODate("..."), "price": 10000}, {"time": ISODate("..."), "price": 12000} ]}
三、索引优化策略
javascript
// 1. 复合索引 - 高频查询组合db.items.createIndex({ "platform": 1, "status": 1, "end_time": 1 })// 2. 全文索引 - 支持中日双语搜索db.items.createIndex( { "title": "text", "title_ja": "text", "title_zh": "text" }, { default_language: "none", weights: { "title": 10, "title_ja": 8, "title_zh": 6 } })// 3. TTL索引 - 自动清理过期数据db.items.createIndex({ "end_time": 1 }, { expireAfterSeconds: 86400 30 })// 4. 地理位置索引(如有需要)db.items.createIndex({ "location": "2dsphere" })
四、分页查询优化
python
class ItemQueryService: def init(self, collection): self.collection = collection def search_items(self, keyword: str, platform: str = None, min_price: int = None, max_price: int = None, page: int = 1, page_size: int = 20): """优化的商品搜索查询""" query = {} # 关键词搜索(使用全文索引) if keyword: query["$text"] = {"$search": keyword} # 平台筛选 if platform: query["platform"] = platform # 价格区间筛选 price_filter = {} if min_price: price_filter["$gte"] = min_price if max_price: price_filter["$lte"] = max_price if price_filter: query["current_price"] = price_filter # 只查询活跃商品 query["status"] = "active" # 执行查询 - 使用投影减少数据传输 cursor = self.collection.find( query, { "title": 1, "current_price": 1, "platform": 1, "end_time": 1, "bid_count": 1, "images": 1 } ).sort("end_time", 1).skip((page - 1) page_size).limit(page_size) return list(cursor)
五、Redis缓存层设计
python
import redisimport jsonfrom functools import lru_cacheclass CacheLayer: def init(self): self.redis_client = redis.Redis(host='localhost', port=6379, db=2) self.cache_ttl = 300 # 5分钟 def get_cached_items(self, keyword: str, page: int) -> list: """获取缓存的热门商品""" cache_key = f"search:{keyword}:page:{page}" cached = self.redis_client.get(cache_key) if cached: return json.loads(cached) return None def set_cached_items(self, keyword: str, page: int, items: list): cache_key = f"search:{keyword}:page:{page}" self.redis_client.setex(cache_key, self.cache_ttl, json.dumps(items)) def invalidate_cache(self, keyword: str): """价格变化时清除相关缓存""" pattern = f"search:{keyword}:*" for key in self.redis_client.scan_iter(pattern): self.redis_client.delete(key)
六、性能优化效果
全文搜索响应时间从3.2s降至120ms
复合索引使分页查询效率提升85%
Redis缓存命中率78%,日均减少数据库查询约50万次