我正在嘗試使用JavaScript和JSON編寫一個基本的實驗性搜索系統,其中包含JSON文件中包含的可搜索數據。文件中列出了多個「帖子」,每個帖子都有一個「標籤」數組。我的意圖是搜索每個帖子標籤,並只檢索標籤與查詢匹配的帖子,比如「有趣的貓咪視頻」(帖子必須包含所有三個標籤,「有趣」,「貓」和「視頻「,待退回)。如何在Javascript中使用JSON進行多維搜索?
我特別關心的是性能。我相信這種技術會效率低下,因爲大約有2000個帖子,每個帖子都有5到50個標籤,但它必須用JavaScript來完成。我已經從這個網站參考瞭如何最大化性能,儘管我可以做一些額外的幫助。
這裏是我到目前爲止的代碼,用於存儲數據:
{
"index": {
"count": "2",
"posts": [
{
"id": "1",
"date": "2014-11-21 17:16:39 GMT",
"url": "http://url/",
"image": "http://big_image/",
"thumbnail": "http://little_image/",
"tags": ["funny", "cat", "picture", "falling", "chair", "window sill", "funny"]
},
{
"id": "2",
"date": "2014-11-20 17:57:32 GMT",
"url": "http://url1/",
"image": "http://big_image1/",
"thumbnail": "http://little_image1/",
"tags": ["funny", "cat", "picture", "jumping", "water", "bath", "funny"]
}
]
}
}
這是我的javascript:
var query = "funny cat bath".split(" ");
var data = JSON.parse("THE JSON GOES HERE");
var count = data.index.count;
var index = data.index.posts;
for (var i = 0, indexLength = index.length; i < indexLength; i++) {
tags = index[i].tags;
for (var q = 0, queryLength = query.length; q < queryLength; q++) {
if(tags.indexOf(query[q]) !== false) {
console.log(index[i]);
}
}
}
不幸的是,我無法弄清楚如何讓它只返回具有全部三個標籤的帖子,並且它返回具有提供的任何標籤的所有帖子。不僅如此,它還會返回重複項。
有沒有人有更好的解決方案?我卡住了。
我要重申,這必須是JavaScript的。如果使用數據庫在服務器端寫這些東西,我會更加高興,但這不是一種選擇。 – Forest 2014-11-24 17:33:09
你考慮過使用[IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API)嗎?它是客戶端,但正如名字所暗示的那樣,它是爲性能而編制的。 – 2014-11-24 17:36:50
這實際上很有趣,約旦,但我需要該頁面能夠加載任何計算機並執行相同的操作,因此加載文件。除非我錯過了一些東西,IndexedDB需要將數據存儲在瀏覽器中? – Forest 2014-11-24 17:39:22