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:
- span_first, for matching terms at an early document position. section 12.8 section 12.8.1
- span_near, for expressing ordered or nearby token relationships. section 12.8
- span_within, for locating one positional span inside another. section 12.8
Use the positional diagram to inspect how token positions and span distance determine whether the quotation matches. section 12.8
