0Pricing
Elasticsearch & Full Text Search Systems · Aula

Indexando documentos no Elasticsearch

Entenda como indexar um ou vários documentos em um índice do Elasticsearch, incluindo a geração automática de ID e o uso de IDs personalizados.

Indexando documentos no Elasticsearch é uma aula grátis de Elasticsearch & Full Text Search Systems no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Elasticsearch & Full Text Search Systems, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Elasticsearch & Full Text Search Systems inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

What is Indexing?

Welcome to indexing! In Elasticsearch, indexing is the process of storing data into an index to make it searchable.

Think of it like adding a new book to a library's catalog. You provide the book's details, and the library stores them in a way that makes the book easy to find later.

Documents & Indices Refresher

Before we dive in, let's quickly recap two core concepts:

  • Document: A basic unit of information in Elasticsearch, similar to a row in a traditional database. It's usually a JSON object.
  • Index: A collection of documents that have similar characteristics. It's like a database in a relational world.

When you index, you add a document to an index.

The Index API

You interact with Elasticsearch using its REST API. To index a document, you'll typically use HTTP POST or PUT requests.

  • POST /<index>/_doc: Used to index a document, often letting Elasticsearch generate an ID.
  • PUT /<index>/_doc/<id>: Used to index a document with a specific, user-provided ID.

Let's see them in action!

Auto-Generated IDs

The simplest way to index is to let Elasticsearch generate a unique ID for your document. You use the POST method to the _doc endpoint without specifying an ID.

Here's an example using curl to index a document into an index named products:

curl -X POST "localhost:9200/products/_doc?pretty" \
     -H 'Content-Type: application/json' \
     -d'{"name": "Laptop", "price": 1200}'

Understanding Auto IDs

After the previous POST request, Elasticsearch would return a response including a unique _id for your document, like "_id": "AbCdEfGhIjKlMnOpQrSt".

When should you use auto-generated IDs?

  • When you don't have a natural unique identifier for your data.
  • For logs or temporary data where a unique ID isn't critical for external reference.
  • When you want to guarantee a new document is always created.

Indexing with Custom IDs

Often, your data already has a unique identifier from another system (e.g., a database primary key). In such cases, you can provide your own ID using the PUT method.

The ID is specified directly in the URL path: /<index>/_doc/<your_id>.

curl -X PUT "localhost:9200/products/_doc/prod_101?pretty" \
     -H 'Content-Type: application/json' \
     -d'{"name": "Smartphone", "price": 800}'

Why Use Custom IDs?

Using custom IDs offers several advantages:

  • Integration: Easily map Elasticsearch documents to records in an external database.
  • Predictability: You know the document's ID beforehand.
  • Updates: It makes updating specific documents straightforward, as you always refer to them by their known ID.

Idempotency with PUT

A key concept when using PUT with a custom ID is idempotency. This means that performing the same operation multiple times will produce the same result as performing it once.

  • If a document with the specified ID already exists, PUT will update it.
  • If it doesn't exist, PUT will create it.

This is different from POST, which always creates a *new* document with a new ID.

Indexing Many Documents

While indexing documents one-by-one is fine for small numbers, it can be inefficient for large datasets due to network overhead.

Elasticsearch provides a powerful _bulk API that allows you to perform multiple index, update, or delete operations in a single request. This dramatically improves indexing performance.

We'll explore the _bulk API in more detail in a future lesson!

Indexing Method Check

Imagine you have a new set of sensor readings. Each reading is unique, and you don't have a predefined ID for them, but you want to store them in Elasticsearch to be searchable.

Recap: Indexing Essentials

Great job! In this lesson, you learned the fundamentals of indexing documents into Elasticsearch:

  • What indexing means and its role in making data searchable.
  • The difference between documents and indices.
  • How to use POST /<index>/_doc to index documents with auto-generated IDs.
  • How to use PUT /<index>/_doc/<id> to index documents with custom IDs.
  • The concept of idempotency when using PUT.
  • A brief introduction to the efficiency of bulk indexing.

Next, we'll explore more operations on these documents!

Perguntas Frequentes

A aula “Indexando documentos no Elasticsearch” é grátis?

Sim — o texto completo de “Indexando documentos no Elasticsearch” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Elasticsearch & Full Text Search Systems, atualize para CoddyKit PRO. O curso de Elasticsearch & Full Text Search Systems inclui 4 aulas no total.

O que vou aprender em “Indexando documentos no Elasticsearch”?

Entenda como indexar um ou vários documentos em um índice do Elasticsearch, incluindo a geração automática de ID e o uso de IDs personalizados. Você pratica Elasticsearch & Full Text Search Systems com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Elasticsearch & Full Text Search Systems?

Nenhuma experiência prévia é necessária. Elasticsearch & Full Text Search Systems no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.

Quanto tempo leva a aula “Indexando documentos no Elasticsearch”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Elasticsearch & Full Text Search Systems?

Sim. Cada aula de Elasticsearch & Full Text Search Systems inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Indexando documentos no Elasticsearch
  2. Operações CRUD com documentos
  3. Mapeamento básico e tipos de dados
  4. Indexação em massa e a API Bulk
← Voltar para Elasticsearch & Full Text Search Systems