liveBook · Manning

Logical AND operator

As explained in Elasticsearch in Action, Second Edition

An AND operator is a Boolean query operator that requires all joined terms to match.

The logical AND operator narrows a search by requiring every joined term or condition to match. Elasticsearch uses OR by default, so a match query for “Joshua Schildt” can return books matching either name; setting operator to AND returns no result when no book contains both terms. section 2.3.2

Listing 2.9 Query with an AND operator to fetch exact matches
GET books/_search
{
  "query": {
    "match": {
      "author": {                    #1
        "query": "Joshua Schildt",   #2
        "operator": "AND"            #3
      }
    }
  }
}

Use an object for the match value, then set operator to AND so both author terms must match. section 2.3.2

The same rule applies to multiple words in a title. Searching for “Java Complete Guide” with AND requires all three words, whereas the default OR behavior returns titles containing any of them. AND requires shared terms, not necessarily an exact phrase. section 10.5.4

Choose the form that matches the search interface:

  • Use operator: AND inside a match query for one analyzed field, such as a book title or author. section 2.3.2 section 10.5.4
  • Use default_operator=AND for query-string searches across fields, such as a movie title and actor. section 8.6.2 section 10.9.2
  • Use a bool must array when every condition must hold, such as matching TVs and restricting their price range. section 11.3.3

Combining movie criteria

GET movies/_search?q=title:Knight AND actors:Bale returns a movie matching both the title and actor criteria. Omitting AND broadens the search and can include movies matching either criterion. section 8.6.2

Do not use AND when a partial match is intended. minimum_should_match can require only a chosen number of terms—for example, at least two of three words—while setting it to three is equivalent to requiring all three. section 10.5.5

How Elasticsearch in Action, Second Edition covers it

How deep it goes
Explains default OR behavior, field-level and query-string syntax, bool must, and the partial-match alternative.
Examples
Uses book author and title searches, movie title-and-actor filtering, and TV filtering by product type and price.
What it assumes
Assumes basic Elasticsearch search requests and match or query_string queries while demonstrating their AND configuration.
What you can do after
Apply it via Elasticsearch REST queries to require all terms, fields, or compound conditions in a search.
How it connects
Connects match queries, query_string queries, bool queries, must clauses, range queries, and minimum_should_match.

Also explained in

Compare how 7 books explain logical AND operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elasticsearch in Action, Second Edition. The section links point to the parts of the book it draws on.