假设我们有100万行这样的行:
import sqlite3
db = sqlite3.connect(':memory:')
c = db.cursor()
c.execute('CREATE TABLE mytable (id integer, description text)')
c.execute('INSERT INTO mytable VALUES (1, "Riemann")')
c.execute('INSERT INTO mytable VALUES (2, "All the Carmichael numbers")')
我知道如何使用Sqlite:
使用一个单字查询查找一行,最多有几个拼写错误,其中^{
如果排了1米,速度会非常慢!作为detailed here,postgresql
可以使用trigrams
对此进行优化。Sqlite提供的一个快速解决方案是使用VIRTUAL TABLE USING spellfix
:
c.execute('CREATE VIRTUAL TABLE mytable3 USING spellfix1')
c.execute('INSERT INTO mytable3(word) VALUES ("Riemann")')
c.execute('SELECT * FROM mytable3 WHERE word MATCH "Riehmand"'); print c.fetchall()
#Query: 'Riehmand'
#Answer: [(u'Riemann', 1, 76, 0, 107, 7)], working!
查找一个查询与FTS(“全文搜索”)匹配的查询的表达式:
c.execute('CREATE VIRTUAL TABLE mytable2 USING fts4(id integer, description text)')
c.execute('INSERT INTO mytable2 VALUES (2, "All the Carmichael numbers")')
c.execute('SELECT * FROM mytable2 WHERE description MATCH "NUMBERS carmichael"'); print c.fetchall()
#Query: 'NUMBERS carmichael'
#Answer: [(2, u'All the Carmichael numbers')]
它不区分大小写,甚至可以使用两个单词顺序错误的查询,等等:FTS确实非常强大。但缺点是每个查询关键字的拼写都必须正确,即FTS本身不允许拼写错误。
如何使用Sqlite进行全文搜索(FTS)并允许拼写错误?即“FTS+spellfix”一起使用
示例:
"All the Carmichael numbers"
"NUMMBER carmickaeel"
应该匹配它!在如何使用Sqlite实现这一点?
由于this page状态,Sqlite可能会这样:
Or, it [spellfix] could be used with FTS4 to do full-text search using potentially misspelled words.
链接问题:String similarity with Python + Sqlite (Levenshtein distance / edit distance)
公认的答案是好的(完全归功于他),这里有一个小小的变化,虽然没有公认的复杂案例的完整性,但有助于理解以下观点:
结果如下:
备注:可以注意到,“用spellfix table更正每个查询项”部分是通过每个术语一个SQL查询完成的。研究了这个与单个联合SQL查询的性能here。在
spellfix1
文档实际上告诉您如何做到这一点。从Overview section:SELECT term from search_aux WHERE col='*'
语句extracts all the indexed tokens。在将其与您的示例相连接,其中
mytable2
是您的fts4虚拟表,您可以创建一个fts4aux
表,并将这些标记插入到mytable3
spellfix1表中,方法是:您可能需要进一步限定该查询,以跳过已插入spellfix1中的任何术语,否则最终会出现两个条目:
^{pr2}$现在您可以使用
mytable3
将拼写错误的单词映射到已更正的标记,然后在MATCH
查询中使用这些已更正的标记mytable2
。在根据您的nead,这可能意味着您需要自己进行令牌处理和查询构建;没有公开的fts4查询语法分析器。因此,需要拆分两个令牌搜索字符串,每个令牌运行
spellfix1
表以映射到现有令牌,然后将这些令牌输入到fts4查询。在忽略SQL语法来处理此问题,使用Python进行拆分非常简单:
然后为
spellchecked_search(db, "NUMMBER carmickaeel")
返回[('All the Carmichael numbers',)]
。在然后,在Python中保持拼写检查处理允许您根据需要支持更复杂的FTS查询;您可能需要reimplement the expression parser才能这样做,但至少Python为您提供了这样做的工具。在
一个完整的例子,将上述方法打包到一个类中,该类简单地将术语提取为字母数字字符序列(根据我对表达式语法规范的阅读,这就足够了):
以及使用该类的交互式演示:
相关问题 更多 >
编程相关推荐