sql与nosql_SQL Server JSON函数:NoSQL与关系世界之间的桥梁

sql与nosql

In this article, we will explain what JSON is, what are the SQL Server JSON functions introduced in 2016, how to index JSON values, and how to import JSON data into SQL tables.

在本文中,我们将解释什么是JSON,2016年引入SQL Server JSON函数是什么,如何索引JSON值以及如何将JSON数据导入SQL表。

介绍 (Introduction)

JavaScript Object Notation (JSON) is an open universal data format that uses human-readable text to store data objects in a map format (Key/value pairs). This object notation was standardized in 2013 as ECMA-404. Many years ago, JSON was not popular, while XML was widely used in the data exchange operations. With the rise of the Big Data and NoSQL notions, JSON started slowly to replace XML since it is used and supported by the new data technologies.

的J ava 小号 CRIPTöbjectÑ浮选(JSON)是使用人类可读的文本来存储数据以地图格式(键/值对)对象的开放通用数据格式。 该对象表示法于2013年标准化为ECMA-404 。 许多年前,JSON不流行,而XML被广泛用于数据交换操作中。 随着大数据和NoSQL概念的兴起,JSON开始慢慢取代XML,因为新数据技术已使用并支持它。

Since companies and data consumers widely use traditional database management systems, these systems’ providers started supporting the new data technologies and features to keep pace with their customers emerging needs.

由于公司和数据消费者广泛使用传统的数据库管理系统,因此这些系统的提供商开始支持新的数据技术和功能,以与客户的新兴需求保持同步。

Regarding SQL Server, starting with the 2012 release, the database engine is not considered anymore for medium scale enterprises after adding high-end data-center management capabilities. In the 2016 version, Polybase was introduced, adding the ability to connect traditional databases with NoSQL databases and Hadoop data lakes (more capabilities were introduced in 2019 such as MongoDB and Oracle database support). Besides, JSON becomes supported, enabling developers to combine NoSQL and relational concepts by storing documents formatted as JSON text within tables storing traditional data.

对于SQL Server,从2012版本开始,在添加高端数据中心管理功能之后,中型企业不再考虑使用数据库引擎。 在2016版中,引入了Polybase,增加了连接传统数据库与NoSQL数据库和Hadoop数据湖的功能(2019年引入了更多功能,例如MongoDB和Oracle数据库支持)。 此外,JSON受到支持,使开发人员可以通过将格式为JSON文本的文档存储在存储传统数据的表中,从而将NoSQL和关系概念结合起来。

In the following sections, we will explain SQL Server JSON functions and how to index JSON values and import JSON data into SQL.

在以下各节中,我们将说明SQL Server JSON函数以及如何索引JSON值以及如何将JSON数据导入SQL。

SQL Server JSON函数 (SQL Server JSON functions)

Based on the official Microsoft documentation, the added JSON functionalities allows developers to:

根据Microsoft官方文档 ,添加的JSON功能使开发人员能够:

  1. Parse JSON text and read or modify values

    解析JSON文本并读取或修改值
  2. Transform arrays of JSON objects into table format

    将JSON对象数组转换为表格格式
  3. Run any Transact-SQL query on the converted JSON objects

    在转换后的JSON对象上运行任何Transact-SQL查询
  4. Format the results of Transact-SQL queries in JSON format

    以JSON格式格式化Transact-SQL查询的结果

In this section, we will explain each functionality added by providing some examples using the AdventureWorks database. Before describing these functionalities, we will create a new field of type NVARCHAR(MAX) within the [Person].[Person] table to be used during this guide.

在本节中,我们将通过使用AdventureWorks数据库提供一些示例来说明添加的每个功能。 在描述这些功能之前,我们将在[Person]。[Person]表中创建一个类型为NVARCHAR(MAX)的新字段,以在本指南中使用。

FOR JSON子句 (FOR JSON clause)

This clause is used to convert tabular data into a JSON text. There are two options to be used within this clause:

此子句用于将表格数据转换为JSON文本。 此子句中使用两个选项:

  1. FOR JSON PATH: to format and configure the output JSON text manually

    FOR JSON PATH:手动设置格式和配置输出JSON文本
  2. FOR JSON AUTO: to format the output JSON text automatically

    FOR JSON AUTO:自动设置输出JSON文本的格式

In this guide, we will use the second option to generate JSON text. As an example, let’s convert a record from the Person table to a JSON text:

在本指南中,我们将使用第二个选项来生成JSON文本。 例如,让我们将记录从Person表转换为JSON文本:

 SELECT TOP 1 [BusinessEntityID]
,[PersonType]
,[NameStyle]
,[Title]
,[FirstName]
,[MiddleName]
,[LastName]
,[Suffix]
,[EmailPromotion]
,[AdditionalContactInfo]
,[Demographics]
,[rowguid]
,[ModifiedDate] 
FROM [AdventureWorks2017].[Person].[Person]
FOR JSON AUTO

The result will be shown as following:

结果将显示如下:

using FOR JSON AUTO to generate JSON from an SQL Statement

