Skip to content

Secondary indices interface #602

Closed
Closed

Description

@wmrowan

Now that secondary indices are almost complete it's time to nail down just how it is that secondary indices will be presented to users and how they will have to use them. After a short discussion earlier today it became clear that said interface hadn't yet been settled on so I'd like to present a more fleshed out version of one of the two proposals then discussed and advocate for it's adoption.

In previous discussions we have looked to SQL both for helpful suggestions as to what users might be looking for and for warnings of what to avoid. It's thus helpful to first review how it is that SQL addresses the question of secondary index access.

The short answer is that it doesn't present secondary index directly in the interface at all. In SQL all specification of row access is done in the WHERE clause. In RQL the most direct analog to WHERE is filter yet RQL also presents other ways to access a table based on the value of rows, namely get, between, and eventually a combination of order_by plus nth or slice. These latter ways of accessing a RQL table make use of the primary index to speed up the query while filter is guaranteed to be linear in the size of the table. In SQL these cases are handled by the optimizer. The clause WHERE id = 1 is identified in the query planning stage as an operation that can be assisted by an index and is automatically turned into a log(n) operation (like get in RQL).

There are a few problems with taking inspiration from this approach. The first is that we simply don't already have an optimizer and it would require a lot of infrastructure to be put in place to even do simple optimizations like this.

A more important objection though is philosophical. RQL doesn't really need an optimizer at this point because the programmer is able to ask for the optimal behavior directly. In RQL she doesn't have to trust that the optimizer will just do the right thing, she either gets the linear behavior of filter or the logarithmic behavior of get. This enhances the clarity of queries and allows for more direct performance tuning. Furthermore, to introduce such magical behavior now for secondary indices would make them feel extremely out of place and likely confuse users as the performance characteristics of otherwise identical queries would change significantly based on the prior creation of a secondary index. It's presently possible to look at a RQL query an immediately know what's it's doing. We shouldn't destroy that merely to replicate an established but bad design.

The basis of my proposal it to replicate the existing API we've developed for sublinear access of rows based on the primary index. Again, the three ways of leveraging the primary index are table.get(id), table.between(lower, upper) and in the future table.order_by(key) plus nth or slice. In a sense, r.table is how we reference the primary index for a table. We should similarly have a way to construct a reference to a secondary index which would then support a similar set of operations. I say similar, not identical, due to the slightly different semantics of primary and secondary indices.

Depending on whether secondary indexes exist in the same namespace as primary indexes (tables) or there is a secondary index namespace per table, one would construct a secondary index reference in one of the following ways:

# Secondary and primary indices exist in the same namespace
r.table(...) # primary index reference
r.sindex(...) # secondary index reference

# Secondary index exist in separate table based namespaces
r.table(...).sindex(...) # secondary index reference on table

I have a mild preference for the latter (per table sindex namespaces). While it results in more typing it resolves potential name conflicts (say you want each table to have a 'type' field with a secondary index based on it) and better preserves the relationship between secondary indices and parent tables.

Secondary index objects would support the following API:

sindex.get_set(key) => StreamSelection
sindex.between(lower, upper) => StreamSelection

# The use of `ordered` in place of `order_by` is
# actually a separate proposal and is only included
# here for completeness.
sindex.ordered() => StreamSelection

The main divergence from our primary index API is the use of get_set inplace of get. This is because key values in secondary indices are not guaranteed to be unique so we must be prepared to handle a stream of rows from the table with that key value.

There are some important open questions here that I would like specific feedback on. The first relates to that divergence between get and get_set. I would also like to propose implementing both get and get_set on both primary and secondary index references (i.e. make them both polymorphic). get_set on a primary index would return either the empty stream or a stream with one element. get on a secondary index would either return an error when there are more than one results in the result set or would return an arbitrary element from the set in that case. This would allow primary and secondary indices to be used interchangeably in many situations as well as simplifying use of primary indices even without consideration of the secondary sort. See below for a good example of how this is useful in eq_join.

The second is whether we want between to be polymorphic on both index types or have a separate name for each. Though in this case they both support the same output type their performance characteristics are slightly different (between on a secondary index adds a multiplicative log(n) to the runtime). Making between polymorphic thus slightly clouds the performance clarity of affected queries though increases flexibility (see the argument for get_set above). My slight preference is to make between polymorphic despite this drawback.

