Algorithmcore
Most popular completion
Also called popularity-based query completion, MostPopularCompletion.
Suggests the past queries that extend the prefix with the highest log frequency, found by a top-k search in a scored trie.
- Solves
- Query auto-completion
- Time
- O(m + k L log(k L)) expected
- Space
- O(k L) extra
- Where
- L = the length of the longest logged query; k = the number of completions; m = the length of the prefix
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ziv Bar Yossef, Naama Kraus, 2011
Most popular completion is the method that answers a typed prefix with the past queries that start with it and were issued most often. Bar-Yossef and Kraus named it MostPopularCompletion in 2011 and showed that it is the maximum likelihood choice when the next query is assumed to follow the frequencies of the log. This page gives the fast top- search in a trie whose nodes store the largest count below them, the idea of the Completion Trie of Hsu and Ottaviano. The trie page covers the plain data structure, and query auto-completion covers the problem and the methods that use context, time or the user.
In plain words
A search engine remembers every query that people typed and how many times. When you have typed "bin", it looks at all the remembered queries that begin with "bin" and shows the few that were typed most often. The trick is to do this fast without looking at every query. The engine keeps the queries in a tree of letters, where each branch remembers the highest count of any query further down it. It then always follows the branch with the best remembered count, so it walks straight to the most popular queries and skips the branches that cannot win.
The problem
The log is a map from queries to counts: each query is a non-empty string and its count is the number of times it was issued. For a prefix and an integer , return the queries with as a prefix, ordered by count descending, then by the query string ascending, and keep the first . The tie rule makes the answer unique. If is estimated by divided by the total count of the queries that start with , this order is the order of the estimated probability, so the answer is the maximum likelihood top .
The algorithm
Build a trie over the log. Each node stores the count of the query that ends at it (0 if none), , the largest count in its subtree, and , its preorder number in a traversal that visits children in character order, so that preorder numbers sort like the strings. The children of each node are kept sorted by . The search is best-first on a priority queue of nodes and finished queries, with the key , where a finished query has kind 0 and a node kind 1:
MOST-POPULAR(T, p, k) ▷ T: the scored trie of the log- 1
s ← root of T - 2
for each character a of p: - 3
if s has no child a then return the empty list - 4
s ← child a of s - 5
H ← heap with the node entry of s - 6
out ← empty list - 7
while H is not empty and |out| < k: - 8
e ← pop the entry with the smallest key from H - 9
if e is a finished query q then append (q, c(q)) to out; continue - 10
x ← the node of e - 11
if a query q ends at x then push q with key (−c(q), pre(x), 0) - 12
push the first child y of x with key (−best(y), pre(y), 1) - 13
if x ≠ s then push the next sibling z of x with key (−best(z), pre(z), 1) - 14
return out
Lines L12 and L13 follow the first-child and next-sibling links, so each node is pushed once, and a node is only expanded when its best count can still beat every entry in the heap. Building the trie takes one pass over the log to insert the queries and update along each path, one traversal for the preorder numbers, and one sort of the children of each node.
Example
Take a log of seven queries:
| query | count |
|---|---|
| bing | 80 |
| binary search | 50 |
| bm25 | 40 |
| binary search tree | 30 |
| bin packing | 25 |
| bit manipulation | 20 |
| binomial heap | 15 |
For the prefix "bin" and , lines L1 to L4 walk down to the node of "bin", whose best count is 80. Its children in the order of their best counts are "g" (80), "a" (50), " " (25) and "o" (15). The search pops "bin", then "bing" and its finished query, so "bing" (80) is the first answer. Next it expands the ten nodes of "binary search", one character at a time, because their best count 50 is larger than anything else in the heap, and returns "binary search" (50). The node of "binary search" still has the best count 30 below it, so the five nodes of " tree" come next and give "binary search tree" (30). The answer is bing, binary search, binary search tree. The search popped 17 nodes, the nodes on the three paths, and never entered "bin packing" or "binomial heap": their best counts 25 and 15 stayed in the heap behind the answers. For the prefix "bi" and the answer adds bin packing (25) and bit manipulation (20); "bm25" does not start with "bi".
Correctness
The file proofs/correctness.md gives the proof. Preorder numbers in character order sort the nodes like their strings, so the key order of finished queries is the tie order of the problem. The first-child and next-sibling links make a tree over the subtree of in which the keys of nodes grow from parent to successor, because a child cannot have a larger best count than its parent and a later sibling comes later in the sorted order. So when a query is popped, no query with a smaller key can still be hidden below an entry in the heap: that entry would have a smaller key than the popped one. The finished queries therefore leave the heap in the tie order, and the first of them are the answer.
Proof: The best-first trie search returns the top k completions in the tie orderfull
The log is a finite map from non-empty strings (queries) to positive integers (counts). The trie has one node for each prefix of a logged query, and the node of a string is written . For a node , is the largest count of a query in the subtree of , and is the preorder number of in a traversal that visits the children in character order. The tie order on answers is count descending, then query ascending. The answer has the key , and a node has the key . Keys are compared as tuples, and all keys are distinct.
Lemma 1 (preorder is string order). if and only if in string order, where a proper prefix is smaller than its extensions.
Proof. Let . If is a proper prefix of , the traversal visits before every node of its subtree, so , and . Else let be the longest common prefix, with next characters in and in , . The traversal finishes the subtree of before it starts the subtree of exactly when , which holds exactly when .
So the order of the answer keys is the tie order of the page.
Lemma 2 (search tree). In the search, the successors of a popped node are its first child in the order , its next sibling in that order (not followed for the start node ), and the answer that ends at . Every node and every answer of the subtree of is pushed exactly once, and a node successor has a larger key than .
Proof. The first-child and next-sibling links are the left-child, right-sibling form of the subtree of , so each node of the subtree is pushed exactly once, by its parent or by its previous sibling, and each answer once, by its node. For a child of , and , so . A next sibling comes later in the sorted order of the siblings, so its key is larger.
The answer at can have a smaller key than , when its count is . Along a path of the search tree from to a node , the keys increase, so every node on it has .
Theorem 1 (output). For every prefix and every , the search returns the first answers that start with in the tie order, where is the number of logged queries that start with .
Proof. If does not exist, no query starts with and the search returns the empty list. Else, by Lemma 2, the answers that can appear are exactly the queries in the subtree of , which are the queries that start with . We show that they leave the heap in increasing key order. Suppose an answer is popped while an answer with has not been popped. On the search path from to and then to , the first element is pushed, so some element of the path is in the heap at that moment. If , then . If is a node, then by . With the count of , . If the inequality is strict, . If it is an equality, , and with third entry forces . In every case the heap holds a smaller key than when is popped, which is impossible. So the answers come out in increasing key order, which is the tie order by Lemma 1, and the loop stops after answers or when the heap is empty.
Theorem 2 (work). Let be the length of the longest query. The search pops at most nodes.
Proof. If the search returns all answers, it pops at most every node of the subtree of . Each such node lies on the path from to the end of some query, because the trie has no node without a query below it, so there are at most of them. Else the search stops at its -th answer , with count . Let be a popped node, and its string. When is popped, is not, so as in Theorem 1 some element of the path to is in the heap and . By and , this gives as pairs. Let be the answer of the subtree of with the smallest key; its count is . If , then , so is returned, and is on the path from to . If , then by Lemma 1. When is a prefix of , is on the path to . Otherwise every extension of is smaller than , so and is returned. So every popped node lies on the path from to the node of a returned answer. There are at most answers and each path has at most nodes.
Each node pop pushes at most three entries, so the heap never holds more than entries. The search costs expected time to walk down the prefix with hash table lookups, then time for the heap. The test file checks Theorem 1 against a sort of the whole log for every prefix and every on random logs, and checks the bound of Theorem 2.
Complexity
Every node that the search pops lies on the path from to one of the returned queries. A node with a best count above the -th answer has a winner below it, and a node with the same best count but a smaller string either is a prefix of the -th answer or holds only smaller strings, which are returned. So at most nodes are popped, where is the number of queries with the prefix, and each pop pushes at most three entries. With hash tables for the children, the walk down the prefix costs expected time and the search , with extra space for the heap. Building the trie costs time for a log with characters in total and at most children per node, and the trie has at most nodes. The baseline that filters and sorts the whole log costs time for each prefix, for logged queries.
Properties
- Exact. The answer is the exact top of the log under the tie rule, not an approximation.
- Output-sensitive. The work depends on and on the length of the answers, not on the number of queries with the prefix.
- Static scores. The counts are fixed when the trie is built. A change of one count changes on the whole path to the root and the order of siblings along it.
- Deterministic. Equal logs and prefixes give equal answers.
Variants and improvements
- Compact tries. Hsu and Ottaviano store the Completion Trie with path compression, as in a radix tree, and compress the scores; they report about a microsecond per completion with space competitive with gzip of the log. Their Score-Decomposed Trie and RMQ Trie are other layouts with the same output.
- Sorted array and range minimum queries. Sort the queries; the queries with a given prefix form one range, found by binary search. The top of a range come from a range minimum query structure over the negated counts: take the minimum, split the range around it, and keep the parts in a heap. Gog, Pibiri and Venturini build their system on this idea.
- Precomputed lists. Store the top answers at every node, or at every node near the root. A lookup is then a walk down the prefix, at the cost of entries for each stored node.
- Time-sensitive counts. Replace raw counts with counts that decay with age, or with counts predicted for the next hours, so that new and seasonal queries rise. Cai and de Rijke survey these methods.
- Context and personal history. Bar-Yossef and Kraus rerank the popular candidates by their similarity to the previous queries of the session (NearestCompletion), and combine the two scores (HybridCompletion).
- Fuzzy prefixes. Allow a few edits in the prefix, so that a typo in the first letters does not hide the right completions. See noisy channel spelling correction for a model of the errors.
When to use it
Use most popular completion as the first method for any query box with a large log, and as the baseline against which context-aware or learned methods are measured. It needs only counts, it is exact and fast, and for short prefixes the most frequent queries are usually good guesses. It is weak for rare prefixes with few logged queries, for new events that the log has not seen often yet, and when the same prefix means different things to different users.
Pitfalls
- Ties. Many queries share a count, especially rare ones. Without a tie rule the shown list can change from one build to the next.
- Unsafe and private queries. A raw log contains queries that should not be suggested, such as offensive text or personal data. Filter the log before building the trie.
- Stale counts. Counts over a long period favour old queries. Use a time window or decay.
- Updates. Raising one count can reorder siblings on the whole path to the root. Batch the updates and rebuild, or use a structure built for updates.
- Normalization. Decide on case, spaces and Unicode forms before counting, or the counts of one query split over several strings.
- Very short prefixes. For one letter the answers are the global top queries, which are the same for everyone and often not useful. Many systems show nothing until a few letters are typed.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/most-popular-completion/. The authors are listed in prov/PB06E3.jsonl.
"""Most popular completion with a scored trie.
The log maps each past query to its count. For a prefix p, the answer is
the k logged queries that start with p, in the order count descending,
then query string ascending (Python string order). This is the tie rule
of the page.
Each trie node stores the largest count in its subtree (best) and its
preorder number (pre) in a traversal that visits the children in
character order, so pre orders the nodes as their strings sort. The
children of each node are also kept in the order (-best, pre), as in the
Completion Trie of Hsu and Ottaviano (2013). The search is best-first on
a heap with the key (-best, pre, kind): popping a node pushes its first
child and its next sibling, and the query that ends at it.
"""
import heapq
_QUERY = 0 # a finished query sorts before the node with the same string
_NODE = 1
class _Node:
__slots__ = ("children", "order", "count", "query", "best", "pre", "next")
def __init__(self):
self.children = {} # character -> child node
self.order = [] # children sorted by (-best, pre)
self.count = 0 # count of the query that ends here, 0 if none
self.query = None # the query that ends here
self.best = 0 # largest count in the subtree
self.pre = 0 # preorder number in character order
self.next = None # next sibling in the order (-best, pre)
class CompletionTrie:
"""A trie over a query log, with the top-k search of the page."""
def __init__(self, log: dict[str, int]):
self.root = _Node()
self.pops = 0 # node pops of the last call of top_k
for query, count in log.items():
if not isinstance(query, str) or query == "":
raise ValueError("queries must be non-empty strings")
if count <= 0:
raise ValueError("counts must be positive")
node = self.root
node.best = max(node.best, count)
for ch in query:
node = node.children.setdefault(ch, _Node())
node.best = max(node.best, count)
node.count = count
node.query = query
self._number()
def _number(self) -> None:
"""Give preorder numbers in character order, then link the siblings."""
counter = 0
stack = [self.root]
nodes = []
while stack:
node = stack.pop()
node.pre = counter
counter += 1
nodes.append(node)
for ch in sorted(node.children, reverse=True):
stack.append(node.children[ch])
for node in nodes:
node.order = sorted(node.children.values(), key=lambda c: (-c.best, c.pre))
for a, b in zip(node.order, node.order[1:]):
a.next = b
def top_k(self, prefix: str, k: int) -> list[tuple[str, int]]:
"""The k most frequent logged queries that start with prefix."""
self.pops = 0
node = self.root # @line L1
for ch in prefix: # @line L2
child = node.children.get(ch)
if child is None: # @line L3
return []
node = child # @line L4
start = node
heap = [(-start.best, start.pre, _NODE, start)] # @line L5
out: list[tuple[str, int]] = [] # @line L6
while heap and len(out) < k: # @line L7
_, _, kind, x = heapq.heappop(heap) # @line L8
if kind == _QUERY: # @line L9
out.append((x.query, x.count))
continue
self.pops += 1 # @line L10
if x.count > 0: # @line L11
heapq.heappush(heap, (-x.count, x.pre, _QUERY, x))
if x.order: # @line L12
first = x.order[0]
heapq.heappush(heap, (-first.best, first.pre, _NODE, first))
if x is not start and x.next is not None: # @line L13
y = x.next
heapq.heappush(heap, (-y.best, y.pre, _NODE, y))
return out # @line L14
def scan_top_k(log: dict[str, int], prefix: str, k: int) -> list[tuple[str, int]]:
"""The baseline without an index: filter the whole log and sort it."""
hits = [(q, c) for q, c in log.items() if q.startswith(prefix)]
hits.sort(key=lambda qc: (-qc[1], qc[0]))
return hits[: max(k, 0)]
test_most_popular_completion.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/most-popular-completion/. The authors are listed in prov/PB06E3.jsonl.
import random
import pytest
from most_popular_completion import CompletionTrie, scan_top_k
# The log of the example on the page.
LOG = {
"bing": 80,
"binary search": 50,
"bm25": 40,
"binary search tree": 30,
"bin packing": 25,
"bit manipulation": 20,
"binomial heap": 15,
}
def brute(log, prefix, k):
"""Sort the whole log by the tie rule: count descending, then query ascending."""
ranked = sorted(log.items(), key=lambda qc: (-qc[1], qc[0]))
return [qc for qc in ranked if qc[0].startswith(prefix)][:k]
def random_log(rng, size, alphabet, max_len, max_count):
log = {}
while len(log) < size:
n = rng.randint(1, max_len)
q = "".join(rng.choice(alphabet) for _ in range(n))
log[q] = rng.randint(1, max_count)
return log
def test_example_of_the_page():
t = CompletionTrie(LOG)
assert t.top_k("bin", 3) == [("bing", 80), ("binary search", 50), ("binary search tree", 30)]
assert t.top_k("bi", 5) == [
("bing", 80),
("binary search", 50),
("binary search tree", 30),
("bin packing", 25),
("bit manipulation", 20),
]
assert t.top_k("b", 2) == [("bing", 80), ("binary search", 50)]
assert t.top_k("binary", 10) == [("binary search", 50), ("binary search tree", 30)]
assert t.top_k("c", 3) == []
assert t.top_k("bin", 0) == []
def test_tie_rule_uses_the_query_string():
log = {"ab": 5, "aa": 5, "a": 5, "abc": 5, "b": 9}
t = CompletionTrie(log)
assert t.top_k("", 5) == [("b", 9), ("a", 5), ("aa", 5), ("ab", 5), ("abc", 5)]
assert t.top_k("a", 2) == [("a", 5), ("aa", 5)]
@pytest.mark.parametrize("seed", range(40))
def test_every_prefix_matches_brute_force(seed):
rng = random.Random(seed)
alphabet = "abc" if seed % 2 == 0 else "ab c"
log = random_log(rng, rng.randint(1, 40), alphabet, 6, rng.choice([3, 20, 1000]))
t = CompletionTrie(log)
longest = max(len(q) for q in log)
prefixes = {""} | {q[:i] for q in log for i in range(len(q) + 1)}
prefixes |= {"".join(rng.choice(alphabet) for _ in range(rng.randint(1, 4))) for _ in range(20)}
for p in sorted(prefixes):
n_p = sum(1 for q in log if q.startswith(p))
for k in range(0, len(log) + 2):
got = t.top_k(p, k)
assert got == brute(log, p, k) == scan_top_k(log, p, k)
# Every popped node lies on the path from the prefix node to an answer.
assert t.pops <= min(k, n_p) * (longest - len(p) + 1)
def test_rejects_bad_logs():
with pytest.raises(ValueError):
CompletionTrie({"a": 0})
with pytest.raises(ValueError):
CompletionTrie({"": 3})
History
Query suggestion from logs was part of web search engines before the research papers named the method. Bar-Yossef and Kraus defined MostPopularCompletion in 2011 as the maximum likelihood estimator from the log and used it as the baseline for context-sensitive completion. Hsu and Ottaviano studied the data structures for the top- search in 2013 and gave three compact tries. Gog, Pibiri and Venturini returned to the efficiency question in 2020 with an index built on range minimum queries. Cai and de Rijke surveyed the field in 2016.
References
- Ziv Bar-Yossef and Naama Kraus, Context-sensitive query auto-completion, Proceedings of the 20th International Conference on World Wide Web (WWW 2011), 107-116, the definition of MostPopularCompletion as the maximum likelihood estimate of the next query from the frequencies in the log, used as the baseline of the context-sensitive methods NearestCompletion and HybridCompletion
- Bo-June (Paul) Hsu and Giuseppe Ottaviano, Space-efficient data structures for top-k completion, Proceedings of the 22nd International Conference on World Wide Web (WWW 2013), 583-594, the Completion Trie, with the children of each node sorted by score and a best-first search on a priority queue, and the RMQ Trie and the Score-Decomposed Trie; the measured times of about a microsecond per completion
- Fei Cai and Maarten de Rijke, A survey of query auto completion in information retrieval, Foundations and Trends in Information Retrieval 10(4), 273-363, 2016, the chapters on popularity-based methods (heuristic and learned), on time-sensitive and user-sensitive methods, and on efficiency
- Simon Gog, Giulio Ermanno Pibiri and Rossano Venturini, Efficient and effective query auto-completion, Proceedings of the 43rd International ACM SIGIR Conference (SIGIR 2020), arXiv:2005.06213, the top-k completions of a prefix as the k smallest values in a lexicographic range of the sorted log, found by range minimum queries
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag PB06E3 Edit this page History Report an error Markdown