Oren Eini

CEO of RavenDB

a NoSQL Open Source Document Database

Get in touch with me:

oren@ravendb.net +972 52-548-6969

Posts: 7,567
|
Comments: 51,184
Privacy Policy · Terms
filter by tags archive
time to read 3 min | 588 words

Replication is kinda important to RavenDB. It is the building block for high availability and transparent failover, it is how we do scale out in many cases. I think that you won’t be surprised to hear that we have done a lot of work around that area as well.

Some of that was internal, just optimizing how we are doing things. One such case was optimizing the addition of a new node to a cluster. Previously, that would mean that are carefully laid out plans for how to allocate memory for replication would have to be disrupted, and a lot of the time, we would need to do extra work to server both existing and new replication destinations. In RavenDB 3.0, we have specifically addressed this, and now we can do much better for this scenario, or even the more common one when you have one slower node.

But for the most part, a lot of the changes that has been made were done to make it easier to work with replication. The following screen shot shows a lot of the new features all at once:

image

Now, instead of defining the failover replication behavior on a client side (which meant that different clients could have different failover behavior), we define this behavior on the server side (note that server side behavior will override the client side behavior). This means that your admin can change the cluster from master/slave to the multi master topology and you won’t have to change your code, it will be picked by the clients automatically.

Conflict resolution has also became easier. RavenDB now ships with three automatic conflict resolvers (prefer local, prefer remote, prefer latest). Another one is planned for post 3.0, which will allow you to write a server side conflict resolution script to handle custom logic.  Of course, the usual conflict resolutions (client side listener, server side trigger) are still there and humming along quite nicely.

Below the replication destinations, you can see the server hilo prefix. This is a feature we had in RavenDB for several years, but it has never been really utilized. This allows multiple servers to accept new documents concurrently without having to fear conflicting ids.

Another feature that we added was better tracking of the health of the entire cluster. One part of that is the ability to visualize the topology:

image

From the client side of things, the behavior of the client in the presence of failure has been greatly improved. We do automatic failover, of course, but now we do the health checks of the down servers as a background task. That means that after the initial “server is down” shock, we immediately switch over to the secondary nodes, and we’ll handle the primary recovering and switch back to it within a few seconds. That means that we won’t have the complex backoff strategy or the hit that this took when every N request.

Another change we made to the client side was the ability to explicitly define the failover configuration on the client. That was a feature that people requested, mostly to handle the “we start the first time and the server is down” scenario. Not an hugely common situation, but it completes the entire feature set quite nicely.

time to read 4 min | 611 words

RavenDB is an ACID database for documents, and it is a BASE database for queries. That design principle has serve us very well since the start, because it allow us to modify the way we are handling things internally without violating the promises we give to the user.  In particular, the ability to hand out potentially stale information has been crucial for a lot of performance optimizations in RavenDB.

That said, while is has been a core feature of RavenDB from the start, I haven’t found a single user who had a hankering for longer staleness latency. That is a long way to say that we managed to reduce further the number of times RavenDB will return query results marked as stale. We have talked about some of this in the previous posts, with regards to better batching and optimization in the indexing process itself, but we already talked about this.

In RavenDB 3.0, we are using smarter algorithm to detect if an index has potentially changed, in particular, we can detect if the index isn’t covering any of the changed documents that it hasn’t had a chance to index yet. If we know that no document yet to be indexed is going to be indexed by this index, we can short circuit indexing and declare the index as non stale. In practice, this should resolve a common misconception “I changed one document, all indexes became stale” by having a better match between what the user thinks is going on and the externally observed behavior.

Your applications would be a little faster, but that should be the sole difference from your point of view.

Another change that does require you to take active action is nested transformers. The idea is that transformers often encompass some piece of business logic related to how to pull an entity / entities for a particular task. It would be nice not to have to duplicate this logic (and maintain it over time). With RavenDB 3.0, you can now nest transformers and have one transformer call another to do some part of the work.

Here is how this looks:

//ProductsTransformer
TransformResults = products =>
from doc in products
select new
{
Name = doc.Name.Reverse()
};

// another transformer
TransformResults = products =>
from doc in products
select new
{
Product = doc,
Transformed = TransformWith("ProductTransformer", doc)
};

