Skip to content

ReQL support for pivot/unpivot operations #838

Open

Description

@pixelspark

It seems that there currently is no easy way to do pivot/unpivot operations in ReQL. These operations are really useful when working with data sets such as network data (to convert back and forth between adjacency matrixes and tie lists).

An unpivot operation creates id-key-value pairs from objects, e.g.:

[{id:1, x:2, y:3}, {id:10, x:20, y:30}, {id:100, x:200, y:300}] 

becomes

[{id:1, k:"x", v:2}, {id:1, k:"y", v:3} ....]

A pivot operation is exactly the opposite (e.g. it groups key-value pairs to create larger objects). It is different from a grouped reduce operation, as it uses an attribute's value to determine the resulting column name (e.g. the 'k' attribute determines where the value from 'v' should be placed). Syntax could be something like:

r.table('foo').unpivot('id', 'k', 'v')
r.table('foo').pivot('id', 'k', 'v')

Activity

  1. pixelspark commented on May 18, 2013

    @pixelspark
    Author

    #181 and #272 are related to this request

  2. mlucy commented on May 18, 2013

    @mlucy
    Member

    Hi @pixelspark,

    We currently support these sorts of things through a really ugly API of coercing to and from arrays. (We hope to have implemented a better API by the time we release 1.6.)

    For example:

    irb(main):544:0> r({:id => 1, :x => 2, :y => 3}).coerce_to("array").run
    [["id", 1], ["x", 2], ["y", 3]]
    irb(main):547:0> r([["id", 1], ["x", 2], ["y", 3]]).coerce_to("object").run
    {"x"=>2, "y"=>3, "id"=>1}

    So you could write e.g. unpivot like this:

    def unpivot seq                                                        
      seq.concat_map {|obj|                                                
        obj[:id].do {|id|                                                  
          obj.coerce_to("array").filter{|x| x[0].ne('id')}.map {|kv|       
            {:id => id, :k => kv[0], :v => kv[1]}
          }                                                                
        }                                                                  
      }                                                                    
    end                                                                    
    irb(main):652:0> seq = r([{:id => 1, :x => 2, :y => 3}, {:id => 10, :x => 20, :y => 30}])
    r([{:y => 3, :x => 2, :id => 1}, {:y => 30, :x => 20, :id => 10}])
    irb(main):653:0> PP.pp unpivot(seq).run
    [{"k"=>"x", "v"=>2, "id"=>1},
     {"k"=>"y", "v"=>3, "id"=>1},
     {"k"=>"x", "v"=>20, "id"=>10},
     {"k"=>"y", "v"=>30, "id"=>10}]
  3. pixelspark commented on May 19, 2013

    @pixelspark
    Author

    Although a bit ugly, it seems like a usable workaround for now. Thanks @mlucy! For future reference and others looking for the same functionality, here is an example of how to implement pivot and unpivot in JS syntax:

    r.db('foo').table('bar')
      /* Unpivot */
      .concatMap(function(e) { 
            return r.do(e("id"), function(rid) {
                return e.coerceTo("array").map(function(p) {
                    return {id:rid, k:p.nth(0), v:p.nth(1)}; 
              })
          })
      })
    
        /* Pivot */  
      .groupedMapReduce(function(e) { 
            return e("id") 
      }, function(e) { 
            return r.expr([]).append(r.expr([]).append(e("k")).append(e("v"))) 
      }, function(acc, add) { 
            return acc.union(add)
      })
      .map(function(x) { 
        return x("reduction").coerceTo("object") 
      })
  4. coffeemug commented on May 20, 2013

    @coffeemug
    Contributor

    I'm temporarily moving this to 1.6 to see if we can find a better way of doing this.

  5. karlgrz commented on Jul 29, 2013

    @karlgrz

    I have been finding myself wanting an easy way to do this for a while now. It would be great if rethinkdb made this really easy to do.

  6. coffeemug commented on Aug 6, 2013

    @coffeemug
    Contributor

    For those watching this issue, this almost certainly won't happen until Rethink hits 2.0 -- sorry. The workaround above should be sufficient for most use cases, and unfortunately there are much more important things we have to do first. If you run into a use case where this is a real showstopper, please let us know and we'll see if we can reprioritize.

  7. pilwon commented on May 14, 2015

    @pilwon

    Rethink finally hit 2.0! 😋

  8. modified the milestones: subsequent, backlog on May 14, 2015
  9. coffeemug commented on May 14, 2015

    @coffeemug
    Contributor

    I moved this to subsequent because a lot of people have been asking about this, and I found myself needing these commands from time to time.

  10. thelinuxlich commented on Mar 12, 2018

    @thelinuxlich

    @srh we have .fold() now, can't we close this issue?

  11. srh commented on Mar 26, 2018

    @srh
    Contributor

    I think it would be really annoying to write a fold that does this, so I'll leave it open.

  12. c4lliope commented on Nov 23, 2020

    @c4lliope

    Syntax could be something like:

    r.table('foo').unpivot('id', 'k', 'v')
    r.table('foo').pivot('id', 'k', 'v')

    Are there any limitations to this proposal? Is this approach possible?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions