PostgreSQL-模糊查询

PostgreSQL-模糊查询!/bin/bash1模糊查询时,大多数情况下首先想到的是like‘%关键字%’或基于gin索引的正则表达式,gin至少需要三个字符才会使用索引,对于汉语来说十分不方便;2在海量数据的情况下,基于like和gin索引的正则表达式均不理想时,一般采用分词后进行查询.3分词存在两个弊端3.1词库的维护是比较繁重的工作.当词库中没有的关键词会导致查询结果不正确.3.2历史数据的维护工作不好处理

大家好,又见面了,我是你们的朋友全栈君。

函数已改进,请使用新版本函数,参看PostgreSQL 黑科技-递规二分法切分汉字

1 模糊查询时,大多数情况下首先想到的是like ‘%关键字%’或基于gin索引的正则表达式,gin至少需要三个字符才会使用索引,对于汉语来说十分不方便;

2 在海量数据的情况下,基于like和gin索引的正则表达式均不理想时,一般采用分词后进行查询.

3 分词存在两个弊端

3.1 词库的维护是比较繁重的工作.当词库中没有的关键词会导致查询结果不正确.

3.2 历史数据的维护工作不好处理.新增关键词时,历史数据并不包含些新的关键词,使用新关键词查询时无法查询到历史数据.

4 不使用like/不使用正则/不使用分词并保证查询快捷准确的另一种方法

此方法的缺点是比较浪费空间,不过在当前相比较下来以空间换取时间的方法是值得的.

4.1 首先清除文本中的标点符号

drop function if exists clear_punctuation(text);
create or replace function clear_punctuation(text) 
  returns text
as $$
    select regexp_replace($1,
	'[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\''|\,|\<|\.|\>|\/|\?|\:|\。|\;|\,|\:|\“|\”|\(|\)|\、|\?|\《|\》]'
	,'','g');
$$ language sql strict immutable;

4.2 每两个字符做为一个词处理,将字符串转换为tsvector

drop function if exists str_to_tsvector(text);
create or replace function str_to_tsvector(text) 
returns tsvector
as $$      
	declare
		v_count integer;
		v_txt text;
		v_txts text[];
		v_result tsvector;
	begin
		v_txt := clear_punctuation($1);
		--数组大小为字符数量-1
		v_count := length(v_txt)-1;
		if( v_count < 1 ) then
			raise exception '输入参数("%")去除标点符号后至少需要2个字符',$1;
		end if;
		for i in 1..v_count loop      
			v_txts := array_append(v_txts, substring(v_txt,i,2));      
		end loop;
		--tsvector类型要求去除重复并排序
		with cte1 as(
			select f from unnest(v_txts) as f group by f
		),cte2 as(
			select f from cte1 order by f
		)select array_to_tsvector(array_agg(f)) into v_result from cte2;
		return v_result;
	end;      
$$ language plpgsql strict immutable;

4.3 创建测试表

drop table if exists test_cond;
drop table if exists test;
create table test(
	objectid bigserial not null,					--唯一编号
	name text not null,								--名称
	newtime timestamptz default(now()) not null,	--首次添加时间
	lastime timestamptz,							--最后一次修改时间	
	constraint pk_test_objectid primary key (objectid)
);
--rum需要大量的计算和写入,保存速度非常慢,因此创建表时设置unlogged标记
--unlogged标记不是绝对安全的,因此和主表分开
--虽然浪费了一定的磁盘空间,但可以最大程度保证写入速度
--test_cond表损坏后,通过主表可以很容易的重建,不过机率非常小
--test_cond中的数据通过触发器更新,不需要操作这个表
create unlogged table test_cond(
	objectid bigserial not null,					--唯一编号
	keys tsvector not null,							--关键字
	constraint pk_test_cond_objectid primary key (objectid),
	constraint fk_test_cond_objectid foreign key(objectid) references test(objectid) on delete cascade
);
create index idx_test_cond_keys on test_cond using rum(keys rum_tsvector_ops);