The 2nd transformer calls to the ProductsTransformer by name, allow it to run its own processing (and potentially call yet another transformer, etc). Note that a transformer cannot recurse either directly on indirectly. In other words ,you cannot call yourself, or another transformer that has called you.

There has been a lot of other changes, of course, but a lot of them are too small to merit such a mention. Better support for querying unsigned integers is hardly earth shattering. But there has been a lot of those kind of changes. It means that you’ll have a smoother experience overall.

Next post, replication Smile.

time to read 6 min | 1113 words

concept-18290_640We talked a lot about the changes we made for indexing, now let us talk about the kind of changes we are talking about from the query side of things. More precisely, this is when we start asking questions about our queries.

Timing queries. While it is rare that we have slow queries in RavenDB, it does happen, and when it does, we treat it very seriously. However, in the last few cases that we have seen, the actual problem wasn’t with RavenDB, it was with sending the data back to the client when we had a large result set and large number of documents.

In RavenDB 3.0, we have added the ability to get detailed statistics about what is the cost of the query in every stage of the pipeline.

RavenQueryStatistics stats;
var users = session.Query<Order>("Orders/Totals")
    .Statistics(out stats)
    .Customize(x => x.ShowTimings())
    .Where(x=>x.Company == "companies/11" || x.Employee == "employees/2")
    .ToList();

foreach (var kvp in stats.TimingsInMilliseconds)
{
    Console.WriteLine(kvp.Key + ": " + kvp.Value);
}

Console.WriteLine("Total: " + stats.DurationMilliseconds);

We can now ask RavenDB to explain us its reasoning when doing so:

  • Lucene search: 10
  • Loading documents: 2
  • Transforming results: 0
  • Total: 21

As you can see, the total time for this query is 21 ms, and we have 12 ms accounted for in the actual search time. The rest is network traffic.  This can help you diagnose more easily where the problem is, and hence, how to solve it.

Query timeout and cancellation. As I mentioned, we don’t really have long queries in RavenDB very often. But that is actually is something that happens, and we need a way to deal with that. RavenDB now places a timeout on the amount of time a query gets to run (including querying Lucene, loading documents or transforming the results). A query that doesn’t complete in time will be cancelled, and an error will be returned to the user.

You can also view the currently executing queries and kill a long running query (if you have specified a high timeout, for example).

Explaining queries. Sometimes it is easy to understand why RavenDB has decided to give you documents in a certain order. You asked them sorted by date, and you get them sorted by date. But when you are talking about complex queries, that is much harder. RavenDB will sort the results by default based on relevancy, and that can sometimes be a bit puzzling to understand.

Here is how we can do this:

session.Advanced.DocumentQuery<Order>("Orders/Totals")
                    .Statistics(out stats)
                    .WhereEquals("Company", "companies/11")
                    .WhereEquals("Employee", "employees/3")
                    .ExplainScores()
                    .ToList();

var explanation = stats.ScoreExplantaions["orders/759"];

The result of this would be something that looks like this:

0.6807194 = (MATCH) product of:
  1.361439 = (MATCH) sum of:
    1.361439 = (MATCH) weight(Employee:employees/3 in 469), product of:
      0.4744689 = queryWeight(Employee:employees/3), product of:
        2.869395 = idf(docFreq=127, maxDocs=830)
        0.165355 = queryNorm
      2.869395 = (MATCH) fieldWeight(Employee:employees/3 in 469), product of:
        1 = tf(termFreq(Employee:employees/3)=1)
        2.869395 = idf(docFreq=127, maxDocs=830)
        1 = fieldNorm(field=Employee, doc=469)
  0.5 = coord(1/2)

And if we were to ask for the explanation for orders/237, we will get:

