iOS/Android SQLite 全文检索——FTS (Full Text Search)

本文介绍了如何使用SQLite全文检索(FTS)来提升APP搜索性能,特别是在数据量增大时。文章详细讲解了FTS的基本概念、为何选择SQLite全文检索、版本选择(如FTS4)、分词器的使用、操作步骤及部分查询语法,并提供了Demo示例,适合iOS和Android开发者参考。
摘要由CSDN通过智能技术生成

前言

我们的APP部分功能为了满足用户离线使用搜索的场景,使用了内置SQLite数据库的方式,随着内容的日益丰富,数据库记录快速增多,导致搜索速度明显变慢,为了提升搜索速度,给我们的数据做了全文检索的支持,在3W+的数据下,搜索速度由原来的数秒提升至几十到几百毫秒(设备不同,搜索效率存在差别)。

一、基本概念

  1. 概述
    全文检索是从文本或数据库中,不限定数据字段,自由地搜索出消息的技术。
    运行全文检索任务的程序,一般称作搜索引擎,它可以将用户随意输入的文字从数据库中找到匹配的内容。

  2. 工作原理
    它的工作原理是计算机索引程序通过扫描文章中的每一个词,对每一个词建立一个索引,指明该词在文章中出现的次数和位置,当用户查询时,检索程序就根据事先建立的索引进行查找,并将查找的结果反馈给用户的检索方式。

  3. 分类

  • 按字检索
    指对于文章中的每一个字都建立索引,检索时将词分解为字的组合。

  • 按词检索
    指对文章中的词,即语义单位建立索引,检索时按词检索。


注意:
在中文里面,每个汉字都有单独的含义,而英文中最小的语义单位是词,所以在英文搜索中按字搜索和按词搜索并没有明显的区分。

二、为什么使用SQLite全文检索

在SQLite对全文检索的官方介绍中的开篇,有下面一段内容:


For example, if each of the 517430 documents in the “Enron E-Mail Dataset” is inserted into both an FTS table and an ordinary SQLite table created using the following SQL script:

CREATE VIRTUAL TABLE enrondata1 USING fts3(content TEXT);     /* FTS3 table */
CREATE TABLE enrondata2(content TEXT);                        /* Ordinary table */

Then either of the two queries below may be executed to find the number of documents in the database that contain the word “linux” (351). Using one desktop PC hardware configuration, the query on the FTS3 table returns in approximately 0.03 seconds, versus 22.5 for querying the ordinary table.

SELECT count(*) FROM enrondata1 WHERE content MATCH 'linux';  /* 0.03 seconds */
SELECT count(*) FROM enrondata2 WHERE content LIKE '%linux%'; /* 22.5 seconds */

Of course, the two queries above are not entirely equivalent. For example the LIKE query matches rows that contain terms such as “linuxophobe” or “EnterpriseLinux” (as it happens, the Enron E-Mail Dataset does not actually contain any such terms), whereas the MATCH query on the FTS3 table selects only those rows that contain “linux” as a discrete token. Both searches are case-insensitive. The FTS3 table consumes around 2006 MB on disk compared to just 1453 MB for the ordinary table. Using the same hardware configuration used to perform the SELECT queries above, the FTS3 table took just under 31 minutes to populate, versus 25 for the ordinary table.


在相同的设备环境下,包含 517430条 记录的SQLite数据库中,使用全文检索FTS3创建的数据库 MATCH查询耗时0.03秒没有使用全文检索的数据库,使用 LIKE查询耗时

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值