25

好的,首先,对不起我的英语。

我正在一个 Web 项目中工作,当我在输入框中输入内容时会显示建议,但我想使用 IndexedDB 来提高 Firefox 中的查询速度。

使用 WebSQL 我有这句话:

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 做同样的事情,我有这个代码:

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();
        }
    }
};

但是太慢了,我的代码有问题。我想知道有没有更好的方法来做到这一点。

谢谢回复。

4

3 回答 3

28

我终于找到了解决这个问题的方法。

解决方案包括在搜索词和搜索词之间用“z”字母在结尾处绑定一个键范围。例子:

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();
    }
  };

因为我需要对结果进行排序,所以我在事务之前定义了一个数组,然后我们在加载所有数据的时候调用它,像这样:

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
    }
  };
于 2012-01-22T13:38:17.600 回答
3

我一直在试验 IndexedDB,发现它非常慢,再加上它的 api 的复杂性,我根本不确定它是否值得使用。

这实际上取决于您拥有多少数据,但可能值得在内存中进行搜索,然后您可以将数据从某种存储中编组和取消编组,无论是 indexedDB 还是更简单的 localStorage。

于 2011-08-19T09:09:42.313 回答
2

我在同一个问题上浪费了大约 2 个小时,我发现了真正的问题。

这里的解决方案:

  • 替换IDBCursor.PREVprev (这很糟糕,但这是解决方案)

IDBCursor.PREV目前在 Chrome 上被窃听 (26/02/2013)

于 2013-02-26T14:07:08.580 回答