6.047595 = (MATCH) sum of:
  4.686156 = (MATCH) weight(Company:companies/11 in 236), product of:
    0.8802723 = queryWeight(Company:companies/11), product of:
      5.32353 = idf(docFreq=10, maxDocs=830)
      0.165355 = queryNorm
    5.32353 = (MATCH) fieldWeight(Company:companies/11 in 236), product of:
      1 = tf(termFreq(Company:companies/11)=1)
      5.32353 = idf(docFreq=10, maxDocs=830)
      1 = fieldNorm(field=Company, doc=236)
  1.361439 = (MATCH) weight(Employee:employees/3 in 236), product of:
    0.4744689 = queryWeight(Employee:employees/3), product of:
      2.869395 = idf(docFreq=127, maxDocs=830)
      0.165355 = queryNorm
    2.869395 = (MATCH) fieldWeight(Employee:employees/3 in 236), product of:
      1 = tf(termFreq(Employee:employees/3)=1)
      2.869395 = idf(docFreq=127, maxDocs=830)
      1 = fieldNorm(field=Employee, doc=236)

In other words, we can see that orders/237 is ranked much higher than orders/759. That is because is matched both clauses of the query. And a match on Company is a much stronger indication for relevancy because Companies/11 appears only in 10 documents out out 830, while Employees/3 appears in 127 out of 830.

For details about this format, see this presentation, it actually talks about Solr here, but this data comes from Lucene, so it applies to both.

That is it about queries diagnostics, next, we’ll deal with transformers and another important optimization, the staleness reduction system.

time to read 7 min | 1394 words

chess-345904_640

We talked previously about the kind of improvements we have in RavenDB 3.0 for the indexing backend. In this post, I want to go over a few features that are much more visible.

Attachment indexing. This is a feature that I am not so hot about, mostly because we want to move all attachment usages to RavenFS. But in the meantime, you can reference the contents of an attachment during index. That can let you do things like store large text data in an attachment, but still make it available for the indexes. That said, there is no tracking of the attachment, so if it change, the document that referred to it won’t be re-indexed as well. But for the common case where both the attachments and the documents are always changed together, that can be a pretty nice thing to have.

Optimized new index creation. In RavenDB 2.5, creating a new index would force us to go over all of the documents in the database, not just the documents that we have in that collection. In many cases, that surprised users, because they expected there to be some sort of physical separation between the collections. In RavenDB 3.0, we changed things so creating a new index on a small collection (by default, less than 131,072 items) will be able to only touch the documents that belong to the collections being covered by that index. This alone represent a pretty significant change in the way we are processing indexes.

In practice, this means that creating a new index on a small index would complete much more rapidly. For example, I reset an index on a production instance, it covers about 7,583 documents our of 19,191. RavenDB was able to index that in just 690 ms, out of about 3 seconds overall that took for the index reset to take place.

What about the cases where we have new indexes on large collections? At this point, in 2.5, we would do round robin indexing between the new index and the existing ones. The problem was that 2.5 was biased toward the new index. That meant that it was busy indexing the new stuff, while the existing indexes (which you are actually using) took longer to run. Another problem was that in 2.5 creating a new index would effectively poison a lot of performance heuristics.  Those were built for the assumptions of all indexes running pretty much in tandem. And when we have one or more that weren’t doing so… well, that caused things to be more expensive.

In 3.0, we have changed how this works. We’ll have separate performance optimization pipelines for each group of indexes based on its rough indexing position. That lets us take advantage of batching many indexes together. We are also not going to try to interleave the indexes (running first the new index and then the existing ones). Instead, we’ll be running all of them in parallel, to reduce stalls and to increase the speed in which everything comes up to speed.

This is using our scheduling engine to ensure that we aren’t actually overloading the machine with computation work (concurrent indexing) or memory (number of items to index at once). I’ve very proud in what we have done here, and even though this is actually a backend feature, it is too important to get lost in the minutia of all the other backend indexing changes we talked about in my previous post.

Explicit Cartesian/fanout indexing. A Cartesian index (we usually call them fanout indexes) is an index that output multiple index entries per each document. Here is an example of such an index:

from postComment in docs.PostComments
from comment in postComment.Comments
where comment.IsSpam == false
select new {
    CreatedAt = comment.CreatedAt,
    CommentId = comment.Id,
    PostCommentsId = postComment.__document_id,
    PostId = postComment.Post.Id,
    PostPublishAt = postComment.Post.PublishAt
}

For a large post, with a lot of comments, we are going to get an entry per comment. That means that a single document can generate hundreds of index entries.  Now, in this case, that is actually what I want, so that is fine.