To continue our experiments, we will fill the newly added NVARCHAR(MAX) column (called Details) with the JSON text created from the other columns using the following query:

为了继续我们的实验,我们将使用从其他列创建的JSON文本(使用以下查询)填充新添加的NVARCHAR(MAX)列(称为Details)

UPDATE [AdventureWorks2017].[Person].[Person]
SET [Details] = (SELECT [BusinessEntityID]
,[PersonType]
,[NameStyle]
,[Title]
,[FirstName]
,[MiddleName]
,[LastName]
,[Suffix]
,[EmailPromotion]
,[AdditionalContactInfo]
,[Demographics]
,[rowguid]
,[ModifiedDate] 
FROM [AdventureWorks2017].[Person].[Person] T1 
WHERE T1.[BusinessEntityID] = [AdventureWorks2017].[Person].[Person].[BusinessEntityID] FOR JSON AUTO)

If you decided to go with the first option we mentioned (FOR JSON PATH), you can refer to the following official documentation.

如果您决定采用我们提到的第一个选项(FOR JSON PATH),则可以参考以下官方文档

ISJSON()函数 (ISJSON() function)

ISJSON() is the simplest SQL Server JSON function; it checks if a given string is a valid JSON text. It returns 1 if the string is valid, else it returns 0.

ISJSON()是最简单SQL Server JSON函数; 它检查给定的字符串是否是有效的JSON文本。 如果字符串有效,则返回1 ,否则返回0

As an example, we will use check if FirstName and Details (the added NVARCHAR(MAX) column) columns contain a valid JSON text:

作为示例,我们将使用FirstNameDetails (添加的NVARCHAR(MAX)列)列是否包含有效的JSON文本:

SELECT TOP 1 ISJSON([FirstName]) IsJson_FirstName,ISJSON([Details]) IsJson_Details
FROM [AdventureWorks2017].[Person].[Person]

As shown in the image below, FirstName does not contain a valid JSON while Details does.

如下图所示, FirstName不包含有效的JSON,而Details则包含。

using ISJSON() (SQL Server JSON function) to check if a column value is JSON

JSON_VALUE()函数 (JSON_VALUE() function)

To extract a scalar value from a JSON text, we can use JSON_VALUE() function. This SQL Server JSON function takes the input JSON string and the JSON path that contains the property to extract as arguments. (Note that the context item of a JSON path is a dollar sign ($).)

要从JSON文本提取标量值,我们可以使用JSON_VALUE()函数。 此SQL Server JSON函数采用输入的JSON字符串和包含要提取的属性的JSON路径作为参数。 ( 请注意,JSON路径的上下文项是美元符号($)。)

In the following example, we used JSON_VALUE() function to filter the query result where the BusinessEntityID value stored within the first array of the JSON text is equal to 1:

在以下示例中,我们使用JSON_VALUE()函数筛选查询结果,其中JSON文本的第一个数组中存储的BusinessEntityID值等于1:

SELECT *
FROM [AdventureWorks2017].[Person].[Person]
WHERE JSON_VALUE([Details], '$[0].BusinessEntityID') = '1'

As shown below, the query returns only one row:

如下所示,查询仅返回一行:

Using JSON_VALUE() (SQL Server Json function) to search for a property value within a JSON string

More examples of the JSON_VALUE() function can be found in the official documentation.

JSON_VALUE()函数的更多示例可以在官方文档中找到。

Besides, if you are not familiar with JSON PATH expressions, you can refer to the following article.

此外,如果您不熟悉JSON PATH表达式,则可以参考以下文章

JSON_QUERY()函数 (JSON_QUERY() function)

To extract an array or object from a JSON text, we must use JSON_QUERY() function. This SQL Server JSON function is similar to JSON_VALUE(); it takes the same arguments (input JSON and path) and returns a JSON text (NVARCHAR(MAX)) value.

要从JSON文本提取数组或对象,我们必须使用JSON_QUERY()函数。 此SQL Server JSON函数类似于JSON_VALUE(); 它采用相同的参数(输入JSON和路径),并返回JSON文本(NVARCHAR(MAX))值。

As an example, let’s return the items stored within the first array in the root element:

例如,让我们返回根元素中第一个数组中存储的项目:

SELECT TOP 5 JSON_Query([Details], '$[0]')
FROM [AdventureWorks2017].[Person].[Person]

As shown in the image below, the result is a JSON string.

如下图所示,结果是一个JSON字符串。

Using JSON_QUERY() (SQL Server Json function) to search for an object within a JSON string

JSON_MODIFY()函数 (JSON_MODIFY() function)

This function modifies the value of a property within a JSON string and returns the updated JSON text. It takes three parameters; the input JSON string, the property JSON path, and the new value. As an example, If we are looking to add a leading zero to the BusinessEntityID property stored within the Details column. We should use the following query:

此函数修改JSON字符串中的属性值,并返回更新的JSON文本。 它包含三个参数; 输入JSON字符串,属性JSON路径和新值。 例如,如果我们要向“ 详细信息”列中存储的BusinessEntityID属性添加前导零。 我们应该使用以下查询:

