IndexedDB模糊搜索 [英] IndexedDB Fuzzy Search
问题描述
好的,首先,对不起我的英语。
Ok, first of all, sorry for my English.
我正在一个网络项目中工作,显示当我在输入框中输入内容时,但是我想要使用IndexedDB来提高Firefox中的查询速度。
I'm working in a web project that show suggests when I type something in the inputbox, but I want to use IndexedDB to improve the query speed in Firefox.
使用WebSQL我有这句话:
With WebSQL I have this sentence:
db.transaction(function (tx) {
var SQL = 'SELECT "column1",
"column2"
FROM "table"
WHERE "column1" LIKE ?
ORDER BY "sortcolumn" DESC
LIMIT 6';
tx.executeSql(SQL, [searchTerm + '%'], function(tx, rs) {
// Process code here
});
});
我想用IndexedDB做同样的事情,我有这个代码:
I want to do same thing with IndexedDB and I have this code:
db.transaction(['table'], 'readonly')
.objectStore('table')
.index('sortcolumn')
.openCursor(null, 'prev')
.onsuccess = function (e) {
e || (e = event);
var cursor = e.target.result;
if (cursor) {
if (cursor.value.column1.substr(0, searchTerm.length) == searchTerm) {
// Process code here
} else {
cursor.continue();
}
}
};
但是太慢了,而且我的代码很麻烦..我想知道有没有更好的方法这样做。
But there's too slow and my code is buggy.. I want to know is there a better way to do this.
感谢回复。
推荐答案
我终于找到了这个问题的解决方案。
I finally found the solution to this problem.
解决方案包括在搜索词和搜索词之间用一个'z'字母限定一个键范围。示例:
The solution consist to bound a key range between the search term and the search term with a 'z' letter at the final. Example:
db.transaction(['table'], 'readonly')
.objectStore('table')
.openCursor(
IDBKeyRange.bound(searchTerm, searchTerm + '\uffff'), // The important part, thank Velmont to point out
'prev')
.onsuccess = function (e) {
e || (e = event);
var cursor = e.target.result;
if (cursor) {
// console.log(cursor.value.column1 + ' = ' + cursor.value.column2);
cursor.continue();
}
};
因为我需要订购结果,所以我在交易前定义了一个数组,然后我们称之为当我们加载所有数据时,如下所示:
Because I need to order the result, so I defined a array before the transaction, then we call it when we loaded all data, like this:
var result = [];
db.transaction(['table'], 'readonly')
.objectStore('table')
.openCursor(
IDBKeyRange.bound(searchTerm, searchTerm + '\uffff'), // The important part, thank Velmont to point out
'prev')
.onsuccess = function (e) {
e || (e = event);
var cursor = e.target.result;
if (cursor) {
result.push([cursor.value.column1, cursor.value.sortcolumn]);
cursor.continue();
} else {
if (result.length) {
result.sort(function (a, b) {
return a[1] - b[2];
});
}
// Process code here
}
};
这篇关于IndexedDB模糊搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!