But there is a problem here. RavenDB has no way of knowing upfront how many index entries a document will generate, that means that it is very hard to allocate the appropriate amount of memory reserves for this, and it is possible to get into situations where we simply run out of memory. In RavenDB 3.0, we have added explicit instructions for this. An index has a budget, by default, each document is allowed to output up to 15 entries. If it tries to output more than 15 entries, that document indexing is aborted, and it won’t be indexed by this index.

You can override this option either globally, or on an index by index basis, to increase the number of index entries per document that are allowed for an index (and old indexes will have a limit of 16,384 items, to avoid breaking existing indexes).

The reason that this is done is so either you didn’t specify a value, in which case we are limited to the default 15 index entries per document, or you did specify what you believe is a maximum number of index entries outputted per document, in which case we can take advantage of that when doing capacity planning for memory during indexing.

Simpler auto indexes. This feature is closely related to the previous one. Let us say that we want to find all users that have an admin role and has an unexpired credit card. We do that using the following query:

var q = from u in session.Query<User>()
        where u.Roles.Any(x=>x.Name == "Admin") && u.CreditCards.Any(x=>x.Expired == false)
        select u;

In RavenDB 2.5, we would generate the following index to answer this query:

from doc in docs.Users
from docCreditCardsItem in ((IEnumerable<dynamic>)doc.CreditCards).DefaultIfEmpty()
from docRolesItem in ((IEnumerable<dynamic>)doc.Roles).DefaultIfEmpty()
select new {
    CreditCards_Expired = docCreditCardsItem.Expired,
    Roles_Name = docRolesItem.Name
}

And in RavenDB 3.0 we generate this:

from doc in docs.Users
select new {
    CreditCards_Expired = (
        from docCreditCardsItem in ((IEnumerable<dynamic>)doc.CreditCards).DefaultIfEmpty()
        select docCreditCardsItem.Expired).ToArray(),
    Roles_Name = (
        from docRolesItem in ((IEnumerable<dynamic>)doc.Roles).DefaultIfEmpty()
        select docRolesItem.Name).ToArray()
}

Note the difference between the two. The 2.5 would generate multiple index entries per document, while RavenDB 3.0 generate just one. What is worse is that 2.5 would generate a Cartesian product, so the number of index entries outputted in 2.5 would be the number of roles for a user times the number of credit cards they have.  In RavenDB 3.0, we have just one entry, and the overall cost is much reduced. It was a big change, but I think it was well worth it, considering the alternative.

In my next post, I’ll talk about the other side of indexing, queries. Hang on, we still have a lot to go through.

time to read 8 min | 1401 words

image

RavenDB indexes are one of the things that make is more than a simple key/value store. They are incredibly important for us. And like many other pieces in 3.0, they have had a lot of work done, and now they are sparkling & shiny. In this post I’m going to talk about a lot of the backend changes that were made to indexing, making them faster, more reliable and better all around. In the next post, I’ll discuss the actual user visible features we added.

Indexing to memory. Time and time again we have seen that actually hitting the disk is a good way of saying “Sayonara, perf”. In 2.5, we introduced the notion of building new indexes in RAM only, to speed up the I/O for new index creation. With 3.0, we have taken this further and indexes no longer go to disk as often. Instead, we index to an in memory buffer, and only write to disk once we hit a size/time/work limit.

At that point, we’ll flush those indexes to disk, and continue to buffer in memory. The idea is to reduce the amount of disk I/O that we do, as well as batch it to reduce the amount of time we spend hitting the disk.  Under high load, this can dramatically improve performance, because we are I/O bound so much. In fact, for the common load spike scenario, we never have to hit the disk for indexing at all.

Aysnc index deletion. Indexes in RavenDB are composed of the actual indexed data, as well as the relevant metadata about the index. Usually, metadata is much smaller than the actual data. But in this case, an index metadata in the case of a map/reduce index include all of the intermediary steps in the process, so we can do incremental map/reduce. If you use LoadDocument, we need to maintain the documents references, and on large databases, that can take a lot of space. As a result of that, index deletion could take a long time in RavenDB 2.5.

With RavenDB 3.0, we are now doing async index deletions, so you can delete the index, which does a very short operation to free up the index name, but do the actual work to cleanup after the index in the background. And yes, you can restart the database midway through, and it will resume the async index deletion behavior. The immediate behavior is that it is much easier to manage indexes, because you delete a big index and not have to wait for this to continue. This most commonly showed up when updating an index definition.