The third is whether secondary index objects also support the other operations of primary indices. These fall into two groups, the sequence operations that treat a table as a stream and the update operations that modify the underlying table. In both cases, these operations could transparently treat a secondary index object as synonymous with the underlying table. There is precedent for this if you consider such operations on a primary index reference as again bypassing the index for the underlying table, treating it as just a collection of rows on disk and not as an ordered, queryable set.

All three of these open questions are related for when taken together they imply interchangeability between primary and secondary index references. This turns out to be quite powerful and is perhaps the best argument for this proposal over the alternatives.

Consider the case of eq_join. Though no longer implemented this way, it may be implemented in the Python DSL as follows:

def eq_join(table1, attr, table2):
    table1.concatMap(
        lambda row1: table2.get(x[attr]).do(
            lambda row2: r.branch(row2 == None,
                [],
                [{'left':row1, 'right':row2}]
        )
    )

# What this would look like with `get_set`, ignoring secondary indices
def eq_join(table1, attr, table2):
    table1.concatMap(
        lambda row1: table2.get_set(x[attr]).map(
            lambda row2: {'left':row1, 'right':row2}
        )
    )

The first thing you notice with this example is just how much cleaner it looks with get_set instead of get. There is no need for an ugly branch on NULL because that case is handled neatly by the empty stream.

The second remarkable thing about this function is that it is completely agnostic to whether table1 and table2 are primary or secondary indices since they both support get_set with roughly comparable performance characteristics. This advantage will become even more apparent when we eventually support libraries of helpful RQL functions that, like eq_join, take index arguments that may be primary or secondary indices.

This, I think, preserves what's actually good about the SQL API, that once you've created a secondary index it's trivial to begin using it to speed up your queries because there is no separate interface for interacting with secondary indices, it just works exactly like primary indices do.

Activity

  1. jdoliner commented on Apr 4, 2013

    @jdoliner
    Contributor

    I have a few comments. First off I think the name can't work here, consider:

    table.index("foo") #create an index
    table.sindex("foo") #access an index

    Seems pretty confusing to me. So I think we're going to need to do something like table.index_by("foo").

    On a similar note I think the name get_set is bad. For 2 reasons the first is that what you're getting back isn't really a set in any standard sense of the word. The second is that it's possible it might cause confusion because set could be construed as a synonym for insert


    Comparing syntaxes:

    So in our current system the index you want to use is passed as an argument to the operation that will be using. For example:

    table.index_by("foo").get(1)
    # vs
    table.get(1, "foo")

    I think I could live with both of these syntaxes but I'd prefer the shorter one. Similarly with between we have:

    table.index_by("foo").between(1, 10)
    # vs
    table.between(1, 10, "foo")

    Again I don't see a huge increase in clarity that makes up for increased verbosity.


    My biggest objection to this proposal is that it seems to create a mental model which isn't as concise as it could be. And having cruft in the mental model is one of the worst things we can have since it will make it harder for people to truly grok ReQL. As far as I can tell people think of databases like this: there exist tables, tables can have 0 or more indexes which can be used to make certain operations more efficient. In SQL indexes are used implicitly while in ours they need to be explicitly specified but I think the mental model is mostly the same.
    I think the proposal in which the index is an argument to the operation that uses it matches up better with this mental model because it reinforces the idea that the index only has any use with respect to these operations. You can only reference an index when you're doing one of these operations which is great because that's the only time we can use one on the server side.
    With this proposal we have to answer the question: "What is this object table.index_by("foo")? It's a table object which when you do a get will use the secondary index which was specified. But you can't give a description of this object that doesn't hinge on how it affects later operations on it which I think is confusing.

  2. danielmewes commented on Apr 4, 2013

    @danielmewes
    Member

    I have to agree with @jdoliner . I would find it very strange to have different indexes on a table being presented as if they were different table objects. It is an interesting idea and certainly worth thinking about, but it would really need some getting used to.

    My way of thinking is certainly influenced heavily by how it works in SQL (seeing an index as an accelerator for operations), but I think that SQL is actually a good design in this respect.

    On the downside, there might be effects of using an index which go further than accelerating just a single operation. For example, if you use an index in SQL to perform a "between" operation, and then sort the result by the same field, the sorting in many database systems becomes a no-op, because the index already guarantees the correct order. Could something like this ever be the case in RethinkDB?
    If any such exist, the table().index().... semantics would represent such subtleties better I think.

    Also, I feel like the table().index() approach would make it more difficult to add an optimizer to RethinkDB in the future, while keeping a clean and consistent QL interface. But I might just not understand it well enough.

  3. jdoliner commented on Apr 4, 2013

    @jdoliner
    Contributor

    On the downside, there might be effects of using an index which go further than accelerating just a single operation. For example, if you use an index in SQL to perform a "between" operation, and then sort the result by the same field, the sorting in many database systems becomes a no-op, because the index already guarantees the correct order. Could something like this ever be the case in RethinkDB?

    I can't off the top of my head think of a case like this in RethinkDB because of its sharded nature it's much more efficient not to sort things unless we're specifically asked to. So order_by at this point is basically never a no-op. (Unless of course you did it twice in a row but we don't currently optimize that.) On the other hand I'm not sure I fully grasp what you mean by "something like this" what would be some other things in this category?

  4. danielmewes commented on Apr 4, 2013

    @danielmewes
    Member

    @jdoliner No, I cannot think of anything else. In general, I was thinking about semantic differences or different guarantees between table(...) and table(...).index(...), other than the fact that some operations have different performance characteristics. But it seems that none such exist in RethinkDB.

  5. wmrowan commented on Apr 4, 2013

    @wmrowan
    ContributorAuthor

    Having slept on it a bit, I'd like to update the proposal with a more well thought out set of names. Hopefully this will address some of Joe's concerns.

    # How we presently create, list, destroy, and reference tables
    db.table_create(name, options...)
    db.table_list()
    db.table_drop(name)
    db.table(name)
    
    # How we should create, list, destroy, and reference indices
    table.index_create(name, function)
    table.index_list()
    table.index_drop(name)
    table.index(name)
    
    # Reference the primary index. While essentially an identity operation
    # it allows the primary index to be treated as just another index
    table.index("primary")
    
    # Indices (including the primary one) support the following operations
    index.get(key) => null | SingleSelection
    index.get_all(key) => StreamSelection
    index.between(lower, upper) => StreamSelection
    # Part of a future proposal, included here for completeness
    index.ordered() => StreamSelection

    I agree that get_set was a bad name. I think that get_all is much better. Remember also, that whatever we do with secondary index support I'd like to add get_all to primary indices too.


    RethinkDB table references support three conceptually distinct sets of operations.

    One set treats a table as a set of rows on disk. These objects can be modified, added to, or removed from the table with update, replace, delete, and insert.

    Another treats a table as a Sequence of rows that can be manipulated with map, reduce, limit, etc.

    And yet another treats a table as a btree that can be queried in sublinear time with get and between, and which supports linear sorting with ordered. The index method on tables is how we refer to other indices defined on that table. These other indices are like separate views on the table that can also be queried in the same manner as the primary view but through distinctly constructed btrees thus offering different performance characteristics.

    The core reasoning behind this proposal is simply that secondary indices, themselves btrees that behave very similarly to the primary index, should be presented to the user in the same way that their primary index brethren are. RQL users already know how to leverage btree operations with get on a primary index. This understanding should translate directly to secondary index access.

    @danielmewes RQL already handles primary index access in a completely different fashion from SQL. An SQL WHERE clause may be accelerated by any index (including the primary one) that happens to be relevant to that query. RQL already requires the programer to explicitly make use of the primary index by calling get on the table rather than relying on the optimizer to speed up a filter operation. I actually see this as a feature, not a bug, for it makes the performance characteristics of queries much more transparent. It would be weird in RQL to require explicit use of the primary index while relying on magical optimizer behavior for access to secondary indices.

  6. mlucy commented on Apr 4, 2013

    @mlucy
    Member

    So, I have mixed feelings about this proposal, but overall I think I like it.

    The downsides:

    • It complicates out data model (we have to introduce a new index type).
    • It might not match users' mental models as well as just making all the retrieval functions variadic.

    The upsides:

    • We don't have to tack on this optional secondary index argument to everything that we want to work with secondary indices. (For example, instead of trying to shim a fourth argument into eq_join, people would just write tbl1.eq_join(:tbl1_attr, tbl2.index(:tbl2_index)).)
    • I think get and get_all is much better than just giving get a different return type for primary and secondary indices. (I'm extremely uncomfortable with get having multiple return types; that seems confusing to me.) The addition of get_all would also make the implementations of e.g. eq_join simpler, and would allows us to use the same expanded code for both primary and secondary indices in places where we implement high-level terms by expansion to lower-level terms.

    Even if we decide not to complicate our data model, I think we should still try to have both get and get_all.

  7. coffeemug commented on Apr 5, 2013

    @coffeemug
    Contributor

    I like get and get_all. I like index_create, index_drop, and index_list, coupled with static value sugar proposal in #595.

    As for the actual controversy, here's a thought experiment. Suppose we introduce an operation scanning_eq_join that does exactly the same thing as eq_join but for right table attributes that have no index. Do we want scanning_eq_join and eq_join to have the same interface? I claim that we do.

    To me the .index(...) proposal has all of the following disadvantages:

    • It introduces a new concept users have to learn
    • It's unfamiliar (coming from the SQL background, this will seem very off at first)
    • It's harder to do and think through for us (i.e. it introduces a new type we have to deal with, etc.)
    • It violates the less is more principle. That's cool, but I think for cases when we choose to do the "grander" thing, we need really strong evidence that the thing we're doing has overwhelmingly greater value. I don't believe we meet this standard of evidence here.
    • It breaks denotational semantics of ReQL. Right now ReQL can be treated as a program (hey db, just run the query as is) or a set of demands (hey db, here's the data I want, please figure out how to run it). Until we get an optimizer, we'll execute queries via the former method, but I'd like to keep the door open for the latter method. Adding things like .index() break that forever.

    I think we should follow less is more philosophy here. Just add an extra attribute everywhere that looks for an index name, and be done with it. This has all of the following advantages:

    • It's easy for us to implement
    • It's easy for users to think about
    • It's familiar
    • It's incremental as opposed to grand
    • It maintains the possibility of treating ReQL as a declarative program later
    • Everyone understands all implications

    (BTW, I think we should treat the primary key name as the name of the index, so one could do table.get_all(5, 'id') => [obj])

  8. neumino commented on Apr 5, 2013

    @neumino
    Member

    I tend to agree with @coffeemug. The .index() while not too hard to understand is just strange compared to what we can find in other databases.

    @jdoliner can we enforce that we don't have redundant values for secondary indexes? I've seen some people storing multiple "primary keys".
    If it's possible, we can have .get() for these secondary indexes.

    For get, get_all, index_create, index_drop, index_list, they sound quite good to me.

  9. jdoliner commented on Apr 6, 2013

    @jdoliner
    Contributor

    @neumino unfortunately preventing redundant values for secondary indexes is tough. We could maybe have that somewhere down the road but I can't say with certainty. I totally agree that it would be awesome to have it.

  10. wmrowan commented on Apr 8, 2013

    @wmrowan
    ContributorAuthor

    Having slept on it a bit more, I don't think we would need to add a new type. Since the secondary index object supports the same interface as a table it effectively is a table.

    The only question is, do the slightly divergent performance semantics of secondary indices warrant being called out in the type system? If not, then the only change in the API (apart from what we've already all agreed on) is:

    index :: Table, !STRING -> Table
    

    The index method returns the table as viewed through the given secondary index with table.index('secondary').index('primary') being an identity operation.

  11. al3xandru commented on Apr 9, 2013

    @al3xandru
    Contributor

    I've been sleeping on this for a while too mainly because there was something intriguing about it, but also something that I didn't like but couldn't tell.

    Finally the previous comment nailed it! It is promoting the notion of indexes to the level of tables that I don't like (if an index is just a table can I insert data directly?). Secondly, once indexes become such a strong notion in our db (and it would be the only one that I know of that makes indexes so visible to end users), it will be more difficult to go to the next step of having a query analyzer (supporting hints when needed).

    I'm 👍 with @jdoliner's initial proposal of providing indexes as an extra parameter to specific functions.

  12. jdoliner commented on Apr 9, 2013

    @jdoliner
    Contributor

    I think that trying to explain the idea to people that table.index('foo') is actually a table is really going to be too confusing to be workable. While I do appreciate the elegance of this notion I think we're going to wind up asking people to reorganize their mental models too much without providing enough of a benefit to make them feel like it was worth their while once they do.

  13. coffeemug commented on Apr 9, 2013

    @coffeemug
    Contributor

    After thinking about it some more, I think we should just add a secondary index name parameter to every function that needs it and call it a day.

  14. wmrowan commented on Apr 9, 2013

    @wmrowan
    ContributorAuthor

    OK. So to summarize on what I think we've agreed on thus far.

    table.index_create(name, function) => {'created':1, ...}
    table.index_drop(name) => {'dropped': 1, ...}
    table.index_list() => [...]
    
    table.get(key) => SingleSelection # unchanged, works only for primary index
    table.get_all(key[, index]) => StreamSelection
    table.between(lower, upper[, index]) => StreamSelection
    table.eq_join(other, key[, index]) => Stream
    
    # This has never used an index and I assume we're still punting for now.
    # Someday we'll have to figure out how this should look.
    table.order_by(attr[, attrs...]) => Stream

    So what are the remaining open questions?

    1. Should ordinary get also work on secondary indices?
      • error on multiple matches
      • return row with least primary key
      • return arbitrary row from result set
      • return random row from result set
    2. Should the index parameter be the last argument or should it be an optional argument?

    And I think that's it. Did I miss anything?

  15. mlucy commented on Apr 9, 2013

    @mlucy
    Member

    The current syntax for eq_join is table.eq_join(field_name, other_table). I think we should maybe extend it to table1.eq_join(field_name_or_index_for_table1, index_for_table2, table2) (which is similar to the eq_join signature in the old protobuf when we hardcoded id).

    As an aside, I really don't like putting the index on the end of all of these. It looks ugly and different from everything else:

    r.table('people').get_all('John')
    r.table('people').get_all('John', :name)

    Imagine if we handled the problem of an optional database that way:

    r.table('people')
    r.table('people', 'test') # instead of r.db('test').table('people')

    I think both of these look better:

    r.table('people').index(:name).get_all('John')
    r.table('people').get_all(:name, 'John') # although this one might be confusing
  16. 30 remaining items

  17. coffeemug commented on Apr 10, 2013

    @coffeemug
    Contributor

    There's no guarantee they don't also have a sindex named 'id' and I feel like it would be a pain to prevent it.

    I'd strongly prefer to reject creating secondary indexes that have the same name as the primary key. That makes everything a lot tighter. We can do it later if it's hard, but I think we should design with that in mind.

  18. coffeemug commented on Apr 10, 2013

    @coffeemug
    Contributor

    Status update: I can't get this in by tonight (I'm out of juice). I'm actually thinking this should be part of sprint-3 instead (I can write up reql tests very early, but then it'll take some time to get the implementation up-to-speed).

  19. coffeemug commented on Apr 23, 2013

    @coffeemug
    Contributor

    Status update: I plan to finish all my administrative/PM work today. I'll do this next since other people are blocking on me for this.

  20. coffeemug commented on Apr 24, 2013

    @coffeemug
    Contributor

    Reassigning to @mlucy who kindly agreed to encode the API in polyglot tests.

  21. ghost assigned on Apr 24, 2013
  22. coffeemug commented on Apr 26, 2013

    @coffeemug
    Contributor

    FYI, @607 depends on this.

  23. mlucy commented on Apr 26, 2013

    @mlucy
    Member

    I have a review for this, sans between, up in code-review 450 by @coffeemug and @jdoliner . I'd like to pair-program the between change with @Tryneus if possible, since it's mildly nontrivial and I think he implemented the sindex range gets.

  24. coffeemug commented on Apr 30, 2013

    @coffeemug
    Contributor

    @wmrowan -- is there an implementation for py and js drivers yet?

  25. wmrowan commented on Apr 30, 2013

    @wmrowan
    ContributorAuthor

    The Python driver interface (except for between which @mlucy is still working on) is is in branch 602_sindex_api as of 8c6fe75. I'm working on the JS driver now.

  26. coffeemug commented on Apr 30, 2013

    @coffeemug
    Contributor

    Cool thnx.

  27. wmrowan commented on Apr 30, 2013

    @wmrowan
    ContributorAuthor

    between is now done for both Python and JavaScript.

  28. mlucy commented on May 1, 2013

    @mlucy
    Member

    Could you add it to review 450?

  29. coffeemug commented on May 1, 2013

    @coffeemug
    Contributor

    Moving to 1.5-sprint-4 since we're technically past due.

  30. mlucy commented on May 2, 2013

    @mlucy
    Member

    This is in next.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions