Postgres JSON 데이터 유형 Rails 쿼리
Postgres의 json 데이터 타입을 사용하고 있습니다만, json 내에 중첩된 데이터로 쿼리/오더를 하고 싶습니다.
json 데이터 유형의 .where를 주문하거나 쿼리하고 싶습니다.예를 들어 팔로어 수가 500을 넘는 사용자나 팔로어 또는 팔로어 수로 주문하는 사용자를 조회합니다.
감사합니다!
예:
model User
data: {
"photos"=>[
{"type"=>"facebook", "type_id"=>"facebook", "type_name"=>"Facebook", "url"=>"facebook.com"}
],
"social_profiles"=>[
{"type"=>"vimeo", "type_id"=>"vimeo", "type_name"=>"Vimeo", "url"=>"http://vimeo.com/", "username"=>"v", "id"=>"1"},
{"bio"=>"I am not a person, but a series of plants", "followers"=>1500, "following"=>240, "type"=>"twitter", "type_id"=>"twitter", "type_name"=>"Twitter", "url"=>"http://www.twitter.com/", "username"=>"123", "id"=>"123"}
]
}
이걸 우연히 발견하는 사람을 위해.ActiveRecord와 Postgres의 JSON 데이터 타입을 사용한 쿼리 리스트를 작성했습니다.좀 더 명확하게 하기 위해 자유롭게 편집해 주세요.
JSON 오퍼레이터에 대한 문서.https://www.postgresql.org/docs/current/functions-json.html 를 참조해 주세요.
# Sort based on the Hstore data:
Post.order("data->'hello' DESC")
=> #<ActiveRecord::Relation [
#<Post id: 4, data: {"hi"=>"23", "hello"=>"22"}>,
#<Post id: 3, data: {"hi"=>"13", "hello"=>"21"}>,
#<Post id: 2, data: {"hi"=>"3", "hello"=>"2"}>,
#<Post id: 1, data: {"hi"=>"2", "hello"=>"1"}>]>
# Where inside a JSON object:
Record.where("data ->> 'likelihood' = '0.89'")
# Example json object:
r.column_data
=> {"data1"=>[1, 2, 3],
"data2"=>"data2-3",
"array"=>[{"hello"=>1}, {"hi"=>2}],
"nest"=>{"nest1"=>"yes"}}
# Nested search:
Record.where("column_data -> 'nest' ->> 'nest1' = 'yes' ")
# Search within array:
Record.where("column_data #>> '{data1,1}' = '2' ")
# Search within a value that's an array:
Record.where("column_data #> '{array,0}' ->> 'hello' = '1' ")
# this only find for one element of the array.
# All elements:
Record.where("column_data ->> 'array' LIKE '%hello%' ") # bad
Record.where("column_data ->> 'array' LIKE ?", "%hello%") # good
이 http://edgeguides.rubyonrails.org/active_record_postgresql.html#json에 따르면 사용방법에 차이가 있습니다.->그리고.->>:
# db/migrate/20131220144913_create_events.rb
create_table :events do |t|
t.json 'payload'
end
# app/models/event.rb
class Event < ActiveRecord::Base
end
# Usage
Event.create(payload: { kind: "user_renamed", change: ["jack", "john"]})
event = Event.first
event.payload # => {"kind"=>"user_renamed", "change"=>["jack", "john"]}
## Query based on JSON document
# The -> operator returns the original JSON type (which might be an object), whereas ->> returns text
Event.where("payload->>'kind' = ?", "user_renamed")
그러니까 한번 해봐.Record.where("data ->> 'status' = 200 ")또는 문의에 적합한 연산자(http://www.postgresql.org/docs/current/static/functions-json.html))를 참조하십시오.
질문 내용이 표시된 데이터와 일치하지 않는 것 같습니다만, 테이블에 이름이 지정되어 있는 경우는,users그리고.data이 테이블의 필드에는 JSON이 다음과 같이 표시됩니다.{count:123}그 후 쿼리
SELECT * WHERE data->'count' > 500 FROM users
효과가 있습니다.데이터베이스 스키마를 살펴보고 레이아웃을 이해하고 쿼리가 작동하는지 확인한 후 Rails 규약과 복잡하게 만드십시오.
레일에서의 JSON 필터링
Event.create( payload: [{ "name": 'Jack', "age": 12 },
{ "name": 'John', "age": 13 },
{ "name": 'Dohn', "age": 24 }]
Event.where('payload @> ?', '[{"age": 12}]')
#You can also filter by name key
Event.where('payload @> ?', '[{"name": "John"}]')
#You can also filter by {"name":"Jack", "age":12}
Event.where('payload @> ?', {"name":"Jack", "age":12}.to_json)
자세한 내용은 이쪽에서 확인하실 수 있습니다.
언급URL : https://stackoverflow.com/questions/22667401/postgres-json-data-type-rails-query
'source' 카테고리의 다른 글
| 모든 타입 스크립트유형 체크를 비활성화하려면 어떻게 해야 하나요? (0) | 2023.02.14 |
|---|---|
| mongodb 여러 어레이 항목에서 검색 (0) | 2023.02.14 |
| JSON Stringify가 UTC로 인해 날짜를 변경합니다. (0) | 2023.02.14 |
| useState는 동기화되어 있습니까? (0) | 2023.02.14 |
| 구체화된 뷰와표:어떤 장점이 있습니까? (0) | 2023.02.14 |