Index ids instead of names. Because we had to break the 1:1 association between index and its name, we moved to an internal representation of indexes using numeric ids. That was pretty much forced on us because we had to distinguish between the old index Users/Search (who is now in the process of being deleted) and the new Users/Search index (who is now in the process of being indexed).

A happy side effect of that was that we actually has a more efficient internal structure for working with indexes in general. That speeds up writes and reads and reduce the overall disk space that is used.

Interleaves indexing & task executions. RavenDB uses the term task to refer to cleanup jobs (mostly) that run on the indexes. For example, removing deleted index entries, or re-indexing referencing documents when the referenced document has changed. In 2.5, it was possible to get a lot of tasks in the queue, which would stall indexing. For example, mass deletes were one common scenario were the task queue would be full and take a bit to drain. In RavenDB 3.0 we have changed things so a big task queue won’t impact indexing to that extent. Instead, we can interleave indexing and task execution so we won’t stall the indexing process.

Large documents indexing. RavenDB doesn’t place arbitrary limits on the size of documents. That is great as a user, but it places a whole set of challenges for RavenDB when we need to index. Assume that we want to introduce a new index of a relatively large collection of documents. We will start indexing the collection, realize that there is a lot to index, so we’ll grow the number of items to be indexed in each batch. The problem is that is is pretty common that as the system grows, so does the documents. So a lot of the documents that were updated later on would be bigger than those we had initially. That can get to a point where we are trying to fetch a batch size of 128K documents, but each of them is 250Kb in size. That requires us to load 31 GB of documents to index in a single batch.

That might take a while, even if we are talking just about reading them from disk, leaving aside the cost in memory. This was worse because in many cases, when having so much data, the users would usually go for the compression bundle. So when RavenDB tried to figure out what is the size of the documents (by checking its on disk size), it would get the compressed size. Hilarity did not ensue as a result, I tell you that. In 3.0, we are better prepared to handle such scenarios, and we know to count the size of the document in memory, as well as being more proactive about limiting the amount of memory we’ll use per batch.

I/O bounded batching. A core scenario for RavenDB is running on the cloud platforms. We have customers running us on anything from i2.8xlarge EC2 instances (32 cores, 244GB RAM, 8 x 800 GB SSD drives) to A0 Azure instances (shared CPU, 768 MB RAM, let us not talk about the disks, lest I cry). We actually got customers complaints about “Why isn’t RavenDB using all of the resources available to it”, because we could handle the load in about 1/4 of the resources that the machine in question had available. Their capacity calculations were based on another database product, and RavenDB works very differently, so while they had no performance complaints, there were kinda upset that we weren’t using more CPU/RAM – they paid for those, so we should use them.

Funny as that might seem, the other side is not much better. The low end cloud machines are slow, and starved of just about any resource that you can name. In particular, I/O rates for the low end cloud machines are pretty much abysmal. If you created a new index on an existing database in one of those machine, it would turn out that a lot of what you did was just wait for I/O. The problem would actually grow worse over time. We were loading a small batch (took half a second to load from disk) and indexing it. Then we loaded another batch, and another, etc. As we realized that we have a lot to go through, we increased the batch size. But the time we would spend waiting for disk would grow higher and higher.  From the admin perspective, it would appears as if we were hanging, and not actually doing any indexing.

In RavenDB 3.0, we are not bounding the I/O costs, so we’ll try to load a batch for a while, but if we can’t get enough in a reasonable time frame, we’ll just give you what we already have so far, let you index that, and continue the I/O operation in a background thread. The idea is that by the time you are done indexing, you’ve another batch of documents available for you. Combined with the batch index writes, that gave us a hell of a perceived performance boost (oh, it is indexing all the time, and I can see that it is doing a lot of I/O and CPU, so everything is good) and real actual gains (we were able to better parallelize the load process this way).

 

Summary – pretty much all of those changes are not something that you’ll really see. There are all engine changes that happen behind the scene. But all of them are going to work together to end up giving you a smoother, faster and overall better experience.

time to read 5 min | 940 words

