pg数据库模糊搜索, 和根据匹配排序
常用模糊搜索,一般是,
1. 搜索字段内容里面是否包含某关键字. 比如:
1. 搜索字段内容里面是否包含某关键字. 比如:
Word.where("name ilike ? ", "%abcd%")2. 搜索字段是否在给要搜索的这段字符串里面.比如:
Word.where("position(name in "abcd") > 0")
select * from words where position(name in 'abcd') > 03.根据匹配的单词的长度排序:
Word.where("name ilike ? ", escape_search_term(@txt))
.order("char_length(name)")) def escape_seach_term(term)
# pg里面不能包含奇数个单引号
term = term.gsub(/'+/, "''")
"%#{term.gsub(/\s+/, '%')}%"
end4.根据匹配的位置前后排序:
Word.select("name, strpos(name, '#{@search_txt}') as loc")
.where("name ilike ? ", escape_search_term(@txt))
.order("loc")) 获取搜索的内容在字段里面的位置:pgSql里面是strpos(), MySql里面是instr(), locate(),等类似函数。
5.优先匹配位置,再根据单词长度排序:
Word.select("name, char_length(name) as len, strpos(name, '#{@search_txt}') as loc")
.where("name ilike ? or ? =ANY(tags)", escape_search_term(@search_txt), @search_txt)
.order("loc, len")6.查询单词包含哪些前缀:strops 类似position(),
# 前缀不能在最后
Prefix.where("position(name in '#{word}') > 0 and
position(name in '#{word}') <= (#{word.length} - LENGTH(name))")7. 搜索相似 similar
Post.where("content similar to ? ", helpers.pg_similar_search(txt))
#有些单词在首位通过下面这在方式ok。
def pg_similar_search(txt)
return "%\\m(#{txt.downcase}|#{txt.upcase}|#{txt.titlecase})\\M%"
end
阅读量: 2385
发布于:
修改于:
发布于:
修改于: