Skip to content

ReQL non proposal: Getting keys whose compound indexes has a common prefix. #955

Closed

Description

@jdoliner

Suppose I have a compound index cid and I want to get all of documents that have "foo" as the first value in the compound index. AFAIK there isn't a great way to do this in ReQL. The best way to do this that I can come up with is:

r.table.between(["foo"], ["fop"], id = "cid").filter(lambda x: x["cid"][0] == "foo")

Which isn't terribly pretty. I'm not sure I have a full proposal for this (hence the non proposal title). I'd like the support the syntax:

r.table.prefix(["foo"], id = "cid")

which would be feasible. What do others think would be a good API for this?

Activity

  1. jdoliner commented on Jun 6, 2013

    @jdoliner
    ContributorAuthor

    This was requested in IRC by lincolnq.

  2. mlucy commented on Jun 6, 2013

    @mlucy
    Member

    After issue #869, between will be half-open by default and changeable with an optarg, so you could write r.table.between(["foo"], ["fop"]) and it would work I think.

  3. jdoliner commented on Jun 6, 2013

    @jdoliner
    ContributorAuthor

    @mlucy no it wouldn't. ["fooa"] is between ["foo"] and ["fop"].

  4. lincolnq commented on Jun 6, 2013

    @lincolnq

    I have a bunch of ideas on this front.

    In brief:

    1. Make indexes accessible in ReQL as their own (readonly) selection:
      table.index('uid') ==> [ {'uid': 'value_of_uid', 'id': 'value_of_primary_key'}, ...]
    2. Add 'selection range operators' to perform a guaranteed-to-be-fast range query over a selection, based on its primary key. Essentially, this is half of between. There would be options or variant forms for including/excluding prefix matches. Example:
      selection.filterLtePrefix('b') ==> new selection with all entries from selection where the 1-length prefix of the primary key is 'b' or less. So this would grab ['a', 'ab', 'b', 'bc'] but not 'c'.

    Benefits:

    • Now, between desugars into (e.g.) sel.index().filterGte().filterLte().eqJoin().zip()
    • @jdoliner's prefix desugars into sel.index().filterGte().filterLtePrefix().eqJoin().zip()
    • You can write queries that only access the index without doing that eqJoin, which is very useful in some scenarios (I wanted it today)

    Problems:

    • in the above "between" example, the desugar doesn't work because eqJoin() doesn't produce a selection but between does. So we would need to work around that somehow.

    EDIT: .index() (with different semantics, but a similar idea) was discussed in #602 .

  5. coffeemug commented on Jun 7, 2013

    @coffeemug
    Contributor

    SQL dbs typically allow any leftmost prefix of a compound index to be used by the optimizer to efficiently find rows. So it's the status quo, and we should probably do it too (especially since we already know it's useful from @lincolnq's report).

    Could we allow specifying a prefix everywhere where the user can specify a compound index to search by that prefix? E.g.:

    // where `idx` is a compound index of the form `[l, m, n]`
    
    // get all documents where idx starts with `foo`
    r.table('foo').getAll(['foo'], { index: 'idx' })
    
    // get all documents where idx starts with `['foo', 'bar']`
    r.table('foo').getAll(['foo', 'bar'], { index: 'idx' })
    
    // get all documents where idx is between the prefex
    r.table('foo').between(['foo', 'bar'], ['zet', 'zem'], { index: 'idx' })
    

    This gives a few benefits:

    1. People can efficiently search by compound index prefixes
    2. The syntax is very natural
    3. We don't have to define new commands and complicate the API at all
    4. The lt/lte/gt/gte will be automatically handled by between once we add openness/closeness flags

    Would this proposal work?

  6. lincolnq commented on Jun 7, 2013

    @lincolnq

    @coffeemug's proposal would work for me, I think -- but how do you know when getAll is going to do a prefix match, as opposed to an exact match?

  7. coffeemug commented on Jun 7, 2013

    @coffeemug
    Contributor

    It would do a prefix match if you don't specify all the attributes of the compound index. That is, if your index is [i, j, k] and you say getAll([1], { index: 'foo' }), you'll get a prefix match. If you say getAll([1, 2, 3], { index: 'foo' }), you'll get a full match.

    Does that make sense?

  8. coffeemug commented on Jun 7, 2013

    @coffeemug
    Contributor

    Another option is to introduce an optional flag matchPrefix to be passed to commands that work on an index (e.g. getAll, between). If you pass the flag set to true, it matches documents based on a prefix, otherwise it skips them. This way there is no confusion.

  9. jdoliner commented on Jun 7, 2013

    @jdoliner
    ContributorAuthor

    @coffeemug that doesn't work an index can contain docs with the index ["foo"] and ["foo", "bar"]. We need to have a special term to specify prefix matching.

  10. coffeemug commented on Jun 7, 2013

    @coffeemug
    Contributor

    @jdoliner -- right, a matchPrefix flag (possible with a better name) would address this issue.

  11. jdoliner commented on Jun 7, 2013

    @jdoliner
    ContributorAuthor

    The flag also might be a bit clunky with between because you'd need one to specify that the left side is a prefix and one to specify that the right side is a prefix. But I'm sure we can work this out.

  12. coffeemug commented on Jun 7, 2013

    @coffeemug
    Contributor

    I don't believe it's possible to efficiently use the right side as a prefix. Since the users can only use the left side, this wouldn't be an issue. (As a data point, SQL systems don't allow you to use the right side as a prefix for this reason)

  13. jdoliner commented on Jun 7, 2013

    @jdoliner
    ContributorAuthor

    Why wouldn't that be possible?

  14. jdoliner commented on Jun 7, 2013

    @jdoliner
    ContributorAuthor

    Actually wait. I bet it's the other way around. I bet you can't have the left side be a prefix and that's because it's already implicitly a prefix since ["foo"] < ["foo", "bar"].

  15. 6 remaining items

  16. stuartpb commented on Feb 19, 2015

    @stuartpb

    Now that the open/closed flags have been implemented, couldn't you do this with r.between(prefix, prefixWithLastCharCodeUp1, {index: index, left_bound: 'open', right_bound: 'closed'})?

    (snipped irrelevant thought below)

    Perhaps a note that, right now, if you want to use a prefix for an index query, you should just make another secondary index for types of prefix (using an index function to provide whatever truncation applies)?

    Granted, it's not great if you're looking to do something like autocomplete, but it's something.

  17. danielmewes commented on Feb 19, 2015

    @danielmewes
    Member

    @stuartpb Thanks for pointing that out. That indeed works (it's basically what @jdoliner had noted in the initial post at the top with between(["foo"], ["fop"], id = "cid"), except that you can cut off the filter now.
    In fact it's going to become even easier with #1023:
    r.table(...).between(["foo", r.minval], ["foo", r.maxval]).

    This is still not quite as nice as a separate prefix syntax, especially since you have to use between instead of getAll and that might not be obvious to new users. So I think there's still value in this issue, but there's definitely a better work-around now.

  18. stuartpb commented on Feb 19, 2015

    @stuartpb

    r.table(...).between(["foo", r.minval], ["foo", r.maxval])

    Is that right? That's what I had written initially, but it seemed to me that even if the right bound were open (which I assume is what r.maxval means), that means it's still not going to find things that start with the prefix, as they would sort lower than it. Do they sort equivalent to the prefix?

  19. danielmewes commented on Feb 20, 2015

    @danielmewes
    Member

    @stuartpb Ohh I think we're talking about different things. Sorry I misunderstood your proposal.

    This thread is about what we call a compound index, where you typically index by an array containing multiple fields from the document. So the keys look like [r.row('field1'), r.row('field2'), r.row('field3')]. Now the question was how to query such an index if you only want to filter by the value of say field1, but don't care what's in field2 or field3. So that's what you can use r.minval and r.maxval for.

    What you described I believe was filtering by a prefix of a string, didn't you? This is independent of compound indexes, and for that indeed your solution is the right one (and the only one that currently works I think).

  20. stuartpb commented on Feb 20, 2015

    @stuartpb

    Right - I was getting a little lost because it seems a lot of this discussion hinges on the implementation essentially being a "prefix" for what is, under the hood, one big string.

    For only wanting a single component of a compound index, I would go back to my initial (snipped above) suggestion to consider using a separate secondary index for just the "prefix" component of the compound index. (Granted, that's not a one-size-fits-all solution, especially at scale.)

  21. stuartpb commented on Feb 20, 2015

    @stuartpb

    Oh, okay, I get what the r.minval and r.maxval do in that query now - they stand in for the second part of the compound index, effectively saying "the second part can be anything". What confuses me is how the query works when they're not specified - what is their default value, if not these? Does it look for documents in which that part of the index is in some way not defined?

  22. mlucy commented on Feb 20, 2015

    @mlucy
    Member

    @stuartpb -- because RethinkDB is (mostly) a JSON datastore, we don't restrict you to a particular type in your index. A "compound index" is just an index where the type of the index is an array. So if you specify a one-element array as e.g. the lower part of your range, we just treat that one-element array as the lower part of your range -- we don't assume that everything in the index is a two-element array, because it might not be true.

  23. stuartpb commented on Feb 20, 2015

    @stuartpb

    So how do one-element arrays sort relative to two-element arrays?

  24. mlucy commented on Feb 20, 2015

    @mlucy
    Member

    We compare the first element of the arrays. If one of the first elements is smaller, that array is smaller. If the first elements are equal, the one-element array is considered smaller.

    In general it's something like

    def cmp(arr1, arr2)
      if arr1 == []
        if arr2 == []
          return 0
        else
          return -1
        end
      elsif arr2 == []
        return 1
      else
        el1cmp = cmp(arr1[0], arr2[0])
        if el1cmp != 0
          return el1cmp
        else
          return cmp(arr1[1..-1], arr2[1..-1])
        end
      end
    end
    
  25. stuartpb commented on Feb 20, 2015

    @stuartpb

    So r.table(...).between(["foo", r.minval], ["foo", r.maxval]) could just be reduced to r.table(...).between(["foo"], ["foo", r.maxval]) ?

  26. mlucy commented on Feb 20, 2015

    @mlucy
    Member

    Yes, except if you happened to have an entry in your index with the exact key ["foo"], it would be omitted from the first and included in the second.

  27. srh commented on May 17, 2017

    @srh
    Contributor

    Closing because I'm trimming down open issues and the need for this is obviated by r.maxval. And it's still in the proposal stage. If you come across this and want this (because appending r.maxval is kind of annoying), be sure to chime in.

  28. modified the milestones: outdated, backlog on May 17, 2017
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

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions