Goodbye Transformers, Welcome Server-side Projections

In the previous post, I shared some good things about our new query language: RQL. Now, I will show you how to shape your query results using server-side projections.

What happened with Transformers?

[tweet]If you know RavenDB 3.5, you are probably looking for how to implement Transformers. Bad news: They are gone! Great news: You will not miss them.[/tweet]

Transformers were removed and substituted by server-side projection support. Methods like TransformWith are no longer available, and simple Select should be used instead.

Easy start with server-side projections

Instead of pulling full documents in query results you can just grab some pieces of data from documents. You can also transform the projected results.

Let me share a short example:

// request Name, City and Country for all entities from 'Companies' collection
var results = session
    .Query<Company>()
    .Select(x => new
    {
        Name = x.Name,
        City = x.Address.City,
        Country = x.Address.Country
    })
    .ToList();

This approach is a lot easier than Transformers! Right?

The related RQL is pretty simple as well:

from Companies
select Name, Address.City as City, Address.Country as Country

I love how expressive and easy to understand RQL is.

Another example? Here we go:

var results = (from e in session.Query<Employee>()
               select new
               {
                   FullName = e.FirstName + " " + e.LastName,
               }).ToList();

And here it is the RQL:

from Employees as e
select {
    FullName : e.FirstName + " " + e.LastName
}

Getting some more advanced results using functions

Let’s do something more complicated.

var results = (from e in session.Query<Employee>()
               let format = (Func<Employee, string>)(p => p.FirstName + " " + p.LastName)
               select new
               {
                   FullName = format(e)
               }).ToList();

What are we doing? We just created a function that will run on the server-side.

But, … let’s look the RQL.

declare function output(e) {
    var format = function(p){ return p.FirstName + " " + p.LastName; };
    return {
        FullName : format(e)
    };
}
from Employees as e select output(e)

OMG! Yes, that is it! We can define functions when coding with RQL. These functions are pure Javascript (You shouldn’t have doubts about the0 Javascript power).

Composing results with multiple documents

What if we need to mix data from multiple documents? Easy and simple:

var results = (from o in session.Query<Order>()
               let c = RavenQuery.Load<Company>(o.Company)
               select new
               {
                   CompanyName = c.Name,
                   ShippedAt = o.ShippedAt
               }).ToList();

Very similar in RQL:

from Orders as o
load o.Company as c
select {
	CompanyName: c.Name,
	ShippedAt: o.ShippedAt
}

Call to action

RavenDB4 makes easier to shape query results. No more transformers!

Want to learn more about this functionality, I recommend you to read to read our article that covers the projection functionality which can be found here.

Go write some code!

Cover: unsplash-logoIgnacio Giri

Compartilhe este insight:

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Mais insights para o seu negócio

Veja mais alguns estudos e reflexões que podem gerar alguns insights para o seu negócio:

Gosto bastante da abordagem de Caitie McCaffrey para explicar sagas. Neste post, me inspiro na linha de raciocínio dela para...
Uma das vantagens de estudar diversas linguagens, frameworks, técnicas e prática é encontrar inspiração inusitada para nosso código. Nesse post...
Há anos eu conheço e aceito a ideia de que devemos buscar melhoria contínua. Sei que é natural e aceitável...
Nesse ano, palestrei na APIX sobre microsserviços. Abaixo, registro em vídeo feito pela organização do evento. Comentários? Feedback?
Ligo a TV e assisto algum político falando besteiras. Acesso o Instagram e vejo a foto de um casal de...
Confesso que estava sentindo falta de escrever em primeira pessoa. Há tempos, publicando apenas nos sites da EximiaCo, não encontrava,...

Inscrição realizada com sucesso!

No dia da masterclass você receberá um e-mail com um link para acompanhar a aula ao vivo. Até lá!

A sua subscrição foi enviada com sucesso!

Aguarde, em breve entraremos em contato com você para lhe fornecer mais informações sobre como participar da mentoria.

Crie sua conta

Preencha os dados para iniciar o seu cadastro no plano anual do Clube de Estudos:

Crie sua conta

Preencha os dados para iniciar o seu cadastro no plano mensal do Clube de Estudos:

× Precisa de ajuda?