source

Postgres JSON 데이터 유형 Rails 쿼리

nicesource 2023. 2. 14. 21:29
반응형

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

반응형