【发布时间】:2013-03-03 14:43:04
【问题描述】:
我有一个关于 JSONStore 搜索字段的问题。
如果我使用number 作为searchFields 键并尝试通过WL.JSONStore.find 方法以0 作为查询来查找数据,它将命中所有数据(未过滤)。
使用上述案例的integer 可以正常工作。
number 和 integer 有什么区别?
【问题讨论】:
我有一个关于 JSONStore 搜索字段的问题。
如果我使用number 作为searchFields 键并尝试通过WL.JSONStore.find 方法以0 作为查询来查找数据,它将命中所有数据(未过滤)。
使用上述案例的integer 可以正常工作。
number 和 integer 有什么区别?
【问题讨论】:
JSON数字和整数之间的实际区别是
defining {age: 'number'} indexes 1 as 1.0,
while defining{age: 'integer'} indexes 1 as 1.
希望你理解
【讨论】:
JSONStore 使用 SQLite 来持久化数据,你可以阅读 SQLite 数据类型here。简短的回答是number 将数据存储为REAL,而integer 将数据存储为INTEGER。
如果您创建一个名为 nums 的集合,其中包含一个名为 num 的类型为 number 的搜索字段
var nums = WL.JSONStore.initCollection('nums', {num: 'number'}, {});
并添加一些数据:
var len = 5;
while (len--) {
nums.add({num: len});
}
然后使用查询调用find:{num: 0}
nums.find({num: 0}, {onSuccess: function (res) {
console.log(JSON.stringify(res));
}})
你应该回来:
[{"_id":1,"json":{"num":4}},{"_id":2,"json":{"num":3}},{"_id":3,"json":{"num":2}},{"_id":4,"json":{"num":1}},{"_id":5,"json":{"num":0}}]
请注意,您已取回所有存储的文档 (num = 4, 3, 2, 1, 0)。
如果你查看 .sqlite 文件:
$ cd ~/Library/Application Support/iPhone Simulator/6.1/Applications/[id]/Documents
$ sqlite3 jsonstore.sqlite
(android文件应该在/data/data/com.[app-name]/databases/下)
sqlite> .schema
CREATE TABLE nums ( _id INTEGER primary key autoincrement, 'num' REAL, json BLOB, _dirty REAL default 0, _deleted INTEGER default 0, _operation TEXT);
注意 num 的数据类型是REAL。
运行与 find 函数中使用的查询相同的查询:
sqlite> SELECT * FROM nums WHERE num LIKE '%0%';
1|4.0|{"num":4}|1363326259.80431|0|add
2|3.0|{"num":3}|1363326259.80748|0|add
3|2.0|{"num":2}|1363326259.81|0|add
4|1.0|{"num":1}|1363326259.81289|0|add
5|0.0|{"num":0}|1363326259.81519|0|add
注意4 存储为4.0 并且JSONStore 的查询总是使用LIKE,任何带有0 的num 都会匹配查询。
如果您改用integer:
var nums = WL.JSONStore.initCollection('nums', {num: 'integer'}, {});
寻找回报:
[{"_id":5,"json":{"num":0}}]
schema 表明 num 具有 INTEGER 数据类型:
sqlite> .schema
CREATE TABLE nums ( _id INTEGER primary key autoincrement, 'num' INTEGER, json BLOB, _dirty REAL default 0, _deleted INTEGER default 0, _operation TEXT);
sqlite> SELECT * FROM nums WHERE num LIKE '%0%';
5|0|{"num":0}|1363326923.44466|0|add
为简洁起见,我跳过了一些 onSuccess 和所有 onFailure 回调。
【讨论】:
LIKE... 这意味着即使我使用integer 数据类型并存储4, 44, 444 之类的数据,然后按4 搜索也会找到所有3 个数据对吗?大问题..
findById(4) 将对_id 字段进行完全匹配,并且只返回一个结果。
findById() 会进行完全匹配。感谢您的回答。我将要求 IBM 将默认 SQL 更改为不使用 LIKE。