Postgres JSON data type Rails query

前端 未结 3 1939
孤城傲影
孤城傲影 2020-11-28 19:40

I am using Postgres\' json data type but want to do a query/ordering with data that is nested within the json.

I want to order or query with .where on the json data

3条回答
  •  孤城傲影
    2020-11-28 19:55

    For any who stumbles upon this. I have come up with a list of queries using ActiveRecord and Postgres' JSON data type. Feel free to edit this to make it more clear.

    Documentation to the JSON operators used below: https://www.postgresql.org/docs/current/functions-json.html.

    # Sort based on the Hstore data:
    Post.order("data->'hello' DESC")
    => #"23", "hello"=>"22"}>, 
        #"13", "hello"=>"21"}>, 
        #"3", "hello"=>"2"}>, 
        #"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
    

提交回复
热议问题