Boolean retrieval: exact conditions and the order of execution
布尔检索
Parse a small query grammar and compare equivalent postings-intersection plans.
boolean-retrievalThe same words, different parentheses
Should “bicycle OR brake AND cable” include a bicycle-paint record that has no cable? Under our declared precedence, AND binds before OR, so it should. “(bicycle OR brake) AND cable” should exclude it. A search interface needs an explicit language; guessing the user’s parentheses changes the task.
Boolean retrieval selects documents satisfying conditions rather than giving each document a graded relevance score. The conditions operate on indexed terms, so exact logical execution can still miss synonyms or return a document that does not meet the broader information need. IIR, chapter 1
The nine invented records make every result inspectable. A direct scan that tests each document against the expression is the simplest baseline. An inverted index can answer the same expression by combining term postings.
Separate meaning from execution order
Let A and B be sets of live documents containing two indexed terms. AND and OR denote intersection and union:
NOT requires a universe U. Here U contains the current live document IDs, including a live empty document. It is not “every document that has ever existed”:
Changing U can change an answer even when the term’s postings are unchanged. Deletions therefore need to affect the live set or another equivalent filter. Within a fixed universe, De Morgan’s law gives two equivalent expressions:
The parser uses uppercase NOT, AND and OR, with NOT binding most tightly and AND before OR. Parentheses override precedence. Lowercase “and” is an ordinary indexed term. Implicit conjunction, quotes and wildcards are outside this small grammar; malformed input is rejected rather than evaluated as Python.
For two nonempty sorted postings lists, a merge compares the current IDs and advances at least one pointer each time. An equal pair is emitted once and advances both pointers. Hence the number of pair comparisons is bounded by:
If either list is empty, no comparisons are needed. An AND over several terms may begin with the shortest list to keep intermediate results small. This preserves the intersection, but it is a heuristic for work, not a guarantee of optimal wall-clock time on every storage system. The textbook discusses this distinction between a query’s meaning and its execution plan. IIR, section 1.3
Parse, evaluate, then compare plans
Run with Python 3.12 and the standard library. The recursive-descent parser produces a tuple tree, whose leaves are terms. Evaluation uses set operations over an explicit live universe. A separate merge routine counts comparisons for two equivalent conjunction plans; it does not claim the set evaluator uses that merge internally.
import json,math,re
from collections import Counter,defaultdict
DOCUMENTS=(
'repair bicycle brake cable',
'bicycle brake adjustment guide',
'bicycle paint blue frame',
'car brake cable repair',
'cycle stopping wire replacement',
'repair bicycle brake cable cable cable',
'',
'brake cable bicycle repair',
'cell cycle stopping research',
)
def tokens(text):
if not isinstance(text,str) or len(text)>2000:raise ValueError('text of at most2000 characters required')
return re.findall(r'[a-z]+',text.lower())
def corpus(documents):
if not isinstance(documents,(list,tuple)) or not 1<=len(documents)<=100:raise ValueError('one to100 documents required')
return [tokens(d) for d in documents]
def build(documents=DOCUMENTS):
index={}
for doc,ts in enumerate(corpus(documents)):
for t in set(ts):index.setdefault(t,set()).add(doc)
return index
def parse(query):
if not isinstance(query,str) or not 1<=len(query)<=200:raise ValueError('nonempty bounded query required')
matches=list(re.finditer(r'[A-Za-z]+|[()]',query));last=0;ts=[]
for m in matches:
if query[last:m.start()].strip():raise ValueError('unsupported character')
ts.append(m.group());last=m.end()
if query[last:].strip() or not ts or len(ts)>64:raise ValueError('invalid or oversized query')
pos=0
def unary(depth):
nonlocal pos
if depth>16 or pos>=len(ts):raise ValueError('missing operand or excessive nesting')
word=ts[pos];pos+=1
if word=='NOT':return ('not',unary(depth+1))
if word=='(':
result=disjunction(depth+1)
if pos>=len(ts) or ts[pos]!=')':raise ValueError('unmatched parenthesis')
pos+=1;return result
if word in ['AND','OR',')']:raise ValueError('operand required')
return ('term',word.lower())
def conjunction(depth):
nonlocal pos
node=unary(depth)
while pos<len(ts) and ts[pos]=='AND':pos+=1;node=('and',node,unary(depth))
return node
def disjunction(depth):
nonlocal pos
node=conjunction(depth)
while pos<len(ts) and ts[pos]=='OR':pos+=1;node=('or',node,conjunction(depth))
return node
tree=disjunction(0)
if pos!=len(ts):raise ValueError('explicit operator required')
return tree
def evaluate(tree,index,live):
op=tree[0]
if op=='term':return set(index.get(tree[1],set()))&set(live)
if op=='not':return set(live)-evaluate(tree[1],index,live)
a=evaluate(tree[1],index,live);b=evaluate(tree[2],index,live)
if op=='and':return a&b
if op=='or':return a|b
raise ValueError('unknown operator')
def intersect(a,b):
i=j=comparisons=0;out=[]
while i<len(a) and j<len(b):
comparisons+=1
if a[i]==b[j]:out.append(a[i]);i+=1;j+=1
elif a[i]<b[j]:i+=1
else:j+=1
return out,comparisons
def plan(terms,index,ascending):
if not terms:raise ValueError('terms required')
order=sorted(terms,key=lambda t:len(index.get(t,set())),reverse=not ascending);result=sorted(index.get(order[0],set()));count=0;sizes=[len(result)]
for t in order[1:]:
if not result:break
result,n=intersect(result,sorted(index.get(t,set())));count+=n;sizes.append(len(result))
return dict(order=order,result=result,comparisons=count,intermediate_sizes=sizes)
def demo():
index=build();live=set(range(len(DOCUMENTS)))
queries=['bicycle AND brake AND NOT paint','bicycle OR brake AND cable','(bicycle OR brake) AND cable','NOT bicycle','NOT quasar','NOT (bicycle OR car)','NOT bicycle AND NOT car']
result={q:sorted(evaluate(parse(q),index,live)) for q in queries}
terms=['bicycle','brake','adjustment']
return dict(documents=list(DOCUMENTS),results=result,without_doc7=sorted(evaluate(parse('bicycle AND brake'),index,live-{7})),plans={'shortest_first':plan(terms,index,True),'longest_first':plan(terms,index,False)},empty_document_id=6,scope='Small explicit Boolean grammar: NOT before AND before OR, uppercase operators, complement over declared live IDs; not Lucene query syntax.')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
“bicycle OR brake AND cable” returns 0,1,2,3,5,7. With parentheses around the OR, it returns 0,3,5,7. ID 2 is the bicycle-paint record. “NOT bicycle” includes 3,4,6,8; ID 6 is empty but live. “NOT quasar” returns every live ID because the unknown term’s postings are empty.
For bicycle AND brake AND adjustment, shortest-first starts with adjustment, found only in document 1. It makes four ID comparisons in total. Longest-first starts with bicycle and brake and makes eight. Both return only ID 1. These are exact comparison counts on this fixture; list construction, sorting, memory access and Python overhead are not included.
The query length is limited to 200 characters and 64 tokens, with a nesting guard of 16 for parentheses and unary negation. For q expression nodes and N live documents, this simple materialized-set evaluator can require O(qN) set work and O(qN) worst-case intermediate storage. A production engine may instead stream iterators, use skip data or apply cost-based planning.
Logical NOT is not every engine’s query syntax
Lucene’s BooleanClause.Occur distinguishes MUST, FILTER, SHOULD and MUST_NOT. FILTER constrains matching without contributing to score, and a query consisting only of MUST_NOT is not allowed as a complete query in that API. Our explicit-universe complement is a mathematical teaching language, not a claim that “NOT term” has identical semantics in every search product. Lucene 9.12.3
Unknown words, analyzer mismatches and an incorrect universe can cause surprising answers without a bug in set algebra. A permission filter belongs in the declared live or eligible universe; otherwise negation could expose documents the user should not receive. Repeated terms do not change set membership, and Boolean matching supplies no natural preference among matching documents.
Use Boolean conditions for requirements such as mandatory terms, excluded categories or metadata filters. If the task calls for “most useful first,” add a separately specified ranker. Validate the parser with malformed input and truth tables, then compare the indexed result with direct document scanning. See BM25 for ranking after lexical matching.
Meaning first, speed second
- Why can a bicycle-paint record match “bicycle OR brake AND cable”?
Answer: AND binds first, so the expression is bicycle OR (brake AND cable). Matching bicycle is sufficient; the parenthesized alternative requires cable in every result.
- Should a live empty document match NOT bicycle in this grammar?
Answer: Yes. It belongs to U and not to the bicycle set. Removing it from U removes it from the complement.
- Does shortest-first change the answer for bicycle AND brake AND adjustment?
Answer: No. Intersection is associative and commutative. On this fixture it changes comparison count from eight to four while retaining result 1.
- Can an application’s Boolean syntax be inferred solely from the mathematical NOT symbol?
Answer: No. Inspect the engine’s grammar, implicit operators, universe and pure-negative-query rules. Lucene’s MUST_NOT contract illustrates why a mathematical complement and an API query are different objects.
Algebra and an interface contract
The IIR textbook supplies Boolean query processing and postings-merge principles. The fixed Lucene document supplies a concrete engine contract. The parser, nine records, live-set examples and comparison counts are original. No Lucene parser or query engine is reproduced.
Make a prediction, then check
Does processing the shortest postings list first change an AND query result?
Learning objectives
- Define operator precedence and live-document complement, then separate semantics from execution cost.
- Run the original small corpus and explain a failure case.
Prerequisites & connections
Explore related knowledge →References
- An Introduction to Information Retrieval — online draft, April 1, 2009
Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2009 - BooleanClause.Occur — Lucene 9.12.3 core API
Apache Lucene contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Viewed physical PDF43/48/78/133/134/158/159/193; read PDF38/44/49/155/189/192 text. Inverted/positional indexes, Boolean merge, variable bytes, lexical vectors and evaluation; not a whole-book review. Read MUST/FILTER/SHOULD/MUST_NOT definitions; pure MUST_NOT is not a complete query. Original teaching grammar is separate. 4 paired equations and four explained exercises. Truth tables, exhaustive small sorted intersections, precedence, live-universe complements, parser rejection and4/8 comparison plans checked.
- Truth tables, exhaustive small sorted intersections, precedence, live-universe complements, parser rejection and4/8 comparison plans checked.
- Four computed SVG variants per topic;10 numeric/geometry tests and30 responsive cases passed. Ten selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- An Introduction to Information Retrieval — online draft, April 1, 2009 · Viewed physical PDF43/48/78/133/134/158/159/193; read PDF38/44/49/155/189/192 text. Inverted/positional indexes, Boolean merge, variable bytes, lexical vectors and evaluation; not a whole-book review.
- BooleanClause.Occur — Lucene 9.12.3 core API · Read MUST/FILTER/SHOULD/MUST_NOT definitions; pure MUST_NOT is not a complete query. Original teaching grammar is separate.
Related topics