Repository navigation
Description
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 tableI 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() => StreamSelectionThe 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
jdoliner commentedon Apr 4, 2013
I have a few comments. First off I think the name can't work here, consider:
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_setis 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 becausesetcould be construed as a synonym forinsertComparing 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:
I think I could live with both of these syntaxes but I'd prefer the shorter one. Similarly with
betweenwe have: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 agetwill 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.danielmewes commentedon Apr 4, 2013
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.
jdoliner commentedon Apr 4, 2013
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_byat 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?danielmewes commentedon Apr 4, 2013
@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.
wmrowan commentedon Apr 4, 2013
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.
I agree that
get_setwas a bad name. I think thatget_allis much better. Remember also, that whatever we do with secondary index support I'd like to addget_allto 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, andinsert.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
getandbetween, and which supports linear sorting withordered. Theindexmethod 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
geton 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
WHEREclause 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 callinggeton the table rather than relying on the optimizer to speed up afilteroperation. 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.mlucy commentedon Apr 4, 2013
So, I have mixed feelings about this proposal, but overall I think I like it.
The downsides:
indextype).The upsides:
eq_join, people would just writetbl1.eq_join(:tbl1_attr, tbl2.index(:tbl2_index)).)getandget_allis much better than just givinggeta different return type for primary and secondary indices. (I'm extremely uncomfortable withgethaving multiple return types; that seems confusing to me.) The addition ofget_allwould also make the implementations of e.g.eq_joinsimpler, 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
getandget_all.coffeemug commentedon Apr 5, 2013
I like
getandget_all. I likeindex_create,index_drop, andindex_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_jointhat does exactly the same thing aseq_joinbut for right table attributes that have no index. Do we wantscanning_eq_joinandeq_jointo have the same interface? I claim that we do.To me the
.index(...)proposal has all of the following disadvantages:.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:
(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])neumino commentedon Apr 5, 2013
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.jdoliner commentedon Apr 6, 2013
@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.
wmrowan commentedon Apr 8, 2013
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:
The index method returns the table as viewed through the given secondary index with
table.index('secondary').index('primary')being an identity operation.al3xandru commentedon Apr 9, 2013
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.
jdoliner commentedon Apr 9, 2013
I think that trying to explain the idea to people that
table.index('foo')is actually atableis 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.coffeemug commentedon Apr 9, 2013
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.
wmrowan commentedon Apr 9, 2013
OK. So to summarize on what I think we've agreed on thus far.
So what are the remaining open questions?
getalso work on secondary indices?And I think that's it. Did I miss anything?
mlucy commentedon Apr 9, 2013
The current syntax for
eq_joinistable.eq_join(field_name, other_table). I think we should maybe extend it totable1.eq_join(field_name_or_index_for_table1, index_for_table2, table2)(which is similar to theeq_joinsignature in the old protobuf when we hardcodedid).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:
Imagine if we handled the problem of an optional database that way:
I think both of these look better:
30 remaining items
coffeemug commentedon Apr 10, 2013
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.
coffeemug commentedon Apr 10, 2013
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).
coffeemug commentedon Apr 23, 2013
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.
coffeemug commentedon Apr 24, 2013
Reassigning to @mlucy who kindly agreed to encode the API in polyglot tests.
coffeemug commentedon Apr 26, 2013
FYI, @607 depends on this.
mlucy commentedon Apr 26, 2013
I have a review for this, sans
between, up in code-review 450 by @coffeemug and @jdoliner . I'd like to pair-program thebetweenchange with @Tryneus if possible, since it's mildly nontrivial and I think he implemented the sindex range gets.coffeemug commentedon Apr 30, 2013
@wmrowan -- is there an implementation for py and js drivers yet?
wmrowan commentedon Apr 30, 2013
The Python driver interface (except for
betweenwhich @mlucy is still working on) is is in branch602_sindex_apias of 8c6fe75. I'm working on the JS driver now.coffeemug commentedon Apr 30, 2013
Cool thnx.
wmrowan commentedon Apr 30, 2013
betweenis now done for both Python and JavaScript.mlucy commentedon May 1, 2013
Could you add it to review 450?
coffeemug commentedon May 1, 2013
Moving to 1.5-sprint-4 since we're technically past due.
mlucy commentedon May 2, 2013
This is in next.