Chapter 14. Multifield Search
Queries are seldom simple one-clause match
queries. We frequently need to
search for the same or different query strings in one or more fields, which
means that we need to be able to combine multiple query clauses and their
relevance scores in a way that makes sense.
Perhaps we’re looking for a book called War and Peace by an author called Leo Tolstoy. Perhaps we’re searching the Elasticsearch documentation for “minimum should match,” which might be in the title or the body of a page. Or perhaps we’re searching for users with first name John and last name Smith.
In this chapter, we present the available tools for constructing multiclause searches and how to figure out which solution you should apply to your particular use case.
Multiple Query Strings
The simplest multifield query to deal with is the one where we can map
search terms to specific fields. If we know that War and Peace is the
title, and Leo Tolstoy is the author, it is easy to write each of these
conditions as a match
clause and to combine them with a bool
query:
GET
/
_search
{
"query"
:
{
"bool"
:
{
"should"
:
[
{
"match"
:
{
"title"
:
"War and Peace"
}},
{
"match"
:
{
"author"
:
"Leo Tolstoy"
}}
]
}
}
}
The bool
query takes a more-matches-is-better approach, so the score from
each match
clause will be added together to provide the final _score
for
each document. Documents that match both clauses will score higher than
documents that match just one clause.
Of course, you’re not restricted ...
Get Elasticsearch: The Definitive Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.