4.4 创建关联触发器

--test_cond表设置了级联删除,所以不需要delete触发
drop trigger if exists tri_test_change on test;
drop function if exists tri_test_trigger();
create or replace function tri_test_trigger() 
returns trigger as $$ 
        begin 
			if (TG_OP = 'INSERT') then					
				insert into test_cond(objectid,keys) values(NEW.objectid,str_to_tsvector(NEW.name));
				return NEW;
			elsif (TG_OP = 'UPDATE') then
				update test_cond set keys=str_to_tsvector(NEW.name) where objectid=NEW.objectid;
				return NEW;			
			end if;
			 RETURN NULL; 
        end; 
$$ language 'plpgsql' SECURITY DEFINER;
--test_cond依赖test表,因此只能在test成功后再触好,只能设置为after
create trigger tri_test_change after INSERT or UPDATE on test 
	for each ROW EXECUTE PROCEDURE tri_test_trigger();

新版本函数,请参看PostgreSQL 黑科技-递规二分法切分汉字

--test_cond表设置了级联删除,所以不需要delete触发
drop trigger if exists tri_test_change on test;
drop function if exists tri_test_trigger();
create or replace function tri_test_trigger() 
returns trigger as $$ 
        begin 
			if (TG_OP = 'INSERT') then					
				insert into test_cond(objectid,keys) values(NEW.objectid,dichotomy_split_tsv(NEW.name));
				return NEW;
			elsif (TG_OP = 'UPDATE') then
				update test_cond set keys=dichotomy_split_tsv(NEW.name) where objectid=NEW.objectid;
				return NEW;			
			end if;
			 RETURN NULL; 
        end; 
$$ language 'plpgsql' SECURITY DEFINER;
--test_cond依赖test表,因此只能在test成功后再触好,只能设置为after
create trigger tri_test_change after INSERT or UPDATE on test 
	for each ROW EXECUTE PROCEDURE tri_test_trigger();

4.5 创建随机生成汉字

drop function if exists gen_random_zh(int,int);
create or replace function gen_random_zh(int,int)
	returns text
as $$
	select string_agg(chr((random()*(20901-19968)+19968 )::integer) , '')  from generate_series(1,(random()*($2-$1)+$1)::integer);
$$ language sql;

4.6 生成测试数据

每调一次ins_test插入100万数据,可以同时调用ins_test插入更多数据,以便验证模糊查询性能

drop function if exists ins_test();
create or replace function ins_test() 
	returns void 
as $$
	declare 
		v_index integer;
	begin
		v_index := 0;
		for i in 1..1000 loop	
			v_index := v_index + 1;
			insert into test(name)
				select gen_random_zh(8,32) as name from generate_series(1,1000);
			raise notice  '%', v_index;
		end loop;
	end;
$$ language plpgsql;
--每调一次ins_test插入100万数据
select ins_test();

4.7 验证触发器的update功能

update test set name='哈哈,我来验证了' where objectid=10000;

4.7 查询数据量

select count(*) from test;
select count(*) from test_cond;

5 模糊查询测试

5.1 创建查询转换函数

drop function if exists str_to_tsquery(text,boolean);
create or replace function str_to_tsquery(text,boolean default true) 
returns tsquery
as $$      
	declare
		v_count integer;
		v_txt text;
		v_txts text[];
		v_result tsquery;
	begin
		v_txt := clear_punctuation($1);
		--数组大小为字符数量-1
		v_count := length(v_txt)-1;
		if( v_count < 1 ) then
			raise exception '输入参数("%")去除标点符号后至少需要2个字符',$1;
		end if;
		for i in 1..v_count loop      
			v_txts := array_append(v_txts, substring(v_txt,i,2));      
		end loop;
		--tsquery类型要求去除重复并排序
		with cte1 as(
			select f from unnest(v_txts) as f group by f
		),cte2 as(
			select f from cte1 order by f
		)select string_agg(f, (case when $2 then '&' else '|' end ) )::tsquery into v_result from cte2;
		return v_result;
	end;      
