如何在Postgres中保存可搜索和可查询的json文档?

时间:2016-04-03 17:19:24

标签: java json postgresql database-design nosql

以JSON身份接收个人资料。我怎么能model它可以搜索这个JSON文档的每个值?
不仅需要搜索json文档。它也应该是可以查询的,像#34;找到所有喜欢塔兰蒂诺电影的人#34;。  我可以在具有一对多关系的关系模型中定义此文档。但是这种方法不允许从客户端进行自由文本搜索。
是否有更好的方法来处理这种情况?
文档看起来像这样:

{  
   "name":"FirstN LastN",
   "photo":nicephoto.jpg,
   "location":"Boston, MA",
   "contacts":[  
      {  
         "type":"phone",
         "value":"701290012734"
      },
      {  
         "type":"email",
         "value":"test@test.com"
      }
   ],
   "movies":[  
      {  
         "name":"The Godfather",
         "director":"Francis Ford Coppola",
         "releaseYear":"1972",
         "favQuote":"I'm gonna make him an offer he can't refuse. Okay?"
      },
      {  
         "name":"Pulp Fiction",
         "director":"Quentin Tarantino",
         "releaseYear":"1994",
         "favQuote":"Just because you are a character doesn't mean that you have character."
      }
   ],
   "school":null,

}

2 个答案:

答案 0 :(得分:0)

“找到所有喜欢塔兰蒂诺电影的人”需要在SQL中编写或转换,如:

select persons->>'name' from jdoc,json_array_elements(jdoc.persons->'movies') movies where movies->>'director' ~ 'Tarantino';

其他选择标准可以用类似的方式建模。

需要Postgres 9.3或更高版本

http://sqlfiddle.com/#!15/652eb/10

问题“如何保存”:

create table jdoc (persons json);
insert into jdoc values ('{  
   "name":"FirstN LastN",
   "photo":"nicephoto.jpg",
   "location":"Boston, MA",
  "contacts":[  
      {  
         "type":"phone",
         "value":"701290012734"
      },
      {  
         "type":"email",
         "value":"test@test.com"
      }
   ],
   "movies":[  
      {  
         "name":"The Godfather",
         "director":"Francis Ford Coppola",
         "releaseYear":"1972",
         "favQuote":"Im gonna make him an offer he cant refuse. Okay?"
      },
      {  
         "name":"Pulp Fiction",
         "director":"Quentin Tarantino",
         "releaseYear":"1994",
         "favQuote":"Just because you are a character doesnt mean that you have character."
      }
   ], 
   "school":null

}')
;

答案 1 :(得分:0)

您可能以FLWOR的身份looking

   for $d in doc("depts.xml")//deptno
   let $e := doc("emps.xml")//employee[deptno = $d]
   where count($e) >= 10
   order by avg($e/salary) descending
   return
     <big-dept>
        { $d,
           <headcount>{count($e)}</headcount>,
           <avgsal>{avg($e/salary)}</avgsal>
        }
     </big-dept>

尽管看起来Postgres没有plans支持Xquery