[英]How to create index on json array type in mysql5.7
Now I use SQL script like SELECT * FROM user WHERE JSON_CONTAINS(users, '[1]');
现在我使用 SQL 脚本,如SELECT * FROM user WHERE JSON_CONTAINS(users, '[1]');
But it will scan full table, it's inefficient.但它会扫描全表,效率低下。 So I want to create the index on users
column.所以我想在users
列上创建索引。
For example, I have a column named users
, data looked like [1,2,3,4]
.例如,我有一个名为users
的列,数据看起来像[1,2,3,4]
。 Please tell me how to set index on JSON array type(Generate virtual column).请告诉我如何在 JSON 数组类型(生成虚拟列)上设置索引。 I had read the document on MySQL website, they all talked about to indexing in JSON object type by using JSON_EXTRACT()
function.我已经阅读了 MySQL 网站上的文档,他们都谈到了使用JSON_EXTRACT()
函数在 JSON 对象类型中建立索引。
It's now possible with MySQL 8+现在可以使用 MySQL 8+
Here is an example:下面是一个例子:
CREATE TABLE customers (
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
modified DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
custinfo JSON
);
ALTER TABLE customers ADD INDEX comp(id, modified,
(CAST(custinfo->'$.zipcode' AS UNSIGNED ARRAY)) );
Use it this way:以这种方式使用它:
SELECT * FROM customers
-> WHERE JSON_CONTAINS(custinfo->'$.zipcode', CAST('[94507,94582]' AS JSON));
More info: https://dev.mysql.com/doc/refman/8.0/en/create-index.html更多信息: https : //dev.mysql.com/doc/refman/8.0/en/create-index.html
You cannot, not at least the way you intend.你不能,至少是你想要的方式。 At The JSON Data Type we can read:在JSON 数据类型中,我们可以阅读:
JSON
columns, like columns of other binary types, are not indexed directly;JSON
列与其他二进制类型的列一样,不直接编入索引; instead, you can create an index on a generated column that extracts a scalar value from theJSON
column.相反,您可以在从JSON
列中提取标量值的生成列上创建索引。 See Indexing a Generated Column to Provide a JSON Column Index , for a detailed example.有关详细示例,请参阅索引生成的列以提供 JSON 列索引。
So with the restriction comes the workaround ;-)因此,随着限制而来的是解决方法;-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.