2014-03-07 36 views
0

我目前使用的Postgres 9.3.3搜索關鍵字在PostgreSQL的JSON場

以下是我的表看起來像 -

Column  |   Type   |        Modifiers        | Storage | Stats target | Description 
--------------------+--------------------------+--------------------------------------------------------------------+----------+--------------+------------- 
id     | integer     | not null default nextval('playerbase_palyerdata_id_seq'::regclass) | plain |    | 
date_joined  | timestamp with time zone | not null               | plain |    | 
belongs_to_camp_id | integer     | not null               | plain |    | 
belongs_to_coach_id | integer     | not null               | plain |    | 
json_kvps   | character varying(2000) | not null               | extended |    | 

一個樣本數據如下 -

id |  date_joined | belongs_to_camp_id | belongs_to_coach_id | json_kvps 

1 | 2014-03-07 18:10:45.824749+05:30 |     1 |     1 | {"alumnicode": "2003360009", "emailusername": "[email protected]", "altemail": "", "salutation": "Mrs", "fname": "Aaron", "mname": "V", "lname": "Schwartz", "fullname": "Aaraon M Scwartz", "programmename": "MEP", "batchyearin": "2003"} 

現在我想要搜索整個表格,並找到具有「emailusername」的用戶:「[email protected]

如此地 - http://www.postgresql.org/docs/current/static/functions-json.html

我嘗試如下編寫一個查詢 -

SELECT * FROM playerbase_playerdata WHERE json_kvps->>'emailusername' = '[email protected]'; 

我期待一個列以上,而不是我得到了下面的錯誤 -

ERROR: operator does not exist: character varying ->> unknown 
LINE 1: ...ELECT * FROM memberbase_memberdata WHERE json_kvps->>'emailu... 
                  ^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. 
莫非

有人請告訴我,我錯過了什麼?

+0

「可能有人請告訴我,我缺少什麼?」文檔中的postgres版本號。這些運營商增加了9.3。 9.2中提供的一些功能。但9.1中沒有任何內容。 – pozs

+0

升級到版本9.3.3 –

+0

然後在標題&標籤中也反映出正確的版本。 - 對於你的問題:你必須使用'json'類型,而不是'text'和'varchar'。 – pozs

回答

1

像這樣的功能只存在於PostgreSQL 9.3版本中。 因此,不幸的是,要做出這樣的查詢,你需要更新你的PostgreSQL。

如果你有9.3,那麼你需要使用json列類型。

在這裏你可以看到一些例子。它幫助我,更早: http://clarkdave.net/2013/06/what-can-you-do-with-postgresql-and-json/

祝你有美好的一天。

0

在django模型的情況下,你可以使用JsonField。

https://pypi.python.org/pypi/jsonfield

它的工作正常,但如果您使用PostgreSQL版本低於9.2,它會創建字符列。

0
select [Required Fields] from [Table Name] WHERE [Column Name]::text = '{[Key]}' ::text 
0

對於PostgreSQL 9.3或更高,一個可能的解決方案可以是使用流延到JSON:

SELECT * FROM playerbase_playerdata WHERE json_kvps - >> 'emailusername'= '[email protected]' ;

SELECT * FROM playerbase_playerdata WHERE CAST(json_kvps AS JSON)->>'emailusername' = '[email protected]';