Skip to content

ReQL semi-proposal: extending selections to objects #2692

Open

Description

@coffeemug

There is a whole class of document manipulation tasks that are extremely frustrating to perform in ReQL. Consider the following example document:

{
  # primary key, a db_name/table_name pair; named "table"
  "table": "db_name.table_name_1",

  # list of shards for the table
  "shards": [
    {
      # shard name
      name: "shard1",

      # list of replicas; must be the same length across all shards;
      # servers are specified by name
      "replicas": ["m1", "m2"],

      # priority list of directors; must be a non-empty subset of replicas;
      # this field may be omitted, in which case the system just uses the
      # replica list above
      "director_candidates": ["m2"]
    },
    {
      # shard name
      name: "shard2",

      # list of replicas; must be the same length across all shards;
      # servers are specified by name
      "replicas": ["m1", "m2"],

      # priority list of directors; must be a non-empty subset of replicas;
      # this field may be omitted, in which case the system just uses the
      # replica list above
      "director_candidates": ["m2"]
    }
  ]
}

Suppose I'd like to change the second replica in shard2 from m2 to m3. Doing that in ReQL right now is really, really, really hard.

I propose introducing a concept of subobject selections, that would allow performing this operation as follows:

r.table('foo')
  .get(doc_id)('shards')
  .filter({ 'name': 'shard2'})('replicas').nth(1)
  .update('m3')

Commands like get_field, pluck, nth, and filter (called on selections of objects or arrays) would return subobject selections that could then be modified via update, delete, and replace directly. This is absolutely beautiful because I could incrementally build up a query for precisely the element I want, and then change it by tacking on a mutable command.

Some open questions I can think of:

  • How do we make this work with our type system? What are the edge cases I didn't think through?
  • This introduces a weird duality in commands -- if the object above isn't a document in the table and is passed via r.expr, the code to return a new object with the second replica of shard2 modified is dramatically different (and much more complicated) from the code if the object is a document in the table. Is there anything we can do to unify these two use cases so the code looks similar?

Related to (and possibly supersedes) #2056.

