Search code examples
pythonrethinkdb-python

RethinkDB Join and Order using Python


I would like to join and order the field in RethinkDB. My tables and sample data is:

Category Table

{
"id":  "2be434e0-0f34-4705-ba7f-560437a8e65c" ,
"name":  "IT"
} {
"id":  "76db46b7-2b1b-4c6e-99dd-83852d921ec0" ,
"name":  "Electronic"
} {
"id":  "61774bf5-b197-4676-be95-873d6f701243" ,
"name":  "Motor"
}

Item table

{
"id":  "8d14ac9f-713c-4424-aba8-de2e6fb4d51a" ,
"category_id":  "2be434e0-0f34-4705-ba7f-560437a8e65c" ,
"item_name": 'Computer'
}
{
"id":  "266f34a7-b850-45b3-b15a-9fb59c90113d" ,
"category_id":  "2be434e0-0f34-4705-ba7f-560437a8e65c" ,
"item_name": 'Notebook'
}
{
"id":  "397e574c-0597-4198-97c6-33a50c6f464a" ,
"category_id":  "2be434e0-0f34-4705-ba7f-560437a8e65c" ,
"item_name": 'Smart Phone'
}
{
"id":  "3a080b71-a250-4616-a22b-c14483ce8be0" ,
"category_id":  "76db46b7-2b1b-4c6e-99dd-83852d921ec0" ,
"item_name": 'Generator'
}
{
"id":  "5a66eb5e-271a-47d6-8c4e-036fa06a0ea2" ,
"category_id":  "76db46b7-2b1b-4c6e-99dd-83852d921ec0" ,
"item_name": 'Air-Con'
}
{
"id":  "449ec1ef-dac0-42a3-aef9-e79f0556452a" ,
"category_id":  "61774bf5-b197-4676-be95-873d6f701243" ,
"item_name": 'Car'
}

I want to join and order by field count that tables in python. I want to following result

{
"id":  "2be434e0-0f34-4705-ba7f-560437a8e65c" ,
"name":  "IT",
"count": 3
} {
"id":  "76db46b7-2b1b-4c6e-99dd-83852d921ec0" ,
"name":  "Electronic",
"count": 2
} {
"id":  "61774bf5-b197-4676-be95-873d6f701243" ,
"name":  "Motor",
'count': 1
}

Help me please.


Solution

  •  r.table('Category').merge(lambda row:{'count':r.table('Item').filter({'category_id':row['id']}).count()}).order_by(r.desc('count')).run()
    

    I got the solution. Thanks all.