首页 > 解决方案 > 创建虚拟列和索引以优化 JSON 列中数组的过滤器

问题描述

这是有关如何在不使用 OpenJson 且仅使用 Json_Value 的情况下优化 json 列的 microsoft 文档: https ://docs.microsoft.com/en-us/sql/relational-databases/json/index-json-data?view =sql-server-ver15

我的问题是我有一个 JSON 列,其中包含一个数组,我试图从数组中的每个元素中获取所有名为 Test_ID 的键,以与连接语句 testId 进行比较,虽然它有效,但它相对较慢。400 行大约需要 9 秒。我正在尝试以指数方式加快速度,似乎唯一的方法是通过该文章中提到的索引,但我似乎无法弄清楚如何为数组执行此操作。

我的 JSON 与此类似:'{"Property":{"Label":"0"},"Tests":[{"Test_ID":"GUID_HERE","Type":{"Label":" "},"Name":{"Label":" "},"Value":null,{"Test_ID":"GUID_HERE","Type":{"Label":" "},"Name":{"Label":" "},"Value":" "}]}'

这是我的擦洗查询

SELECT DISTINCT w.W_ID, 
       'Proc' ProcHeaderName, p.ProcNumber ProcValue, 
       'Class' ClassHeaderName, p.Class ClassValue 
INTO #Procs
FROM proc p
LEFT JOIN (SELECT wt.W_ID, wt.TestId 
    from TestValue wt where wt.IsDeleted = 0) as wtRow on wtRow.W_ID in (SELECT ID FROM #tmp) 
LEFT JOIN TableNameHere c on c.IsDeleted = 0 and c.col_ID in (SELECT col_ID FROM tmp)
WHERE p.IsDeleted = 0 and [dbo].[GetTestIdJson](c.Json, wtRow.TestId) = wtRow.TestId
    AND p.ProcNumber + ',' + p.RNumber = JSON_VALUE(c.Json,'$.Property.Label') + ',' + JSON_VALUE(c.Json,'$.Property.Label')
GROUP BY wtRow.W_ID, p.ProcNumber, p.Class

标签: jsonsql-serverindexingquery-optimizationvirtual-column

解决方案


… 索引视图 …小提琴

create table dbo.a (id int primary key, json nvarchar(max));   
insert into dbo.a values(1, '{"Property":{"Label":"0"},"Tests":[{"Test_ID":"GUID_HERE1","Type":{"Label":" "},"Name":{"Label":" "},"Value":null},{"Test_ID":"GUID_HERE2","Type":{"Label":" "},"Name":{"Label":" "},"Value":" "}]}');
insert into dbo.a values(2, '{"Property":{"Label":"0"},"Tests":[{"Test_ID":"GUID_HERE21","Type":{"Label":" "},"Name":{"Label":" "},"Value":null},{"Test_ID":"GUID_HERE22","Type":{"Label":" "},"Name":{"Label":" "},"Value":" "}]}');
GO
--numbers table
create table dbo.n(n int primary key);
insert into dbo.n values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10); --assume max 11 elements in Tests[]
GO
create view dbo.v
with schemabinding
as
select a.id, n.n, json_value(a.json, concat('$.Tests[', n.n,'].Test_ID')) as Test_Id
from dbo.a as a
cross join dbo.n as n
where json_value(a.json, concat('$.Tests[', n.n,'].Test_ID')) is not null;
GO
create unique clustered index vuidx on dbo.v(id,n);
create index idTestId on dbo.v(Test_Id);
GO
select * from dbo.v
GO
set statistics xml on;
select *
from dbo.v with(noexpand)
where Test_Id = 'GUID_HERE2';
GO
drop view if exists dbo.v;
GO
drop table if exists dbo.n;
GO
drop table if exists dbo.a;

推荐阅读