Search code examples
rethinkdbrethinkdb-javascript

RethinkDB: .get() with just part of the uuid?


Let's say this is the uuid of one of my documents in RethinkDB: 594a64ab-b78b-4838-a79f-318020a352a9

Normally, to retrieve the document, I do:

r.db("databasename").table("tablename").get('594a64ab-b78b-4838-a79f-318020a352a9')

Is there some way I can achieve the same thing with only some prefixing portion of the uuid? e.g. I want to do this:

r.db("databasename").table("tablename").getByPrefix('594a64ab-b78b')

Is this possible?


Solution

  • Another solution, including all the steps:

    1/ Create test table

    r.table('foo').insert([
      {foo: 1},
      {foo: 2},
      {foo: 3},
      {foo: 4},
      {foo: 5}
    ])
    

    2/ List table content

    r.table('foo')
    

    Output:

    [
      {"foo":4,"id":"3c6873af-0dfc-41d3-99ad-894bab981635"},
      {"foo":1,"id":"302baaa5-1443-408c-bb58-7970e71129ac"},
      {"foo":2,"id":"ca5ff9c2-8079-4a19-9cfc-4e7b0a834555"},
      {"foo":5,"id":"aabb6c38-710a-444c-a4ae-b8ee14b5e802"},
      {"foo":3,"id":"4fc2e6e8-9434-4fa9-831b-4208bc82fd35"}
    ]
    

    3/ Create secondary index

    r.table('foo').indexCreate('id_prefix', function(d){
      return d('id').slice(0, 13)
    })
    

    4/ List index content

    r.table('foo').distinct({index:'id_prefix'})
    

    Output:

    ["302baaa5-1443","3c6873af-0dfc","4fc2e6e8-9434","aabb6c38-710a","ca5ff9c2-8079"]
    

    5/ Use the index to find the document(s) with prefix "4fc2e6e8-9434"

    r.table('foo').getAll("4fc2e6e8-9434", {index:'id_prefix'})
    

    Output

    [{"foo":3,"id":"4fc2e6e8-9434-4fa9-831b-4208bc82fd35"}]
    

    This is a longer setup and solution, BUT, on a table of for example several millions docs, it can really make it faster.