2

如何使用 FTS5 表在 SQLite3 数据库中搜索(价格)范围?

这是一个高度简化的示例表:

CREATE VIRTUAL TABLE fruits USING fts5 (id, name, price);
INSERT INTO fruits (id,name,price) VALUES (1, 'Apple with A', 5);
INSERT INTO fruits (id,name,price) VALUES (2, 'Pineapple with B', 10);
INSERT INTO fruits (id,name,price) VALUES (3, 'Cucumber with C', 20);
INSERT INTO fruits (id,name,price) VALUES (4, 'Melon with D', 25);
INSERT INTO fruits (id,name,price) VALUES (5, 'Kiwi with E', 30);
INSERT INTO fruits (id,name,price) VALUES (6, 'Cucumber with F', 35);
INSERT INTO fruits (id,name,price) VALUES (7, 'Cucumber with G', 40);

以下命令返回 Cucumber 的预期两条记录 3 和 7:

SELECT * FROM fruits WHERE fruits MATCH 'name:Cucumber AND (price:20 OR price:40)';

如何搜索价格范围为 20 到 40 的 Cucumbers(包括上例中的记录 6)?如果我尝试

SELECT * FROM fruits WHERE fruits MATCH 'name:Cucumber AND (price: BETWEEN 20 AND 40)';

或者

SELECT * FROM fruits WHERE fruits MATCH 'name:Cucumber AND (price: BETWEEN 19 AND 41)';

我根本没有得到任何结果(或错误消息)。不能在一个查询中使用 MATCH 和 BETWEEN 吗?


另外:为什么命令

SELECT * FROM fruits WHERE fruits MATCH 'name:C';

只返回一条记录(id:3)而不是 3、6 和 7,假设也会找到“Cucumber”中的 C,而不仅仅是“with C”中的 C?

4

1 回答 1

5

FTS 表将所有内容存储为文本;id在 FTS 表中包含andprice列是没有意义的。

FTS 表上唯一有效的查询是搜索单词(和内部查找docid)。

您不应将 FTS 表视为表,而应将其视为索引。将其他数据保存在“真实”表中,并对该表执行任何其他查询:

SELECT *
FROM fruits
WHERE id IN (SELECT docid
             FROM fruits_fts
             WHERE fruits_fts MATCH 'Cucumber')
  AND price BETWEEN 20 AND 40;

要搜索以 开头的单词C,您必须使用前缀搜索

于 2017-01-24T10:36:12.563 回答