索引数据库游标范围在多个属性上

kes*_*kes 7 javascript indexeddb

我在indexeddb对象库上有两个属性的复合索引,并希望根据这两个属性的范围检索游标.

这是商店中的示例对象:

{species: 'Oak',xcoord: 123456, ycoord: 654321}
Run Code Online (Sandbox Code Playgroud)

和索引:

treeStore.createIndex("treelocation", ["xcoord","ycoord"], { unique: false });
Run Code Online (Sandbox Code Playgroud)

索引创建是成功的,我可以在Chrome开发人员工具中看到它,但是现在我想在x和y坐标上打开一个带有键范围的光标(这将是地图的范围).

在线搜索我看不到怎么做,打开带有一系列键范围的索引似乎不起作用.

谢谢

安德鲁

Jos*_*ell 7

范围建议是答案的一部分,但即使使用数组键,它实际上也只是一维范围,而不是数据的 2 维(或 N 维)选择。使用您当前的架构,您需要执行以下操作:

index.openCursor([lowX, lowY], [highX, highY]).onsuccess = function(e) {
    var cursor = e.target.result;
    if (!cursor) return; // done!

    var x = cursor.key[0], y = cursor.key[1];
    // assert(lowX <= x && x <= highX);
    if (y < lowY) {
        cursor.continue([x, lowY]);
    } else if (y > highY) {
        cursor.continue([x + 1, lowY]);
    } else {
        processRecord(cursor.value); // we got one!
        cursor.continue();
    }
};
Run Code Online (Sandbox Code Playgroud)

(如果坐标不是整数,请替换+ 1为适当的 epsilon)

我已经发布了一个通用解决方案的例子:

https://gist.github.com/inexorabletash/704e9688f99ac12dd336


Myr*_*tol 6

我被告知解决方案确实如此IDBKeyRange.bound([lowX,lowY],[highX,highY]).

  • 这不会像您期望的那样表现.范围`IDBKeyRange.bound([2,2],[4,4])`包括[3,0]和[3,5]之类的值为[2,2] <[3,0] <[3, 5] <[4,4]每个键的定义(https://w3c.github.io/IndexedDB/#key-construct)也就是说,你需要做额外的过滤,因为这个解决方案本身就是不够.例如,如果看到键[x,y_less_than_min],则忽略它并使用"continue([x,lowY])"前进光标; 如果看到键[x,y_greater_than_max],忽略它并用`continue([x + 1,lowY])前进光标. (5认同)