Querying with RQL

In the previous post, you learned how to install RavenDB on your computer, create a database and load sample data. Also, you learned some fundamental concepts about document databases.

Now, you will learn how to write your queries using RQL.

RQL? What is it?

RQL is one of the most exciting features of RavenDB 4. It is a powerful, easy to use and learn, language that we design to make your life simpler.

From the Documentation:

RQL, the Raven Query Language, is a SQL-like language used to retrieve the data from the server when queries are being executed. It is designed to expose the RavenDB query pipeline in a way that is easy to understand, easy to use, and not overwhelming to the user.

The RQL documentation is really good. You should consider reading it.

Getting ready to write queries

It’s time to stop talking and to write some code. So, let’s do that.

  1. Open the RavenDB Management Studio (http://localhost:8080 by default. Remember?)
  2. In the left panel, click on Databases
  3. Open the database we created in the previous post (Northwind, if you followed my recommendation)
  4. In the left panel, select the Documents section.
  5. Click on Query.

There are other paths to this. I will let you discover it.

You first query

Let’s start easy.

  1. Assuming you are already in the Query editor (inside the RavenDB Management
    Studio). Type the following query.
from Employees
  1. Click on the Run button.

Yes. You are right. This query returns all the documents inside the Employees collection. I think you got it.

Now, go ahead and try other queries like these. Get all the documents from the Products collection.

Filtering

Getting all documents from a collection is a nice thing but quite useless. Let’s make something more exciting.

from Employees
where FirstName=="Nancy"

Yes! I think you got it. FirstName is the name of one of the properties present
in the documents from the Employees collection.

{
    "LastName": "Davolio",
    "FirstName": "Nancy",
    "Title": "Sales Representative",
    "Address": {
        "Line1": "507 - 20th Ave. E.rnApt. 2A",
        "Line2": null,
        "City": "Seattle",
        "Region": "WA",
        "PostalCode": "98122",
        "Country": "USA",
        "Location": {
            "Latitude": 47.623473,
            "Longitude": -122.306009
        }
    },
    "HiredAt": "1992-05-01T00:00:00.0000000",
    "Birthday": "1948-12-08T00:00:00.0000000",
    "HomePhone": "(206) 555-9857",
    "Extension": "5467",
    "ReportsTo": "employees/2-A",
    "Notes": [
        "Education includes a BA in psychology from Colorado State University in 1970.  She also completed "The Art of the Cold Call."  Nancy is a member of Toastmasters International."
    ],
    "Territories": [
        "06897",
        "19713"
    ],
    "@metadata": {
        "@collection": "Employees",
        "@flags": "HasAttachments"
    }
}

Shaping the query result

Until now, we are just getting documents. Let’s say we want to shape what we get. Consider the following query.

from Orders
where Lines.Count > 4
select Lines[].ProductName as ProductNames, OrderedAt, ShipTo.City

Again, I am sure you understand what is going on. We are not interested in all data from the Orders documents. So, we are specifying a shape.

One of the results will look like that:

{
    "ProductNames": [
        "Ikura",
        "Gorgonzola Telino",
        "Geitost",
        "Boston Crab Meat",
        "Lakkalikööri"
    ],
    "OrderedAt": "1996-08-05T00:00:00.0000000",
    "ShipTo.City": "Cunewalde",
    "@metadata": {
        "@flags": "HasRevisions",
        "@id": "orders/26-A",
        "@last-modified": "2018-02-28T11:21:24.1689975Z",
        "@change-vector": "A:275-ZzT6GeIVUkewYXBKQ6vJ9g",
        "@projection": true,
        "@index-score": 1
    }
}

We will talk about the metadata in the future.

Using Javascript in the query projections

The last query was nice. But, let’s say you want to do more customization.

from Orders as o
load o.Company as c
select {
    Name: c.Name.toLowerCase(),
    Country: c.Address.Country,
    LinesCount: o.Lines.length
}

RavenDB allows you to use Javascript (Everybody knows the basics of Javascript, right?) when defining projections for the query results.

There is another interesting thing in this query, as you probably noted. The Company field of an Order document contains the ID of another document stored in the database. The load instruction is smart enough to get that document for you, so you can use it to project data as well.

Map and reduce (Oh Yeah!)

Consider the following query:

from Orders
group by Company
where count() > 5
order by count() desc
select count() as Count, key() as Company

What are we doing here? We are grouping the Orders using the Company field as grouping key. So we are adding a filter to get only groups with five documents at least, and then, ordering this groups by the number of elements in descending order. Finally, we are projecting the number of documents per group and the group key.

In “business words” this query results in a list of top buyers companies.

How it works

For a while, you shouldn’t care about our implementation details. But, it’s important to say that we are concerned about performance and we use a bunch of techniques to deliver results as fast as possible (even more!).

All queries in RavenDB are supported by a sophisticated and efficient indexing mechanism. In simple words, we use indexes for all the queries. But, I will explain it with more details in the future.

Last words…

Awesome!  Now you know the basics about Querying with RavenDB. It’s easy, right?

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:

Aprendemos que a priorização das atividades deve ser feita, invariavelmente, pelo time do negócio. Na prática, entretanto, em nosso time,...
Este post é uma releitura de um que havia escrito, em 2016, e que se perdeu no “reboot” do blog....
Uma dúvida comum e recorrente em minhas consultorias é “Como eu faço para manter a consistência de dados entre meus...
Are you interested to know more about the internals of the .NET Runtime? So you should spend some time reading...
Em minha experiência, a inovação acontece a partir de um dos seguintes gatilhos: A área de negócios identifica uma demanda...
Write code is not a simple task. It is easy to make mistakes that result in bad performance. The last...

Curso Reputação e Marketing Pessoal

Masterclasses

01

Introdução do curso

02

Por que sua “reputação” é importante?

03

Como você se apresenta?

04

Como você apresenta suas ideias?

05

Como usar Storytelling?

06

Você tem uma dor? Eu tenho o alívio!

07

Escrita efetiva para não escritores

08

Como aumentar (e manter) sua audiência?

09

Gatilhos! Gatilhos!

10

Triple Threat: Domine Produto, Embalagem e Distribuição

11

Estratégias Vencedoras: Desbloqueie o Poder da Teoria dos Jogos

12

Análise SWOT de sua marca pessoal

13

Soterrado por informações? Aprenda a fazer gestão do conhecimento pessoal, do jeito certo

14

Vendo além do óbvio com a Pentad de Burkle

15

Construindo Reputação através de Métricas: A Arte de Alinhar Expectativas com Lag e Lead Measures

16

A Tríade da Liderança: Navegando entre Líder, Liderado e Contexto no Mundo do Marketing Pessoal

17

Análise PESTEL para Marketing Pessoal

18

Canvas de Proposta de Valor para Marca Pessoal

19

Método OKR para Objetivos Pessoais

20

Análise de Competências de Gallup

21

Feedback 360 Graus para Autoavaliação

22

Modelo de Cinco Forças de Porter

23

Estratégia Blue Ocean para Diferenciação Pessoal

24

Análise de Tendências para Previsão de Mercado

25

Design Thinking para Inovação Pessoal

26

Metodologia Agile para Desenvolvimento Pessoal

27

Análise de Redes Sociais para Ampliar Conexões

Lições complementares

28

Apresentando-se do Jeito Certo

29

O mercado remunera raridade? Como evidenciar a sua?

30

O que pode estar te impedindo de ter sucesso

Recomendações de Leituras

31

Aprendendo a qualificar sua reputação do jeito certo

32

Quem é você?

33

Qual a sua “IDEIA”?

34

StoryTelling

35

Você tem uma dor? Eu tenho o alívio!

36

Escrita efetiva para não escritores

37

Gatilhos!

38

Triple Threat: Domine Produto, Embalagem e Distribuição

39

Estratégias Vencedoras: Desbloqueie o Poder da Teoria do Jogos

40

Análise SWOT de sua marca pessoal

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.

Masterclass
15/07

Pare de dar a solução certa para o problema errado

Muita gente boa quebra a cabeça por dias tentando resolver o que não estava quebrado, simplesmente por tentar dar a resposta certa pro problema errado, mas precisa realmente ser assim?

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?