侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

SQLServer地址搜索性能优化

数据库  /  管理员 发布于 5年前   153

这是一个很久以前的例子,现在在整理资料时无意发现,就拿出来再改写分享。

1.需求

 1.1 基本需求: 根据输入的地址关键字,搜索出完整的地址路径,耗时要控制在几十毫秒内。

 1.2 数据库地址表结构和数据:

 表TBAddress

 

 表数据

 

 1.3 例子:

 e.g. 给出一个字符串如“广 大”,找出地址全路径中包含有“广” 和“大”的所有地址,Y果如下:

下面将通过4个方法来实现,再分析其中的性能优劣,然后选择一个比较优的方法。

 2.创建表和插入数据

 2.1 创建数据表TBAddress

use test;go/* create table */if object_id('TBAddress') is not null  drop table TBAddress;gocreate table TBAddress( ID int , Parent int not null , LevelNo smallint not null , Name nvarchar(50) not null , constraint PK_TBAddress primary key ( ID ));gocreate nonclustered index ix_TBAddress_Parent on TBAddress(Parent,LevelNo) include(Name) with(fillfactor=80,pad_index=on);create nonclustered index ix_TBAddress_Name on TBAddress(Name)include(LevelNo)with(fillfactor=80,pad_index=on);go

create table

2.2 插入数据

use testgo/*insert data*/set nocount onBegin Try  Begin Tran  Insert Into TBAddress ([ID],[Parent],[LevelNo],[Name])    Select 1,0,0,N'中国' Union All     Select 2,1,1,N'直辖市' Union All     Select 3,1,1,N'辽宁省' Union All     Select 4,1,1,N'广东省' Union All     ... ...    Select 44740,930,4,N'奥依塔克镇' Union All     Select 44741,932,4,N'巴音库鲁提乡' Union All     Select 44742,932,4,N'吉根乡' Union All     Select 44743,932,4,N'托云乡'  Commit TranEnd TryBegin Catch  throw 50001,N'插入^程中l生e`.' ,1Rollback TranEnd Catchgo

附件: insert Data

 Note: 数据有44700条,insert代码比较长,所以采用附件形式。

3.测试,方法1

3.1 分析:

 

a. 先搜索出包字段Name中含有“广”、“大”的所有地址记录存入临时表#tmp。

  b. 再找出#tmp中各个地址到Level 1的全路径。

    c. 根据步骤2所得的结果,筛选出包含有“广”和“大”的地址路径。

      d. 根据步骤3筛选的结果,查询所有到Level n(n为没有子地址的层编号)的地址全路径。

3.2 存储过程代码:

