在sqlite fts5查询中使用Match,但需要对排名进行更多控制吗?

时间:2018-10-11 18:59:49

标签: python-3.x sqlite fts5

我有一个使用fts5创建的虚拟表:

import sqlite3
# create a db in memory
con = sqlite3.connect(':memory:')
con.execute('create virtual table operators using fts5(family, operator, label, summary, tokenize=porter)')

# some sample data
samples = {'insideTOP':
              {'label':'Inside',
               'family':'TOP',
               'summary':'The Inside TOP places Input1 inside Input2.'
              },
           'inTOP':
              {'label':'In',
               'family':'TOP',
               'summary':'The In TOP is used to create a TOP input.'
              },
           'fileinSOP':
              {'label':'File In',
               'family':'SOP',
               'summary':'The File In SOP allows you to read a file'
              }
          }

# fill db with those values
for operator in samples.keys():
    opDescr = samples[operator]
    con.executescript("insert into operators (family, operator, label, summary) values ('{0}','{1}','{2}','{3}');".format(opDescr['family'],operator,opDescr['label'],opDescr['summary']))

具有以下列

+--------+-----------+------------+----------------------------------------------+
| family | operator  |   label    |            summary                           |
+--------+-----------+------------+----------------------------------------------+
| TOP    | insideTOP | Inside     | The Inside TOP places Input1 inside Input2.|
| TOP    | inTOP     | In         | The In TOP is used to create a TOP input.    |
| SOP    | fileinSOP | File In    | The File In SOP allows you to read a file    |
+--------+-----------+------------+----------------------------------------------+

一个示例查询是:

# query the db
query = "select operator from operators where operators match 'operator:In*' or operators match 'label:In*' order by family, bm25(operators)"
result = con.execute(query)

for row in result:
    print(row)

结果我得到了

  • fileinSOP
  • insideTOP
  • inTOP

但是对于这种特殊情况,我实际上希望'inTOP'出现在'insideTOP'之前,因为标签是完美匹配。

什么是一种能够按我希望的方式按摩这些结果的好技术?

非常感谢您

马库斯

1 个答案:

答案 0 :(得分:0)

也许您可以在问题中加入订购规则。

如果使用bm25排序结果,则无法获得所需的结果 我建议您可以使用自定义的排名函数,例如以下sql:

query = "select operator from operators where operators match 'operator:In*' or operators match 'label:In*' order by myrank(family, operators)"

在fts5中定义自定义排名功能非常容易,您可以按照fts5网站上的指南进行操作。

如果您还希望将bm25结果作为排名得分,则可以通过rank方法计算最终得分。