I’m not sure that there is a better word to describe it. We have a sign in the office, 3 feet by 6 feet that says: Reduce Friction. And that is something that we tried very hard to do.

Under simplicity we aggregate everything that might aggravate you, and what we did to reduce that.

That include things like reducing the number of files and assemblies we ship. Compare the 2.5 output:

image

To the 3.0 output:

image

We did that by removing a lot of dependencies that we could do without, and internalizing a lot of the other stuff.

We went over the command line interface of the tooling we use and upgraded that. For example, restoring via the command line is now split into a restoring a system database (offline operation for the entire server) or restoring a regular database (the server is fully online, and other databases can run during this time).

In secret and without telling anyone, we have also doubled the amount of parallel work that RavenDB can do. Previously, if you purchased a standard license, you were limited to 6 concurrent index tasks, for example. In RavenDB 3.0, the standard license still has 6 cores capacity, but it will allow up to 12 concurrent index tasks. If you have a 32 cores Enterprise license, that would mean 64 concurrent indexing tasks, and you can follow the logic from there, I asuume.

We have also dropped the Raven.Client.Embedded assembly. It isn’t necessary. The full functionality is still available, of course, it was just moved to Raven.Database assembly. That reduce the amount of dlls that you have to work with and manage.

You probably don’t care much, but we have done a lot of refactoring on the internals of RavenDB. The DocumentDatabase class (the core functionality in RavenDB) was broken up into many separate classes, and on the client side, we have done much the same to the DocumentStore class. We have also combined several listeners together, so now you don’t have to deal with Extended Conversion Listeners.

In terms of storage, obviously Voron gives us a huge boost, and it is designed to be a zero admin system that self optimize. But we changed things on top of that as well. Previously, we were storing the data as BSON on disk. That decision had a lot to do with serialization costs and the size on disk. However, that created issues when we had to deal with the storage at a low level. So now RavenDB stores the data in text JSON format all the way through. And yes, it will seamlessly convert from BSON to JSON when you update documents, you don’t have to do anything to get it working. We run extensive performance testing here, and it turned out that we were able to reduce the cost of writing by moving to a textual format.

Another small annoyance with RavenDB was the use of in memory databases. Those are usually used for testing, but we also have a number of clients that use those for production data, usually as a high throughput first responder, with replication to / from backend systems to ensure durability. Previously, you had to manually tell RavenDB that it shouldn’t tear down those database when they went idle. Now we won’t tear down an in memory database even if it didn’t do anything for a long while.

Another common issues was people adding / removing bundles on the fly. This isn’t supported, and it can cause issues because it usually works, but not always. We made it so the process for doing that is a bit more involved, and require an actual acknowledgment that you are doing something that might be unsafe.

Users sometimes have proxies / man in the middle service that manipulate the HTTP headers. A common example of that is New Relic. That can cause problems sometimes, since RavenDB use HTTP headers to pass the document metadata, that caused issues. By now, we have pretty much filtered out all the common stuff, but since that always required us to make a new release, that had a prohibitive cost of the users. Instead, we now allow you to customize the list of headers that the server will ignore on the fly.

We did a lot for indexes in 3.0, but one of the changes is both simple and meaningful. We gave you the ability to ask if my current index definition matches the one on the server? That is important during deployments, because you can check if an index is up to date or not, and then decide if you need to do an online index rebuild, or schedule this for a later time, with less load, or just move on because everything is the same.

In RavenDB 3.0, we have deprecated the attachments, they still work (but will be removed in the next major release), but you are expected to use RavenFS for binary storage. RavenDB now comes with a migration tool to move all attachments from a RavenDB database to a RavenFS file system.

As I said, those are small things, none of them would rise to the level of major feature on its own. In aggregate (and I mentioned just the top from a very big list) they represent a significant reduction in the amount of friction that you have to deal with when using RavenDB.

time to read 6 min | 1175 words

RavenDB has always been accessible from other platforms. We have users using RavenDB from Python and Node.JS, we also have users using Ruby & PHP, although there isn’t a publicly available resource for that.

With RaenDB 3.0, we release an official Java Client API for RavenDB. Using it is pretty simple if you are familiar with the RavenDB API or the Hibernate API.

We start by creating the document store:

