2016-09-26 96 views
0

我想模糊搜索十進制數字而不是字符串。所以這個想法正在尋找100應該從數據庫中的行中帶來100,90,95,105,108,120個數值的範圍。模糊搜索雙打postgres

我已經嘗試了像關鍵字,但它不工作,因爲我想。我如何做小數模糊搜索。謝謝

+1

你會如何考慮100和90之間的模糊匹配是否正確?你爲什麼不指定下限和上限? –

回答

1

使用between。該功能是一個例子:

create or replace function fuzzy_match_numeric 
    (number numeric, value numeric, deviation numeric) 
returns boolean language sql as $$ 
    select number between value- value* deviation and value+ value* deviation 
$$; 

檢查值100的5%的偏差匹配:

select 
    fuzzy_match_numeric(94, 100, .05) r1, 
    fuzzy_match_numeric(95, 100, .05) r2, 
    fuzzy_match_numeric(105, 100, .05) r3, 
    fuzzy_match_numeric(106, 100, .05) r4 

r1 | r2 | r3 | r4 
----+----+----+---- 
f | t | t | f 
(1 row)  
1

我建議計算偏差設置你的查找值,並選擇最佳人選。以下是基於整數的示例,但數值類型的工作方式與此類似。

的樣本數據集:SEARCH_TABLE

postgres=# select * from search_table order by 1; 
value 
------- 
    90 
    95 
    100 
    101 
    103 
    105 
    108 
    120 

樣品查找值設置:search_condition

postgres=# select * from search_condition order by 1; 
value 
------- 
    100 
    103 
    105 

查找最佳人選:

select 
    distinct on (value) 
    value, 
    lookup_value as best_candidate 
from ( 
    select 
    st.value, 
    sc.value as lookup_value, 
    abs(1 - st.value*1.0/sc.value) as deviation 
    from search_table st 
    cross join search_condition sc 
) t 
order by value, deviation, best_candidate; 

結果:

value | best_candidate 
-------+---------------- 
    90 |   100 
    95 |   100 
    100 |   100 
    101 |   100 
    103 |   103 
    105 |   105 
    108 |   105 
    120 |   105 

如果有關係,則選擇較低的候選人。這可以通過將DESC添加到ORDER BY條款中的best_candidate列中以獲得最高候選人。