Consultas por termo e correspondência
Aprenda a usar consultas `term` para correspondência exata de valores e consultas `match` para análise de texto completo e pontuação de relevância.
Consultas por termo e correspondência é uma aula grátis de Elasticsearch & Full Text Search Systems no CoddyKit. Esta é a aula 2 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.
Intro to Term & Match Queries
Welcome to the fundamentals of querying data in Elasticsearch! Today, we'll explore two essential query types: term and match.
Understanding their differences is crucial for effective search. We'll learn when to use each to get exactly the results you need, whether it's an exact value or a flexible full-text search.
Indexing Sample Documents
Before we query, let's index some simple documents into an index called products. We'll use these examples throughout the lesson.
Run these curl commands in your terminal (assuming Elasticsearch is running on localhost:9200):
curl -X PUT "localhost:9200/products/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
"name": "Laptop Pro X1",
"category": "Electronics",
"description": "A powerful and lightweight laptop for professionals.",
"price": 1200
}'
curl -X PUT "localhost:9200/products/_doc/2?pretty" -H 'Content-Type: application/json' -d'
{
"name": "Wireless Mouse",
"category": "Accessories",
"description": "Ergonomic wireless mouse with long battery life.",
"price": 25
}'
curl -X PUT "localhost:9200/products/_doc/3?pretty" -H 'Content-Type: application/json' -d'
{
"name": "Gaming Keyboard",
"category": "Electronics",
"description": "Mechanical keyboard for intense gaming sessions.",
"price": 90
}'`term` Query: Exact Matching
The term query is used for finding exact values in a field. It looks for a precise match without any text analysis (like lowercasing or stemming).
- It's ideal for structured data like product IDs, categories, tags, or status fields.
- It works best with fields that are mapped as
keyword(non-analyzed strings) or numeric types.
`term` Query in Action
Let's find all products with the exact category "Electronics". Notice we're querying category.keyword because the default text field would be analyzed.
Try this curl command:
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"term": {
"category.keyword": "Electronics"
}
}
}'Understanding .keyword
When you index a string field (like category), Elasticsearch often creates two versions by default:
category: Atextfield, which is analyzed (broken into words, lowercased).category.keyword: Akeywordfield, which is treated as a single, exact string.
The term query expects an exact match, so using the .keyword sub-field ensures your query string isn't analyzed and matches the exact stored value.
`match` Query: Full-Text Power
The match query is your go-to for full-text search. Unlike term, it's designed to be smart about text.
- It performs text analysis on your search query.
- It breaks your query string into individual terms, lowercases them, and sometimes stems them (e.g., "running" -> "run").
- It then finds documents that contain these analyzed terms, and also assigns a relevancy score.
`match` Query in Action
Let's search for products with "powerful laptop" in their description. Even if the document contains "A powerful and lightweight laptop", the match query will find it.
Try this curl command:
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match": {
"description": "powerful laptop"
}
}
}'The Magic of Text Analysis
When you use a match query, Elasticsearch's text analysis process kicks in:
- Tokenization: "powerful laptop" becomes "powerful" and "laptop".
- Lowercasing: "Powerful" becomes "powerful".
- Stop Words: Common words like "a", "the" might be removed (depending on the analyzer).
This makes match queries highly flexible for natural language search, finding relevant results even with minor variations in phrasing or case.
`term` vs `match`: Key Differences
Here's a quick summary of when to use each query type:
termquery:
- For exact value matching.
- Does NOT perform text analysis on query string.
- Best forkeywordfields, IDs, precise filters.matchquery:
- For full-text search.
- PERFORMS text analysis on query string.
- Best fortextfields, search bars, descriptive content.
Query Understanding Check
Which of the following statements are true regarding term and match queries in Elasticsearch?
Recap: `term` & `match`
Great job! You've learned the fundamental difference between term and match queries.
termis for surgical, exact value searches.matchis for flexible, full-text searches leveraging powerful text analysis.
Knowing when to use each is key to building effective search experiences. Next, we'll explore how to combine these and other queries to create even more sophisticated search logic!
Aprenda Elasticsearch & Full Text Search Systems com um tutor de IA — grátis
Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.
- Cursos
- 12
- Aulas
- 48
Perguntas Frequentes
A aula “Consultas por termo e correspondência” é grátis?
Sim — o texto completo de “Consultas por termo e correspondência” é 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 “Consultas por termo e correspondência”?
Aprenda a usar consultas `term` para correspondência exata de valores e consultas `match` para análise de texto completo e pontuação de relevância. 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 2 de 4.
Quanto tempo leva a aula “Consultas por termo e correspondência”?
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
- Introdução à DSL de consultas
- Consultas por termo e correspondência
- Combinando consultas com Bool
- Filtragem, intervalos e contexto de consulta