從資料到產品:打造搜尋、可視化與即時查詢的資料應用實踐
經過前幾篇文章的努力,我們已經成功從 Taobao 等電商網站抓取了大量商品資料,並完成清洗、去重與入庫。然而,如果這些數據僅存在資料庫中而沒有進一步應用,將無法產生真正的價值。
本篇文章將帶你從「資料供應方」進入「資料應用層」,透過建構 API、整合搜尋引擎與前端展示介面,讓資料具備可查詢、可分析、可互動的能力。
一、什麼是資料 API?讓資料動起來
資料 API(Application Programming Interface)是一種讓應用程式能夠透過 HTTP 請求方式查詢資料庫的機制。它通常提供:
RESTful 風格的端點設計
輸入參數控制(如查詢條件、分頁、排序)
JSON 格式輸出,易於被前端或第三方系統使用
例如:
GET /api/products?q=耳機&price_min=100&price_max=500
二、使用 FastAPI 快速構建查詢 API
FastAPI 是一個現代、高效的 Python Web 框架,非常適合構建資料型應用。
安裝 FastAPI 及 Uvicorn:
pip install fastapi uvicorn pymongo
建立商品查詢 API(連接 MongoDB):
from fastapi import FastAPI, Queryfrom pymongo import MongoClient
from typing import List
app = FastAPI()
client = MongoClient("mongodb://localhost:27017")
collection = client.taobao.products
@app.get("/api/products")
def search_products(
q: str = Query(None),
price_min: float = Query(0),
price_max: float = Query(999999),
limit: int = 20
):
query = {
"price": {"$gte": price_min, "$lte": price_max}
}
if q:
query["title"] = {"$regex": q, "$options": "i"}
results = collection.find(query).limit(limit)
return [
{
"id": str(item["_id"]),
"title": item["title"],
"price": item["price"]
}
for item in results
]
執行:
uvicorn main:app --reload
三、整合 Elasticsearch 搜尋:支援中文與高亮顯示
若資料量龐大且需要支援「模糊搜尋」、「中文分詞」,則可使用 Elasticsearch 作為底層搜尋引擎。
安裝並設定中文分詞器(如 jieba)
在 elasticsearch.yml
中加入:
index.analysis.analyzer.default.type: ik_max_word
FastAPI + Elasticsearch 搜尋實作:
from elasticsearch import Elasticsearchfrom fastapi import FastAPI, Query
app = FastAPI()
es = Elasticsearch("http://localhost:9200")
@app.get("/api/search")
def search_product(q: str = Query(...)):
body = {
"query": {
"match": {
"title": {
"query": q,
"operator": "and"
}
}
},
"highlight": {
"fields": {
"title": {}
}
}
}
res = es.search(index="taobao", body=body)
return [
{
"id": hit["_id"],
"title": hit["highlight"]["title"][0],
"price": hit["_source"]["price"]
}
for hit in res["hits"]["hits"]
]
四、建立可視化報表:從數據變成圖表
使用 Chart.js、Echarts 等前端圖表庫,可以透過後端統計 API 將資料轉為圖表。
統計商品價格分佈(FastAPI + MongoDB):
@app.get("/api/price_stats")def price_histogram():
pipeline = [
{"$bucket": {
"groupBy": "$price",
"boundaries": [0, 100, 300, 500, 1000, 5000],
"default": "5000+",
"output": {"count": {"$sum": 1}}
}}
]
data = list(collection.aggregate(pipeline))
return data
前端配合 Chart.js:
new Chart(ctx, {type: 'bar',
data: {
labels: ['0-100', '100-300', '300-500', '500-1000', '1000-5000', '5000+'],
datasets: [{
label: '商品數',
data: [50, 120, 90, 40, 25, 10]
}]
}
});
五、實時查詢與前端整合技巧
1. 與前端 Vue / React 整合 API
fetch('/api/products?q=藍牙耳機&price_min=100').then(res => res.json())
.then(data => console.log(data))
2. 跨域處理(CORS):
from fastapi.middleware.cors import CORSMiddlewareapp.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 可限定前端域名
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
3. 設定 API 限流:
可透過 Nginx 或 Redis 實作簡易流量控制。
六、安全與效能優化策略
API Key 認證:保護敏感資料與流量濫用
Redis 快取:熱門查詢結果先快取,降低 DB 負擔
查詢效能監控:Mongo 慢查詢日誌 / Elasticsearch 查詢耗時統計
異常監控與警報:搭配 Sentry、Prometheus 等工具
七、延伸應用場景
打造商品搜尋網站(如內部版 Taobao 小搜尋引擎)
結合 Superset / Grafana 展示分析儀表板
將 API 封裝成第三方平台服務,對開發者開放
結語:資料不只是存放,更是啟用
本文,我們把「靜態的資料」轉化為「動態的應用」,讓數據成為網站的核心能力,真正達到從爬蟲 → 清洗 → 儲存 → 查詢與展示的閉環。如果說前面的幾篇是為了「取得與整理資料」,那這篇就是「讓資料真正創造價值」。
接下來,你可以選擇:
拓展資料源(加入更多站點、不同領域)
擴充應用功能(推薦系統、用戶行為分析)
建立資料平台(供開發者使用的 API 集)
Articles related to APIs :
Introduction to Taobao API: Basic Concepts and Application Scenarios
Taobao API: Authentication & Request Flow Explained with Code Examples
Using the Taobao API to Retrieve Product Information and Implement Keyword Search
How to Use the Taobao API to Build a Product Price Tracker and Alert System
Using the Taobao API to Build a Category-Based Product Recommendation System
Taobao Data Source Analysis and Technical Selection: API vs Web Scraping vs Hybrid Crawling
如您需要 Taobao API 可聯係我們:support@luckdata.com