京价保是一个自动监控已购商品价格变化来申请京东价格保护的 Chrome 插件。
很早的时候我就有一个想法,能否把监控已购商品价格过程中形成的价格的数据用某种方式记录下来绘制一个价格走势图。
最近做了一些调研,最终在上周末用百度云的“时序数据库”实现了一个互助的京东价格历史数据库。
废话少说,看看效果:
京造 USB3.0透明分线器 在9月26号售价是39.9元,27号的时候标准价涨到了49,但PLUS价还是39.9元,今天PLUS价也涨了,变成47元。
用时序数据库来实现这个业务有几个非常明显的优势:
- 写入额度极大,通常以时间周期来限制数量
- 储存成本极低,储存几乎不收费
- 查询非常便利,而且不限请求数
由于百度云“时序数据库”这个产品提供了 Node SDK,实际接入过程非常流畅,大概总共只花了一个多小时。
实际上总共也就是接入了写入数据点和查询数据这两个接口,干脆贴两段代码好了:
记录数据
async addPrice(priceInfo: PriceInfo): Promise<any> {
function getTimestamp() {
return Math.round(DateTime.local().startOf('hour').valueOf() / 1000)
}
function buildDataPoint(field: string, sku: string, price: number) {
return {
"metric": "jd",
"field": field,
"tags": {
"sku": sku
},
"timestamp": getTimestamp(),
"value": Number(price)
}
}
let datapoints = [];
datapoints.push(buildDataPoint('price', priceInfo.sku, priceInfo.price))
if (priceInfo.plus_price) {
datapoints.push(buildDataPoint('plus_price', priceInfo.sku, priceInfo.plus_price))
}
if (priceInfo.pingou_price) {
datapoints.push(buildDataPoint('pingou_price', priceInfo.sku, priceInfo.pingou_price))
}
let result = null
try {
result = await this.TSDBClient.writeDatapoints(datapoints)
} catch (error) {
console.error(error);
}
return result
}
查询数据
async getChartData(sku:string) {
var queryList = [
{
"metric": "jd",
"fields": ["price", "plus_price", "pingou_price"],
"filters": {
"start": "15 days ago",
"tags": {
"sku": [sku]
}
}
}
];
let result = null
let chartData: any[] = []
try {
result = await this.TSDBClient.getDatapoints(queryList)
} catch (error) {
console.error(error);
}
if (result.body && result.body.results) {
chartData = _.flatten(_.map(result.body.results[0].groups[0].values, (datapoint: number[]) => {
let points = []
if (datapoint[1] && datapoint[1] > 0) {
points.push({
"timestamp": datapoint[0],
"key": "标准价",
"value": datapoint[1]
})
}
if (datapoint[2] && datapoint[2] > 0) {
points.push({
"timestamp": datapoint[0],
"key": "Plus价",
"value": datapoint[2]
})
}
if (datapoint[3] && datapoint[3] > 0) {
points.push({
"timestamp": datapoint[0],
"key": "拼购价",
"value": datapoint[3]
})
}
return points
}))
}
return chartData;
}
这个功能上线 2 天半时间,目前已经收集了 20 万个价格数据点,覆盖了超过 2 万个 SKU,并且还在以非常快的速度增加。
对了,前端图表用的是支付宝开源的 G2 图表库 相当好用。
Ps. 选择百度云的“时序数据库”的主要原因是因为它的价格非常便宜,每月写入 1500 万数据点的方案只需要 300 元 /年。相比之下阿里云的时序数据库可以说是天价——乞丐版都要 408 元 /月。