简体   繁体   English

使用 Dexie.js 编写多个 where 条件

[英]Write multiple where condition using Dexie.js

How can I write a where condition like the following using Dexie.js?如何使用 Dexie.js 编写如下的 where 条件?

field1=0 AND field2!='test' AND field3 IN(1,2,3,4)

I tried this one but I got an error....我试过这个,但我得到了一个错误......

.where('field1').equals(0).and('field2').notEquals('test').and('field3').anyOf([1,2,3,4]).toArray()

I suppose because the ".and" method works only with a function.我想是因为".and"方法仅适用于 function。 But if I have to write a multiple where condition with different types of conditions (eg: equals , notEquals , anyOf )... How can I do that?但是,如果我必须编写具有不同类型条件的多个 where 条件(例如: equalsnotEqualsanyOf )......我该怎么做?

I apreciate your support, thanks in advance感谢您的支持,提前致谢

Collection.and() is identical to Collection.filter() and takes a JS callback. Collection.and() 与 Collection.filter() 相同,并接受 JS 回调。

The reason is that an index can only be used for one criteria.原因是一个索引只能用于一个标准。 A typical SQL database has the same limitation but it has some intelligent strategies ( query plan ) that tries to find out the which field to use for index lookup and which ones to use for manually filtering the result.典型的 SQL 数据库具有相同的限制,但它具有一些智能策略(查询计划),试图找出用于索引查找的字段以及用于手动过滤结果的字段。 Dexie does not have query plans so you need to do that logic yourself. Dexie 没有查询计划,因此您需要自己执行该逻辑。

For cases where you are combining an equals filter with another filter, a compound index can be used also to get more efficient AND queries.对于将 equals 过滤器与另一个过滤器组合的情况,复合索引也可用于获得更有效的 AND 查询。

So as an example we can take your exact example and translate it into the most optimal way using dexie queries:因此,作为示例,我们可以使用您的确切示例并将其转换为使用 dexie 查询的最佳方式:

const db = new Dexie("multipleCriteriasSample");
db.version(1).stores({
  someTable: 'id, [field1+field3]'
});

function doTheQuery() {
  return db.someTable.where('[field1+field3]').anyOf([
    [0, 1],
    [0, 2],
    [0, 3],
    [0, 4]
  ]).and(item => item.field2 !== "test");
}

The logic for the above is this:上面的逻辑是这样的:

field1 is an equals operator - which makes it possible to combine with another criteria if we have it in a compound index ('[field1+field3]') field2 is a notEqual which generally never has any gain of using an index - so filter it using the and() method. field1 是一个 equals 运算符 - 如果我们将它放在复合索引 ('[field1+field3]') 中,它可以与另一个标准结合起来 field2 是一个 notEqual ,它通常不会有任何使用索引的好处 - 所以过滤它使用 and() 方法。 field3 is an anyOf(). field3 是一个 anyOf()。 Use the compound index and do a single anyOf().使用复合索引并执行单个 anyOf()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM