I use PostgreSQL 9.5 and Rails 5. I want to query the jsonb
column shown below that holds an array of JSON objects to return all the JSON array element containing {"kind":"person"}
and also perform a count.
The SQL I use is shown below the json data. Running the query just returns an empty array.
I have tried the queries suggested here and here.
This is what my jsonb
data looks like:
'[
{"kind":"person", "filter_term":"56","selected_attr":"customer"},
{"kind":"email", "filter_term":"marketer","selected_attr":"job_title"}
]'
I want one of the sql query to return:
data
----------------------------------------------------------------------
'{"kind":"person", "filter_term":"56","selected_attr":"customer"}'
(1 row)
and another query to return array back so that I can call count on it in my app and also loop over it to create forms:
data
----------------------------------------------------------------------
'[{"kind":"person", "filter_term":"56","selected_attr":"customer"}]'
(1 row)
I tried this SQL query:
"SELECT * FROM \"segments\" WHERE (payload @> '[{\"kind\":\"person\"}]')"
I also tried this query:
"SELECT payload FROM segments WHERE payload @> '[{\"kind\":\"person\"}]'::jsonb;"
Here is a 3rd query:
"SELECT * FROM segments s WHERE s.payload->'\"#{a}\"' @> '[{\"kind\":\"person\"}]';"
The model:
class Segment < ApplicationRecord
store_accessor :payload,:kind, :filter_term, :selected_model_name, :selected_attr, :limit, :selected_operator
end
The migration:
create_table "segments", force: :cascade do |t|
t.jsonb "payload", default: "[]", null: false
t.index ["payload"], name: "index_segments_on_payload", using: :gin
end