Use testGoif object_ID('[up_SearchAddressByNameV0]') is not null  Drop Procedure [up_SearchAddressByNameV0]Gocreate proc up_SearchAddressByNameV0 (  @Name nvarchar(200))Asset nocount ondeclare @sql nvarchar(max) declare @tmp Table (Name nvarchar(50)) set @Name=@Name+' ' while patindex('% %',@Name)>0begin  set @Name=replace(@Name,' ',' ')  end set @sql ='select ''' +replace(@Name,' ',''' union all select ''')+''''insert into @tmp(Name) exec(@sql) if object_id('tempdb..#tmp') is not null drop table #tmpif object_id('tempdb..#') is not null drop table # create table #tmp(ID int )  while @Name>''begin  insert into #tmp(ID)  select a.ID from TBAddress a where a.Name like '%'+substring(@Name,1,patindex('% %',@Name)-1)+'%'    set @Name=Stuff(@Name,1,patindex('% %',@Name),'')end  ;with cte_SearchParent as(  select a.ID,a.Parent,a.LevelNo,convert(nvarchar(500),a.Name) as AddressPath from TBAddress a where exists(select 1 from #tmp x where a.ID=x.ID)   union all  select a.ID,b.Parent,b.LevelNo,convert(nvarchar(500),b.Name+'/'+a.AddressPath) as AddressPath    from cte_SearchParent a    inner join TBAddress b on b.ID=a.Parent      --and b.LevelNo=a.LevelNo -1      and b.LevelNo>=1)select a.ID,a.AddressPath   into #  from cte_SearchParent a   where a.LevelNo=1 and exists(select 1 from @tmp x where a.AddressPath like '%'+x.Name+'%' having count(1)=(select count(1) from @tmp)) ;with cte_result as(  select a.ID,a.LevelNo,b.AddressPath    from TBAddress a       inner join # b on b.ID=a.ID  union all  select b.ID,b.LevelNo,convert(nvarchar(500),a.AddressPath+'/'+b.Name) As AddressPath    from cte_result a      inner join TBAddress b on b.Parent=a.ID        --and b.LevelNo=a.LevelNo+1)select distinct a.ID,a.AddressPath   from cte_result a   where not exists(select 1 from TBAddress x where x.Parent=a.ID)  order by a.AddressPath Go

procedure:up_SearchAddressByNameV0

 3.3 执行查询:

exec up_SearchAddressByNameV0 '广 大'

共返回195行记录。

3.4 客户端统计信息:

平均的执行耗时:  244毫秒

4.测试,方法2

 方法2是参照方法1,并借助全文索引来优化方法1中的步骤1。也就是在name列上建立全文索引,在步骤1中,通过全文索引搜索出包字段Name中含有“广”、“大”的所有地址记录存入临时表#tmp,其他步骤保持不变。

 4.1 创建全文索引

use testgo/*create fulltext index*/if not exists(select 1 from sys.fulltext_catalogs a where a.name='ftCatalog')begincreate fulltext catalog ftCatalog As default;endgo--select * From sys.fulltext_languages    create fulltext index on TBAddress(Name language 2052 ) key index PK_TBAddressgo   alter fulltext index on dbo.TBAddress add(Fullpath language 2052)go

Note:  在Name列上创建全文索引使用的语言是简体中文(Simplified Chinese)

4.2 存储过程代码:

Use testGoif object_ID('[up_SearchAddressByNameV1]') is not null  Drop Procedure [up_SearchAddressByNameV1]Gocreate proc up_SearchAddressByNameV1 (  @Name nvarchar(200))Asset nocount ondeclare @sql nvarchar(max),@contains nvarchar(500) declare @tmp Table (Name nvarchar(50)) while patindex('% %',@Name)>0begin  set @Name=replace(@Name,' ',' ')  end set @sql ='select ''' +replace(@Name,' ',''' union all select ''')+''''set @contains='"'+replace(@Name,' ','*" Or "')+'*"' insert into @tmp(Name) exec(@sql) if object_id('tempdb..#') is not null drop table # ;with cte_SearchParent as(  select a.ID,a.Parent,a.LevelNo,convert(nvarchar(2000),a.Name) as AddressPath from TBAddress a where exists(select 1 from TBAddress x where contains(x.Name,@contains) And x.ID=a.ID)   union all  select a.ID,b.Parent,b.LevelNo,convert(nvarchar(2000),b.Name+'/'+a.AddressPath) as AddressPath    from cte_SearchParent a    inner join TBAddress b on b.ID=a.Parent      --and b.LevelNo=a.LevelNo -1      and b.LevelNo>=1)select a.ID,a.AddressPath   into #  from cte_SearchParent a   where a.LevelNo=1 and exists(select 1 from @tmp x where a.AddressPath like '%'+x.Name+'%' having count(1)=(select count(1) from @tmp)) ;with cte_result as(  select a.ID,a.LevelNo,b.AddressPath    from TBAddress a       inner join # b on b.ID=a.ID  union all  select b.ID,b.LevelNo,convert(nvarchar(2000),a.AddressPath+'/'+b.Name) As AddressPath    from cte_result a      inner join TBAddress b on b.Parent=a.ID        --and b.LevelNo=a.LevelNo+1)select distinct a.ID,a.AddressPath   from cte_result a   where not exists(select 1 from TBAddress x where x.Parent=a.ID)  order by a.AddressPath Go

procedure:up_SearchAddressByNameV1

4.3测试存储过程:

exec up_SearchAddressByNameV1 '广 大'

共返回195行记录。

4.4 客户端统计信息:

平均的执行耗时:  166毫秒

5.测试,方法3

在方法2中,我们在Name列上创建全文索引提高了查询性能,但我们不仅仅局限于一两个方法,下面我们介绍第3个方法。

第3个方法,通过修改表的结构和创建全文索引。在表TBAddress增加多一个字段FullPath存储各个地址到Level 1的全路径,再在FullPath列上创建全文索引,然后直接通过全文索引来搜索FullPath列中包含“广”和“大”的记录。

5.1 新增加字段FullPath,并更新列FullPath数据:

use test;go/*alter table */if not exists ( select 1from sys.columns awhere a.object_id = object_id('TBAddress')    and a.name = 'Fullpath' )  begin     alter table TBAddress add Fullpath nvarchar(200);  end;gocreate nonclustered index IX_TBAddress_FullPath on dbo.TBAddress(Fullpath) with(fillfactor=80,pad_index=on);go/*update TBAddress */with  cte_fullPath     as ( select ID, Parent, LevelNo, convert(nvarchar(500), isnull(Name, '')) as FPath, Fullpath        from dbo.TBAddress        where LevelNo = 1        union all        select A.ID, A.Parent, A.LevelNo, convert(nvarchar(500), B.FPath + '/' + isnull(A.Name, '')) as FPath, A.Fullpath        from TBAddress as Ainner join cte_fullPath as B on A.Parent = B.ID       )   update a    set   a.Fullpath = isnull(b.FPath, a.Name)    from dbo.TBAddress a        left join cte_fullPath b on b.ID = a.ID;go

5.2 在列FullPath添加全文索引:

alter fulltext index on dbo.TBAddress add(Fullpath language 2052)

5.3 存储过程代码:

Use testGoif object_ID('[up_SearchAddressByNameV2]') is not null  Drop Procedure [up_SearchAddressByNameV2]Gocreate proc up_SearchAddressByNameV2(  @name nvarchar(200))Asdeclare @contains nvarchar(500)set nocount onset @contains='"'+replace(@Name,' ','*" And "')+'*"'select id,FullPath As AddressPath from TBAddress a where contains(a.FullPath,@contains) and not exists(select 1 from TBAddress x where x.Parent=a.ID) order by AddressPathGo

procedure:up_SearchAddressByNameV2

5.4 测试存储过程:

exec up_SearchAddressByNameV2 '广 大'

共返回195行记录。

5.5 客户端统计信息:

平均的执行耗时:  20.4毫秒

6.测试,方法4

 直接使用Like对列FullPath进行查询。

 6.1存储过程代码:

Use testGoif object_ID('[up_SearchAddressByNameV3]') is not null  Drop Procedure [up_SearchAddressByNameV3]Gocreate proc up_SearchAddressByNameV3(  @name nvarchar(200))Asset nocount ondeclare @sql nvarchar(max) declare @tmp Table (Name nvarchar(50)) set @Name=rtrim(rtrim(@Name)) while patindex('% %',@Name)>0begin  set @Name=replace(@Name,' ',' ')  end set @sql='select id,FullPath As AddressPath   from TBAddress a where not exists(select 1 from TBAddress x where x.Parent=a.ID)  ' set @sql +='And a.FullPath like ''%' +replace(@Name,' ','%'' And a.FullPath Like ''%')+'%'''exec (@sql) Go

procedure:up_SearchAddressByNameV3

6.2 测试存储过程:

exec up_SearchAddressByNameV3 '广 大'

 共返回195行记录。

6.3 客户端统计信息

 

平均的执行耗时:  34毫秒

7.小结

这里通过一个简单的表格,对方法1至方法4作比较。

 

从平均耗时方面分析,一眼就知道方法3比较符合开始的需求(耗时要控制在几十毫秒内)。

当然还有其他的方法,如通过程序实现,把数据一次性加载至内存中,再通过程序写的算法进行搜索,或通过其他工具如Lucene来实现。不管哪一种方法,我们都是选择最优的方法。实际的工作经验告诉我们,在实际应用中,多选择和测试不同的方法来,选择其中一个满足我们环境的,而且是最优的方法。


  • 上一条:
    sql 删除表中的重复记录
    下一条:
    sqlServer实现去除字符串空格
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客