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

问题描述 投票:7回答:3

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

这是商店中的示例对象:

{species: 'Oak',xcoord: 123456, ycoord: 654321}

和索引:

treeStore.createIndex("treelocation", ["xcoord","ycoord"], { unique: false });

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

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

javascript indexeddb
3个回答
6
投票

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


4
投票

您创建的索引是一个复合索引。它是这样的查询:

index = objectStore.index('treelocation');
index.get([123456, 654321]); 

或者,您可以为每个coorrd使用两个索引。在我看来它更好。

x_index = objectStore.index('xcoord'); 
y_index = objectStore.index('ycoord');
x_species = x_index.get(IDBKeyRange.only(123456)) 
y_species = y_index.get(IDBKeyRange.only(654321)) 
species = x_species.intersect(y_species); // this is result

3
投票

范围建议是答案的一部分,但即使使用数组键,它实际上只是一维范围,而不是数据的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();
    }
};

(如果坐标不是整数,则用适当的epsilon替换+ 1

我发布了一个广义解决方案的示例:

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

© www.soinside.com 2019 - 2024. All rights reserved.