Activity

  1. added this to the subsequent milestone on Jul 11, 2014
  2. AtnNn commented on Jul 11, 2014

    @AtnNn
    Member

    I like this idea.

    However it seems to break down if you want to modify multiple parts of the document.

    The "modifiable" state could be preserved when using do and for_each. And when modifying an object, the body of the function passed to do and for_each could be an array of modifications to apply sequentially.

    Something like this:

    r.table('foo')
      .get(doc_id)('shards').nth(0).('replicas').do(
        lambda x: [
           x.nth(0).update('m3'),
           x.nth(1).update('m4')])
    
    r.table('foo')
      .get(doc_id)('shards')('replicas').for_each(
        lambda row: row.update(lambda x: x.set_insert('m3')))
    

    There is now a weird duality in commands -- if the object above isn't a document in the table [...] the code [...] is dramatically different (and much more complicated)

    There could be a command that turns an object into one that can be modified:

    r.expr({'a': [{'b': 1}]})
      .modify(
        lambda x: [
          x['a'][0]['b'].replace(2),
          x.merge({'c': 3})])
    → {'a': [{'b': 2}], 'c': 3}
    
  3. coffeemug commented on Jul 11, 2014

    @coffeemug
    ContributorAuthor

    For the second problem above, perhaps we can introduce a command to fix this. Something like the following (but with a better name):

    r.expr(doc).copyAndChange(function(doc) {
        return doc('shards').filter({ 'name': 'shard2'})('replicas').nth(1)
                            .update('m3')
    })
  4. coffeemug commented on Jul 11, 2014

    @coffeemug
    ContributorAuthor

    Err, @AtnNn beat me to it.

  5. coffeemug commented on Jul 11, 2014

    @coffeemug
    ContributorAuthor

    Man, this would be super-duper-uber delightful.

  6. modified the milestones: , subsequent on Jul 11, 2014
  7. coffeemug commented on Jul 11, 2014

    @coffeemug
    ContributorAuthor

    Moving to polish because this is important.

  8. deontologician commented on Jul 11, 2014

    @deontologician
    Contributor

    Expanding on @AtnNn 's example, multiple operations might be common enough for a syntax like:

    r.table('foo')
      .get(doc_id)('shards').nth(0).('replicas').fork(
           r.row.nth(0).update('m3'),
           r.row.nth(1).update('m4'))
  9. srh commented on Jul 11, 2014

    @srh
    Contributor

    However it seems to break down if you want to modify multiple parts of the document.

    You're making this too complicated. Updating multiple fields at once with weird particular updates can be done by doing a replace on a pluck, and if you want to update particular array entries in particular ways, a replace on the whole array, or just the whole document.

  10. coffeemug commented on Jul 11, 2014

    @coffeemug
    ContributorAuthor

    It might be worth not worrying about multiple updates for the first implementation and making those changes the way @srh suggests. If we find that to be too painful, we can always reconsider.

  11. AtnNn commented on Jul 11, 2014

    @AtnNn
    Member

    a replace on the whole array, or just the whole document

    @srh The motivation behind the proposal is to avoid such updates because they are very hard to do in ReQL currently. Compare my protoype above with the following query that works in 1.13:

    r.table('foo')
      .get(doc_id)
      .update({
        'shards': lambda shards:
          shards[0].merge(
            { 'replicas': ['m3', 'm4', shards[0]['replicas'].slice(2)] })})
    

    There is nothing elegant about this query. I'm used to helping users write such queries, but it is unreasonable to expect users to write and maintain queries like this.

    My suggestion of using arrays however is just a shortcut. Perhaps it is sufficient to just chain modify, as in sequence.replace(r.row.modify(...).modify(...))

  12. coffeemug commented on Jul 11, 2014

    @coffeemug
    ContributorAuthor

    Compare my protoype above with the following query that works in 1.13

    But there is a middle ground between the two. Consider:

    r.table('foo')
      .get(doc_id)('shards').nth(0).('replicas').do(
        lambda x: [
           x.nth(0).update('m3'),
           x.nth(1).update('m4')])

    vs

    r.table('foo')
      .get(doc_id)('shards').nth(0).('replicas').update(
        lambda x: x.changeAt(0, 'm3').changeAt(1, 'm4')
      )

    The latter one is actually ok IMO.

  13. 3 remaining items

  14. AtnNn commented on Jul 11, 2014

    @AtnNn
    Member
  15. coffeemug commented on Jul 11, 2014

    @coffeemug
    ContributorAuthor

    That sounds pretty compelling.

  16. coffeemug commented on Jul 21, 2014

    @coffeemug
    ContributorAuthor

    Note: copying @robert-zaremba's commend from #2729 (comment) here:

    Currently if we want to manipulate the object and set some of it's fields we need to deconstruct it using map or keys.

    The use case is to allow writing more sophisticated function manipulation.
    Eg something we could write in JS:

    function (doc1, doc2) {
        doc1.inner.key = doc2.inner.key2
        return doc1
    }
    

    Proposal:

    set method, which will manipulate an object:

    doc1.inner.set(key, val)
    
  17. mlucy commented on Jul 22, 2014

    @mlucy
    Member

    This seems like it's getting very close to #895.

  18. modified the milestones: , on Aug 13, 2014
  19. modified the milestones: subsequent, on Sep 4, 2014
  20. modified the milestones: 2.1, subsequent on Mar 24, 2015
  21. modified the milestones: subsequent, 2.1 on Apr 17, 2015
  22. ha1331 commented on Aug 13, 2015

    @ha1331

    My idea would be:

    functionThatDoesStuffIfConditionIsMetAndReturnsEveryDocumentExceptIfModeIsDelete(condition, action[,{mode: 'update'|'replace'|'delete'}), or: fTDSICIMAREDEIMID() .If this has some actual merit, you might want to figure out better name for this.

    How would fTDSICIMAREDEIMID() work? Lets say you have a document that looks something like this:

    {id: 1,
        topic: "sample document",
        comments: [{id: 'a', topic: "fabulous comment", text: "I like this.", likes: 0},
            {id: 'b', topic: "not so fabulous comment", text: "I don't like this.", likes: 10}
            {id: 'c', topic: "all your bases are belong to us", text: "Lizard people are a thing you know.", likes: 0}
            {id: 'd', topic: "where are all the cat pictures", text: "i don't even like cats, I'm addicted to them.", likes: 0}]
    }
    

    Now you wanted to add a "like" to one of the comments, what you would do is:

    r.db('cats_and_lizards').table('posts').get(1).update(function(post){
        return post.merge({
            comments: post('comments').fTDSICIMAREDEIMID(
                function(item){
                    return item('id').eq('d')
                }, 
                function(itemToModify){
                    return itemToModify.merge( { likes: itemToModify('likes').add(1) } )
                }, 
                {mode: 'update'}
            )    
        })
    })

    in this example fTDSICIMAREDEIMID() would return:

    [{id: 'a', topic: "fabulous comment", text: "I like this.", likes: 0},
            {id: 'b', topic: "not so fabulous comment", text: "I don't like this.", likes: 10}
            {id: 'c', topic: "all your bases are belong to us", text: "Lizard people are a thing you know.", likes: 0}
            {id: 'd', topic: "where are all the cat pictures", text: "i don't even like cats, I'm addicted to them.", likes: 1}]
    

    If {mode: 'delete'} it would have returned the array without the one object that had id: "d" this delete mode is here mainly to enable well... deleting nested items.

    "update" & "replace" modes work like update() and replace(), "delete" mode is for convenience. I think this proposition enables new ways to do things without going too far from how people have used ReQL before. I'm not an expert, but this seems to allow multiple updates to different fields inside a single update().
    edit:

    mode: "drop" I think is better than "delete", because it describes the action better. After all nothing gets deleted.

  23. mike-marcacci commented on Mar 11, 2016

    @mike-marcacci

    I'd just like to point out that these semantics might be able to be reused for atomic, multi-document mutations if such a feature were implemented like this.

  24. netojose commented on Nov 28, 2019

    @netojose

    5 years later, and this issue still opened? :o

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