Indexing Polymorphic Data



Polymorphic Data

Let's assume, for example, that we have the following inheritance hierarchy:

Figure 1: Polymorphic indexes

When saving a Cat document, it will be assigned to the "Cats" collection,
while a Dog document will be placed in the "Dogs" collection.

If we intend to create a simple Map-index for Cat documents based on their names, we would write:

from cat in docs.Cats
select new { cat.name }

And for dogs:

from dog in docs.Dogs
select new { dog.name }

The challenge

Querying each index results in documents only from the specific collection the index was defined for.
However, what if we need to query across ALL animal collections?

Multi-Map Indexes

The easiest way to do this is by writing a multi-map index such as:

IndexDefinition indexDefinition = new IndexDefinition();
indexDefinition.setName("Animals/ByName");
HashSet<String> maps = new HashSet<>();
maps.add("docs.Cats.Select(c => new { name = c.name})");
maps.add("docs.Dogs.Select(c => new { name = c.name})");
indexDefinition.setMaps(maps);
public static class Animals_ByName extends AbstractJavaScriptIndexCreationTask {
    public Animals_ByName() {
        setMaps(Sets.newHashSet(
            "map('cats', function (c){ return {name: c.name}})",
            "map('dogs', function (d){ return {name: d.name}})"
        ));
    }
}

And query it like this:

List<Animal> results = session
    .query(Animal.class, Query.index("Animals/ByName"))
    .whereEquals("name", "Mitzy")
    .toList();
from index 'Animals/ByName'
where name = 'Mitzy'

Other Options

Another option would be to modify the way we generate the Collection for subclasses of Animal:

try (IDocumentStore store = new DocumentStore()) {
    store.getConventions().setFindCollectionName(clazz -> {
        if (Animal.class.isAssignableFrom(clazz)) {
            return "Animals";
        }

        return DocumentConventions.defaultGetCollectionName(clazz);
    });
}

Using this method, we can now index on all animals using:

from animal in docs.Animals
select new { animal.name }

But what happens when you don't want to modify the entity name of an entity itself?

You can create a polymorphic index using:

from animal in docs.WhereEntityIs("Cats", "Dogs")
select new { animal.Name }

It will generate an index that matches both Cats and Dogs.