UPDATE [AdventureWorks2017].[Person].[Person]
SET [Details] = JSON_MODIFY([Details],'$[0].BusinessEntityID','0' + JSON_VALUE([Details], '$[0].BusinessEntityID'))

Now if we execute the query we provided in the JSON_VALUE() function section, it will not retun any result until we add a leading zero to the condition:

现在,如果我们执行在JSON_VALUE()函数部分中提供的查询,它将不会重新调整任何结果,除非我们向条件添加前导零:

SELECT *
FROM [AdventureWorks2017].[Person].[Person]
WHERE JSON_VALUE([Details], '$[0].BusinessEntityID') = '01'

The following image shows the result of this query:

下图显示了此查询的结果:

validating the update query using JSON_VALUE() function

OPENJSON()函数 (OPENJSON() function)

If you are looking to parse a JSON text into a key-value pairs or a tabular data, you can use OPENJSON() table-valued function. To convert a JSON string to a key-value pair we must use OPENJSON() function as follows:

如果您希望将JSON文本解析为键值对或表格数据,则可以使用OPENJSON()表值函数。 要将JSON字符串转换为键值对,我们必须使用OPENJSON()函数,如下所示:

DECLARE @json nvarchar(max)
SELECT @json = JSON_QUERY([Details],'$[0]') from [AdventureWorks2017].[Person].[Person] WHERE JSON_VALUE([Details], '$[0].BusinessEntityID') = '01'
SELECT * FROM OPENJSON(@json)

The result of this query is a key-value pair of all JSON array objects in addition to the value type:

该查询的结果是除值类型以外的所有JSON数组对象的键值对:

Using OPENJSON() to retrun a jey-value pairs

The following JSON value types are supported:

支持以下JSON值类型:

Type code

Type description

0

null

1

string

2

int

3

true/false

4

array

5

object

类型代码

类型说明

0

空值

1个

2

整型

3

真假

4

数组

5

目的

If we know the JSON text schema, we can use OPENJSON() function to convert JSON into tabular data. We need to define the schema explicitly after this SQL Server JSON function. As an example:

如果我们知道JSON文本模式,则可以使用OPENJSON()函数将JSON转换为表格数据。 我们需要在此SQL Server JSON函数之后显式定义架构。 举个例子:

DECLARE @json nvarchar(max)
 
SELECT @json = [Details] from [AdventureWorks2017].[Person].[Person] WHERE JSON_VALUE([Details], '$[0].BusinessEntityID') = '01'
 
SELECT * FROM OPENJSON(@json) WITH ([BusinessEntityID] [int] ,
  [PersonType] [nchar](2) ,
  [NameStyle] [dbo].[NameStyle] ,
  [Title] [nvarchar](8) ,
  [FirstName] [dbo].[Name]  ,
  [MiddleName] [dbo].[Name] ,
  [LastName] [dbo].[Name]  ,
  [Suffix] [nvarchar](10) ,
  [EmailPromotion] [int]  ,
  [AdditionalContactInfo] [xml](CONTENT [Person].[AdditionalContactInfoSchemaCollection]) ,
  [Demographics] [xml](CONTENT [Person].[IndividualSurveySchemaCollection]) ,
  [rowguid] [uniqueidentifier]    ,
  [ModifiedDate] [datetime]  )

As shown in the image below, the query result is in tabular form.

如下图所示,查询结果采用表格形式。

Using OPENJSON() function with explicit schema

索引JSON列 (Indexing JSON column )

If we need to filter our queries based on a property value within the JSON column, and we need that this property is indexed, we should add a computed column based on this value. Then we must create an index for this column. As an example:

如果需要基于JSON列中的属性值过滤查询,并且需要对该属性进行索引,则应基于此值添加计算列。 然后,我们必须为此列创建索引。 举个例子:

ALTER TABLE Person.Person
ADD vBusinessEntityID AS JSON_VALUE(Details,'$[0].BusinessEntityID')
 
CREATE INDEX idx_BusinessEntityID
ON Person.Person(vBusinessEntityID)

将JSON数据导入SQL数据库 (Import JSON data into SQL database)

There are many methods to import JSON data into SQL database:

有很多方法可以将JSON数据导入SQL数据库:

  • Using Integration Services

    使用集成服务
  • Using OPENROWSET() with OPENJSON() function

    将OPENROWSET()与OPENJSON()函数一起使用

These methods are described in detail in this article, Import JSON data into SQL Server.

本文“将JSON数据导入SQL Server”中详细描述了这些方法。

结论 (Conclusion)

In this article, we have illustrated the SQL Server JSON functions added with the 2016 version. We provided some examples using the AdventureWorks database. We explained how to index properties stored within the JSON column, and finally, we briefly noted the available methods to import JSON into the SQL database.

在本文中,我们已说明了2016版本中添加SQL Server JSON函数。 我们提供了一些使用AdventureWorks数据库的示例。 我们解释了如何索引存储在JSON列中的属性,最后,我们简要地指出了将JSON导入SQL数据库的可用方法。

翻译自: https://www.sqlshack.com/sql-server-json-functions-a-bridge-between-nosql-and-relational-worlds/

sql与nosql

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值