We are working on updating this book for the latest version. Some content might be out of date.
Of course, data denormalization has downsides too.
The first disadvantage is
that the index will be bigger because the
_source document for every
blog post is bigger, and there are more indexed fields. This usually isn’t a
huge problem. The data written to disk is highly compressed, and disk space
is cheap. Elasticsearch can happily cope with the extra data.
The more important issue is that, if the user were to change his name, all
of his blog posts would need to be updated too. Fortunately, users don’t
often change names. Even if they did, it is unlikely that a user would have
written more than a few thousand blog posts, so updating blog posts with
bulk APIs would take less than a
In this example, we are going to emulate a filesystem with directory trees in
Elasticsearch, much like a filesystem on Linux: the root of the directory is
/, and each directory can contain files and subdirectories.
We want to be able to search for files that live in a particular directory, the equivalent of this:
grep "some text" /clinton/projects/elasticsearch/*
This requires us to index the path of the directory where the file lives:
Really, we should also index
directory documents so we can list all
files and subdirectories within a directory, but for brevity’s sake, we will
ignore that requirement.
We also want to be able to search for files that live anywhere in the directory tree below a particular directory, the equivalent of this:
grep -r "some text" /clinton
To support this, we need to index the path hierarchy:
This hierarchy can be generated automatically from the
path field using the
The mapping for the
file type would look like this:
Once the index is set up and the files have been indexed, we can perform a
search for files containing
elasticsearch in just the
/clinton/projects/elasticsearch directory like this:
Every file that lives in any subdirectory under
/clinton will include the
/clinton in the
path.tree field. So we can search for all files in
any subdirectory of
/clinton as follows:
So far, so good.
Renaming a file is easy—a simple
request is all that is required. You can even use
optimistic concurrency control to
ensure that your change doesn’t conflict with the changes from another user:
We can even rename a directory, but this means updating all of the files that
exist anywhere in the path hierarchy beneath that directory. This may be
quick or slow, depending on how many files need to be updated. All we would
need to do is to use
scroll to retrieve all the
files, and the
bulk API to update them. The process isn’t
atomic, but all files will quickly move to their new home.