【问题标题】:How to improve sqlite like statement performance如何提高类似sqlite的语句性能
【发布时间】:2012-12-12 23:08:56
【问题描述】:

我创建一个表使用这样的模式:

CREATE TABLE wordIndex(id integer primary key, word varchar(128), offset integer, length integer);
CREATE INDEX word_idx on wordIndex(word);

现在表有大约 450,000 行记录。当我在 ipod4 上使用下面的 Like 语句时,性能不好: select * from wordIndex where word like 'test accesses%'; 使用解释输出:

explain select * from wordIndex where word like 'test acces%';
0|Trace|0|0|0||00|
1|Goto|0|16|0||00|
2|OpenRead|0|2|0|4|00|
3|Rewind|0|14|0||00|
4|String8|0|2|0|test acces%|00|
5|Column|0|1|3||00|
6|Function|1|2|1|like(2)|02|
7|IfNot|1|13|1||00|
8|Rowid|0|4|0||00|
9|Column|0|1|5||00|
10|Column|0|2|6||00|
11|Column|0|3|7||00|
12|ResultRow|4|4|0||00|
13|Next|0|4|0||01|
14|Close|0|0|0||00|
15|Halt|0|0|0||00|
16|Transaction|0|0|0||00|
17|VerifyCookie|0|2|0||00|
18|TableLock|0|2|0|wordIndex|00|
19|Goto|0|2|0||00|

我可能需要构建一个额外的倒排索引来提高性能还是...? 提前感谢!

【问题讨论】:

  • 你是否只使用这种模式来表示 LIKE(即以开头)?
  • 是的,只是“aaa%”模式

标签: sql performance sqlite sql-like


【解决方案1】:

索引和like 在大多数数据库中无法相处。最好的办法是尽可能将查询重写为范围查询,因为随后将使用索引:

select *
from wordIndex
where word between 'test acces' and 'test acces{'

(左大括号是紧跟在 'z' 后面的 ASCII 字符。)

如果您正在寻找单词开头的模式(比如“%test”),那么您可能不得不让自己接受全表扫描。

编辑:

现在,当模式以常量开头时,索引和like *do` 在大多数数据库中都可以相处,因此您可以这样做:

select *
from wordIndex
where word like 'test acces%' ;

不过,我不能 100% 确定 SQLite,因此请检查执行计划以查看它是否使用索引。

【讨论】:

  • 感谢 Gordon Lionff,它确实有效。查询重写前:执行时间:1.756531 秒,查询重写后:执行时间:在我的 iPod Touch 4 上为 0.011285。
  • Tnx 但它区分大小写!
  • 也可以使用unicode字符<ffff>。要打印它,请使用python -c 'print u"\uffff"'
【解决方案2】:

试试这个:

SELECT * FROM wordIndex
WHERE word COLLATE NOCASE BETWEEN @SearchString AND @SearchString || '~~~~~~~~~~'

“~”是最大的ASCII符号。

【讨论】:

    【解决方案3】:

    我的答案与 Gordon Linoff 略有不同,但方法相同。

    如果你想保留任何跟随“测试访问”的字符,你应该试试这个:

    SELECT * FROM wordIndex
    WHERE word > 'test acces' AND word < 'test accet';
    

    【讨论】:

      猜你喜欢
      • 2011-07-23
      • 2017-02-10
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      相关资源
      最近更新 更多