rethinkdbreql

How to use ReQL filter and match command on arrays


I have a table in rethinkdb where each row has following structure -

{
  'name':'clustername',
  'services':[
     {
        'name':'service1'
     },
     {
        'name':'service2'
     }
  ]
}

I am running a query to filter service2 object like this

r.table('clusters').filter({"name":  "clustername"})
  .pluck('services').filter((service) => { 
     return service("name").match('service2')
  })

But this is not returning anything: No results were returned for this query

Can anyone tell why this is happening?


Solution

  • pluck returns sequence, so this query:

    r.table('clusters').filter({"name":  "clustername"}).pluck('services')
    

    will return:

    {
    
        "services": [
            {
                "name": "service1"
            } ,
            {
                "name": "service2"
            }
        ]
    
    }
    

    You need get services field from it, it will return array with services field of items found by filter.

    And after that you need to use your second filter on each item by using map.

    So, correct query:

    r.table('clusters').filter({"name": "clustername"}).pluck('services')("services").map(item => {
        return item.filter(service => { 
          return service("name").match("service2");
        });
    
    })