16

如何在 MySQL 服务器的 Json 数据类型的子文档上创建索引?

我知道我们必须从基表创建一个生成的列,然后需要对该列进行虚拟索引或存储。

但我想要为子文档创建生成列的语法。

4

3 回答 3

19

对于存储在其中的索引值JSON,请使用存储的生成列

例如,对于索引titlecategory

{"title": "Some Title", "category": "Some Category", "url": "...", ...}

使用类似的东西:

CREATE TABLE listings (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(255) AS
    (data->>'$.title') STORED,
  category VARCHAR(255) AS
    (data->>'$.category') STORED,
  data JSON NOT NULL,
  KEY (title),           -- index title
  KEY (category),        -- index category
  KEY (title, category)  -- composite index of title & category
);

阅读更多关于MySQL 作为智能 JSON 存储的信息:-)

于 2020-07-11T12:26:40.400 回答
11

在 MySQL 8.0.21 版本中,可以使用以下语法:

CREATE TABLE inventory(
items JSON,
INDEX i1 ( (JSON_VALUE(items, '$.name' RETURNING CHAR(50))) ),
INDEX i2 ( (JSON_VALUE(items, '$.price' RETURNING DECIMAL(5,2))) ),
INDEX i3 ( (JSON_VALUE(items, '$.quantity' RETURNING UNSIGNED)) )
);

并使用以下查询:

SELECT items->"$.price" FROM inventory
WHERE JSON_VALUE(items, '$.name' RETURNING VARCHAR(50)) = "hat";

SELECT * FROM inventory
WHERE JSON_VALUE(items, '$.price' RETURNING DECIMAL(5,2)) <= 100.01;

SELECT items->"$.name" AS item, items->"$.price" AS amount
FROM inventory
WHERE JSON_VALUE(items, '$.quantity' RETURNING UNSIGNED) > 500;

来源:https ://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-21.html

于 2021-03-08T14:57:20.800 回答
9
于 2016-07-15T06:56:39.470 回答