sqlite cost_function查询优化器

时间:2018-10-16 15:19:32

标签: sql sqlite

表架构为:

create table test_table (id int PRIMARY KEY NOT NULL, feature blob)

例如数据:

id      feature
1       blob=bytes[512]=float[128] eg[0.01,111,232....]
2       blob=bytes[512]=float[128] eg[0.02,113,-22....]
3       blob=bytes[512]=float[128] eg[2222,113,-22....]

UDF cosine_distance是具有两个Blob参数的自定义函数。 列特征是浮点数组(float [128])的Blob,然后我要计算余弦距离。 我有一个sql,带有sqlite的costum_function cosine_distance(udf)。

select cosine_distance(a,?) as distance 
from test_table 
where distance >=? 
order by distance desc limit ?

在此sql cosine_distance函数中,将在sqlite中调用两次。 如何让cosine_distance(一个昂贵的函数)只执行一次?

当我使用子选择时,例如:

select * from (select cosine_distance(feature,?) d from test_table) nt 
where nt.d>? 
order by nt.d desc limit ?

UDF cosine_distance将对每个记录执行两次。

当表test_table有 5 条记录时,cosine_distance将被调用 10 次。但是cosine_distance非常昂贵。

1 个答案:

答案 0 :(得分:0)

尝试在子查询上添加LIMIT,如下所示:

reactive form

这可能会根据规则13禁用subquery flatenning

选项2:在子查询上使用OFFSET:

select * from (select cosine_distance(feature,?) as d from test_table limit -1) nt 
where nt.d>? 
order by nt.d desc limit ?

选项3:在两个查询上都使用ORDER BY:

select * from (select cosine_distance(feature,?) as d from test_table offset 0) nt 
where nt.d>? 
order by nt.d desc limit ?