$$ language plpgsql strict immutable;

5.2 模糊数据

关键字字数越多,查询越准确,并且查询速度

--因优先级问题,此语句可能会不走rum索引
explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where name @@ (str_to_tsquery('価仴'))

建议采用下面的方式,保证查询使用rum索引

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select str_to_tsquery('哈哈'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select str_to_tsquery('哈我'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select str_to_tsquery('我来'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select str_to_tsquery('来验'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select str_to_tsquery('验证'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select str_to_tsquery('证了'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select str_to_tsquery('哈哈,我来验证了'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select str_to_tsquery('侒亩'));

新版本函数,请参看PostgreSQL 黑科技-递规二分法切分汉字

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select dichotomy_split_tsq('哈哈'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select dichotomy_split_tsq('哈我'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select dichotomy_split_tsq('我来'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select dichotomy_split_tsq('来验'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select dichotomy_split_tsq('验证'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select dichotomy_split_tsq('证了'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select dichotomy_split_tsq('哈哈,我来验证了'));

explain (analyze,verbose,costs,buffers,timing) 
select f.* from test as f left join test_cond as s
on f.objectid=s.objectid
where s.keys @@ (select dichotomy_split_tsq('侒亩'));

5.3 验证级联删除功能

删除后再执行上面的sql查询均查不到数据

delete from test where objectid=10000;
``
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/140035.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • [MFC美化] MFC界面UI库总结

    [MFC美化] MFC界面UI库总结稍微说下自己用过的感受:1.SkinMagic动态库DLL使用,(有VC6版本的静态链接库,没能成功调用)。对控件:菜单和下拉框(下拉滚动条)有问题。不能自由设置颜色背景皮肤格式:.smf,可使

    2022年7月1日
    25
  • 最新PHP 面试、笔试题汇总(code happy)[通俗易懂]

    最新PHP 面试、笔试题汇总(code happy)[通俗易懂]一、秒杀(商品超卖,高并发,同一用户多次抢购) 后端:redis+队列 redis队列实现,三个队列(库存队列,排队队列,抢购结果队列) 用户先进入排队队列,先进先出,判断是否已经在抢购结果队列,如果在,则直接下一个,如果不在,将用户信息加入抢购结果队列,库存-1,等待数据库空闲时,将抢购结果写入数据库 前端: 面对高并发的抢购活动,前端常用的三板斧是【扩容】【静态化】【限流】 扩容:加机器,这是最简单的方法,通过增加前端池的整体承载量来抗峰值。 静态化:将活动页面上的所有可以静态的

    2022年6月1日
    34
  • 域名url转发怎么设置_url和域名

    域名url转发怎么设置_url和域名URL转发技术就是将该域名的网站访问请求,通过浏览器端技术,转向到另外一个网站。域名URL转发分为url显性转发和URL隐性转发这里以万网域名为例教你如何设置显性url转发和隐性URL转发。

    2022年10月18日
    0
  • Python文件写入txt_python创建文件并写入内容

    Python文件写入txt_python创建文件并写入内容文件写入txt

    2022年9月26日
    0
  • 2019版idea激活码(破解版激活)[通俗易懂]

    2019版idea激活码(破解版激活),https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月17日
    694
  • BPTT深度理解「建议收藏」

    BPTT深度理解「建议收藏」本博客适合那些BP网络很熟悉的读者一基本结构和前向传播符号解释:1. cltctl:t时刻第l层的神经元的集合,因为cltctl表示的是一层隐藏层,所以图中一个圆圈表示多个神经元。2. hlthtl:第l层在t时刻的输出。因为hlthtl是一层隐藏层的输出,所以表示的是一个向量。3. LjLj:表示的是在j时刻,网络的输出的值和目标输出值的平方差,L表示的是所有时刻的平方差的和。4. WvWv:…

    2022年6月23日
    22

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号