如何在MySQL中的json列上创建索引?

时间:2016-07-15 06:18:40

标签: json database indexing mysql-5.7

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

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

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

3 个答案:

答案 0 :(得分:5)

在 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

答案 1 :(得分:3)

JSON列与其他二进制类型的列一样,不会直接编入索引;相反,您可以在生成的列上创建索引,从而从JSON列中提取标量值。有关详细示例,请参见第“Secondary Indexes and Generated Virtual Columns”节。

答案 2 :(得分:2)

对于索引存储在JSON中的值,请使用存储的generated column

例如,为索引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 as smart JSON storage:-)