在PostgreSQL 9.2中的json字段上创建索引 [英] Create index on json field in PostgreSQL 9.2

查看:1014
本文介绍了在PostgreSQL 9.2中的json字段上创建索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些带有json列的表,并希望在这些列上构建索引。但是,我得到了一个默认的运算符类( http://www.postgresql。组织/文档/ 9.2 /静态/ SQL-createopclass.html )。有人已经这样做了还是给了我一个替代方案?

I have a few tables with json columns and would like to build an index on these columns. However, I get a default operator class (http://www.postgresql.org/docs/9.2/static/sql-createopclass.html). Has someone already done that or give me an alternative?

要重现这个问题,请尝试:

To reproduce the problem, try:

>> create table foo (json json, id int);
CREATE TABLE
>> create index on foo (id);
CREATE INDEX
>> create index on foo (json);
ERROR:  data type json has no default operator class for access method "btree"
HINT:  You must specify an operator class for the index or define a default operator class for the data type.

同样适用于 gist gil 索引。

有趣的是,当我尝试以下操作时,我没有收到错误:

Interestingly, I don't get the error when I try the following:

>> create type "nested" as (json json, extra text);
CREATE TYPE
>> create table bar (id int, json nested);
CREATE TABLE
>> create index on bar (json);
CREATE INDEX

这是因为没有为组件创建索引吗?

Is that because no index is created for the components?

好的,主要问题是默认运营商。任何帮助或共享经验表示赞赏。
谢谢。

Okay, the main issue is the default operator. Any help or shared experience with that is appreciated. Thanks.

推荐答案

最适合我案例的解决方案如下:

The solution that works best for my case is the following:

我只是将json视为文本并在文本上创建索引。

I simply treat json as text and create an index on the text.

>> create index on foo ((json::text));

然后必须转换查询,以便它使用索引。

A query would then have to be transformed so that it uses the index.

解释显示是否使用了索引。

Explain reveals whether the index is used or not.

>> explain select * from foo where json::text = 'foo';

这篇关于在PostgreSQL 9.2中的json字段上创建索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