IDocumentStore store = new DocumentStore(ravenDbUrl, "todo-db");
store.initialize();
store.executeIndex(new TodoByTitleIndex());

Note that we have an compiled index as well here, which looks like this:

public class TodoByTitleIndex extends AbstractIndexCreationTask {

    public TodoByTitleIndex() {
        map = "from t in docs.todos select new { t.Title, t.CreationDate } ";
        QTodo t = QTodo.todo;
        index(t.title, FieldIndexing.ANALYZED);
    }
}

Since Java doesn’t have Linq, we use the Querydsl to handle that. The index syntax is still Linq on the server side, though.

That is enough about setup, let us see how we can actually work with this. Here is us doing a search:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    ServletContext context = request.getSession().getServletContext();
    IDocumentStore store = (IDocumentStore) context.getAttribute(ContextManager.DOCUMENT_STORE);

    String searchText = request.getParameter("search");

    try (IDocumentSession session = store.openSession()) {
        QTodo t = QTodo.todo;

        IRavenQueryable<Todo> query = session.query(Todo.class, TodoByTitleIndex.class)
            .orderBy(t.creationDate.asc());

        if (StringUtils.isNotBlank(searchText)) {
            query = query.where(t.title.eq(searchText));
        }

        List<Todo> todosList = query.toList();

        response.getWriter().write(RavenJArray.fromObject(todosList).toString());
        response.getWriter().close();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Basically, we get the store from the context, and then open a session. You can see the fluent query API, and how we work with sessions.

A more interesting example, albeit simpler, is how we write:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
    IOException {
    ServletContext context = request.getSession().getServletContext();
    IDocumentStore store = (IDocumentStore) context.getAttribute(ContextManager.DOCUMENT_STORE);

    try (IDocumentSession session = store.openSession()) {
        Todo todo = new Todo(request.getParameter("title"));
        session.store(todo);
        session.saveChanges();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

This API should be instantly familiar for any RavenDB or Hibernate users. As for the actual entity definition, here it goes:

@QueryEntity
public class Todo {

    private Boolean completed;
    private Date creationDate;
    private Integer id;
    private String title;

    public Todo() {
        super();
    }

    public Todo(final String title) {
        super();
        this.title = title;
        this.creationDate = new Date(System.currentTimeMillis());
    }

    public Boolean getCompleted() {
        return completed;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public Integer getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public void setCompleted(Boolean completed) {
        this.completed = completed;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return "Todo [title=" + title + ", completed =" + completed + ", creationDate=" + creationDate + ", id=" + id
            + "]";
    }
}
Except for the @QueryEntity annotation, it is a plain old Java class.
 
And of course, I’m using the term Java Client API, but this is actually available for any JVM language. Including Groovy, Scala and Clojure*.
 
* There is actually a dedicated RavenDB client for Clojure, written by Mark Woodhall.
time to read 1 min | 132 words

It is coming, and soon Smile.

 

I’m going to talk about what is new in RavenDB 3.0 (like the posts you have seen so far, a lot has changed). Manuel will present a case study of building high scale systems, then Michael will give you a guided tour through the RavenDB internal.

After lunch, we’ve Mauro talking about indexes and transformers, then I’m going to talk about the additional database types that are coming to RavenDB, and finally Judah is going to show how RavenDB speeds up your development time by a factor or two.

You can register to that here.

time to read 6 min | 1058 words

While most of the time, when a user is working with RavenDB, they do so via the browser, developers spend most of their time in code, and when working with RavenDB, that means working with the RavenDB Client API. We have spent quite a bit of time on that as well, as you can imagine. Here are a few of the highlights.

Fully async, all the way through. Communication with RavenDB is done to a remote server, which means that a lot of time is spent just doing I/O. Recognizing this, we are now taking full advantage of the async API available to us and the entirety of RavenDB 3.0 Client API is async. Previously, we had an async and sync version of the stack, which cause compatibility issues, some stuff worked for sync and not for async, or vice versa. With 3.0, we now has a single code path, and it is all async. For the sync API, we are just wrapping the async API. That gives us a single code path, and a fully async I/O throughout, unless you chose to use the sync API, at which point we’ll wait, per your request.

Lazy async is fully supported now. As part of the fully async part, we now have support for lazy operations on the full async session.

Lazy timings. As long as we are speaking lazily, a frequent request was to be able to get the actual time that the lazy request spent on the server side. That was actually interesting, because when we first implemented this feature, we thought we had a bug. The total time for the request was lower than the time for each individual request. Then I realized that we are actually running the requests in parallel inside the server, so that made sense.

Embedded / remote clients unity. Similar to the previous issue, embedded clients had a totally different code path than remote clients. That caused issues because sometimes you had something that would work in embedded but not in remote. And that sucked. We changes things so now everything works through the same (async!) pipeline. That means that you can do async calls on embedded databases, and that as far as RavenDB is concerned, there really is no difference if you are calling me from the same process or remotely.

Admin operation split was done so we won’t have a developer accidently try to use an operation that requires admin privileges. Now all of the privilege actions are under the cmds.Admin or cmds.GlobalAdmin properties. That gives you a good indication about the permission levels that you need for an operation. Either you just need access to the database (obvious), or you are a database admin (able to do things such as take backups, start / stop indexing, etc) or you are a server admin, and can create or delete databases, change permissions, etc.

Bulk insert errors are now handled much better, previously we had to wait until the operation would be completed, which could be quite a while. Now we can detect and error on them immediately.

Bulk insert change detection. Users often use bulk insert to manage ETL processes. It is very common to have a nightly process that run over the data and write large portions of it. With 3.0, we have the ability to specify that the data might actually be the same, so the bulk insert process will check, and if the stored value and the new value is the same, the server will skip writing to this document. In this way, we won’t have to re-index this document, re-replicate it, etc.

Reduced client side allocations. RavenDB users often run their software for months at a time, that means that anything that we can do to help reduce resource consumption is good. We have changed how we work internally to reduce the number of allocations that we are doing, and in particular to reduce the number of large object heap allocations. This tend to reduce the overall resource cost significantly over time.

What changes? In RavenDB, you could ask the session if there has been any changes (ie, if a call to SaveChanges() will go to the server), or if a particular entity had changes. Honestly, we added that feature strictly for our own testing, we didn’t think it would actually be used. Overtime, we saw that users often had questions in the form of: “I loaded the document, made no changes, but it is still saying that it changed!” The answer for those questions ranged from: “You have a computed Age field that uses the current time to calculate itself” to “you added/remove a property, and now it needs to be saved.” Sometimes it was our change detection code that had a false positive, as well, but any time this happened, that required a support call to resolve. Now, you can call session.Advanced.WhatChanged(), which will give you a dictionary with full details on all the changes that happened in the session.

Missing properties retention. This one is probably the first feature that we developed strictly for 3.0. The issue is what happens when you load a document from the database, but it has extra properties. What do I mean by that? Imagine that we changed our code to remove the FullName property. However, all our documents retain that property. In 2.5, loading and saving the document would overwrite the existing document with the new one, without the property. We got feedback from customers that this wasn’t a desirable behavior. Now, even though the FullName property isn’t accessible from your model, it will be retained (even if you have made changes to other properties).

Formatted indexes. In 2.5, you usually define indexes using the linq query format, but when you look at them on the server side, they can be… quite ugly. We are now using the same index format technique we have server side to prettify the indexes and make sure that they look very similar to the way you define them in code.

There are other stuff that went into the client, better Linq query support, you can now do includes on the results of MoreLikeThis query, and a lot of other stuff that I just done have the time (and you the patience) to go over them all. Those are the highlights, the things that really stand out.

FUTURE POSTS

  1. The null check that didn't check for nulls - 9 hours from now

There are posts all the way to Apr 28, 2025

RECENT SERIES

  1. Production Postmortem (52):
    07 Apr 2025 - The race condition in the interlock
  2. RavenDB (13):
    02 Apr 2025 - .NET Aspire integration
  3. RavenDB 7.1 (6):
    18 Mar 2025 - One IO Ring to rule them all
  4. RavenDB 7.0 Released (4):
    07 Mar 2025 - Moving to NLog
  5. Challenge (77):
    03 Feb 2025 - Giving file system developer ulcer
View all series

RECENT COMMENTS

Syndication

Main feed Feed Stats
Comments feed   Comments Feed Stats
}