liveBook · Manning

Span query

As explained in Elasticsearch in Action, Second Edition

A span query is an Elasticsearch positional query clause that matches terms according to their order and proximity in analyzed text.

A span query searches analyzed text by token position, preserving word order and proximity instead of ignoring where matching terms occur. This makes it useful for legal documents, research articles, and technical books where exact positional relationships matter. section 12.0 section 12.8

Listing 12.14 Priming Elasticsearch for a span query
PUT quotes             #1
{
  "mappings": {
    "properties": {
      "author":{
        "type": "text"
      },
      "quote":{
        "type": "text"
      }
    }
  }
}
 
PUT quotes/_doc/1      #2
{
  "author":"Isaac Newton",
  "quote":"Plato is my friend. Aristotle is my friend. 
   But my greatest friend is the truth."
}

Create a quotes index with text fields for author and quote, then index a quotation that can be tested with positional queries. section 12.8.1

Finding an ordered quotation

Consider the indexed quote: “Plato is my friend. Aristotle is my friend. But my greatest friend is the truth.” A positional requirement can search for Plato before Aristotle, with Aristotle at least four positions away. In the illustrated relationship, Plato is at position 1, Aristotle at position 5, and their span is 5. A normal full-text or term-level query cannot express all of these conditions; a prefix query only partially helps. section 12.8 section 12.8.1

Span queries provide several positional forms, including:

Figure 12.8 Finding a quote using a positional query

Use the positional diagram to inspect how token positions and span distance determine whether the quotation matches. section 12.8

How Elasticsearch in Action, Second Edition covers it

How deep it goes
Defines low-level positional matching and names several forms, but defers detailed syntax and the complete query family to documentation.
Examples
Uses an Isaac Newton quotation to test whether Plato precedes Aristotle with a specified positional distance.
What it assumes
Assumes basic Elasticsearch searching and text fields while establishing the sample index and documents from scratch.
What you can do after
Evaluate quotations and specialized documents using ordered, proximity-based token criteria.
How it connects
Connects positional tokens with full-text queries, term-level queries, prefix queries, span_first, span_near, and span_within.

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.