DEV Community

Cover image for #008: Como definir o mapeamento no Elasticsearch
Bruno Flegler Dal'Col
Bruno Flegler Dal'Col

Posted on

1 1

#008: Como definir o mapeamento no Elasticsearch

O mapeamento defini como cada campo do documento será indexado. Uma vez que não é definido o tipo do campo o Elasticsearch irá definir dinamicamente. Podemos ver o mapping criado no nosso índice customers.

GET /customers/_mapping
Enter fullscreen mode Exit fullscreen mode
{
  "customers" : {
    "mappings" : {
      "properties" : {
        "age" : {
          "type" : "long"
        },
        "createdAt" : {
          "type" : "date"
        },
        "email" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "id" : {
          "type" : "long"
        },
        "name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

 

Os tipos sugeridos pelo Elasticsearch:

Campo Tipo Valor
age long 18
createdAt date "2021-08-21T03:16:33.116Z"
email text "Antonia.Will@gmail.com"
id long 55
name text "Mrs. Mable Ritchie"

 

⚠️ Atenção:

Uma vez que o índice é definido não podemos mais alterar o tipo do campo, apenas adicionar um campo novo. Da mesma forma não será mais possível indexar um documento com outro formato. Vamos tentar indexar um documento com o id a abcdef.

 

POST /customers/_doc
{
  "id": "abcdef",
  "name": "Brenda H. Barajas",
  "email": "bredahbarajas@hotmail.com",
  "age": 97,
  "createdAt": "2021-08-29T19:16:33.099Z"
}
Enter fullscreen mode Exit fullscreen mode

O Elasticsearch indica que não é possível transformar abcedf em um valor numérico.

{
  "error" : {
    "root_cause" : [
      {
        "type" : "mapper_parsing_exception",
        "reason" : "failed to parse field [id] of type [long] in document with id 'q64NlHsBLpS_vORe78sd'. Preview of field's value: 'abcdef'"
      }
    ],
    "type" : "mapper_parsing_exception",
    "reason" : "failed to parse field [id] of type [long] in document with id 'q64NlHsBLpS_vORe78sd'. Preview of field's value: 'abcdef'",
    "caused_by" : {
      "type" : "illegal_argument_exception",
      "reason" : "For input string: \"abcdef\""
    }
  },
  "status" : 400
}
Enter fullscreen mode Exit fullscreen mode

Vamos deletar o índice customers e criar ele novamente definindo o mapping antes.

DELETE customers
Enter fullscreen mode Exit fullscreen mode

Agora podemos criar o mapping antes de indexar o primeiro documento.

PUT /customers
{
  "mappings": {
    "properties": {
      "id": {
        "type": "text"
      },
      "age": {
        "type": "integer"
      },
      "email": {
        "type": "text"
      },
      "name": {
        "type": "text"
      },
      "createdAt": {
        "type": "date"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Se olharmos o mapping agora o id será do tipo text e conseguiríamos indexar com o valor abcdef.

O mapeamento é um tema complexo, envolve os tipos dos campos e depende de um conhecimento prévio do documento que será indexado para conseguir otimizar as buscas. Com o tempo vamos entender quais tipos são sugeridos para cada tipo de situação.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up