Parse a small search grammar without allowing user text to become backend query syntax or corrupting exact identifiers.
Safe search query parsing: operators, filters and literal identifiers
Separate user text from query instructions
A search box receives untrusted text. Some users want literal terms; others want a quoted phrase or a field filter. Treating every colon, quote or minus sign as an operator makes part numbers and copied error messages disappear. Sending the entire string to an engine's strict query-language parser also exposes backend syntax and brittle error behavior. Define a small public grammar and compile it to typed backend clauses. Keep literal identifier matching available even when the ordinary text analyzer stems or splits words.
Write down the grammar before the parser
For a maintenance archive, allow plain words, double-quoted phrases and one filter of the form site:plant-a. Make the allowed filter names explicit. Put bounds on query bytes, phrase length and operator count before parsing; a syntactically valid query can still consume excessive work. Reject unknown filters rather than silently treating them as authorization. A site filter narrows a search; it cannot grant access to a plant the user is forbidden to see. Corpus permissions must be applied by the server independently of the query.
Compile to data, never to a concatenated query string
The backend should receive structured term, phrase and filter values. It should escape or parameterize them using its own API, not string interpolation into a query-language expression. If an external search service accepts only a query string, encode literal tokens with that service's documented escaping rules and test metacharacters end to end. Do not reuse SQL quoting rules for search-engine syntax. Parse errors should be explicit and safe: show the offending span without echoing private backend diagnostics. Query expansion is a separate, measured step after the literal request is preserved.
Preserve exact tokens and interpretation
Store the raw query, parsed clauses, parser version and final backend request in a protected trace. A serial such as P-47/AC may need both a raw keyword field and a normalized text field; the slash and hyphen should not accidentally become operators. Search analytics can group equivalent grammar versions, but never rewrite a user's identifier into a guessed synonym without retaining an exact branch. When a result seems wrong, retrieval traces reveal whether the parser, analyzer, filter or ranker changed the request.
Test the contract at its boundaries
Build a table of valid and invalid requests: empty input, unmatched quotes, doubled filters, Unicode letters, copied stack traces, 47-word inputs and punctuation-heavy IDs. Check that forbidden sites stay excluded even when the user asks for them. Compare parsed intent with human judgments on realistic query logs after redacting personal data. A permissive fallback that sends a malformed query directly to the engine defeats the parser; return a clear error or treat the whole input as literal text according to one documented rule.
Worked contract
import re
from dataclasses import dataclass
@dataclass(frozen=True)
class SearchRequest:
terms: tuple[str, ...]
phrases: tuple[str, ...]
site: str | None
TOKEN = re.compile(r'"[^"\n]{1,80}"|[^\s"]+')
SITE = re.compile(r"site:([a-z0-9][a-z0-9-]{0,31})$", re.I)
def parse_search(raw_query: str, allowed_sites: set[str]) -> SearchRequest:
if len(raw_query.encode("utf-8")) > 384:
raise ValueError("query too long")
terms, phrases, site = [], [], None
remaining = TOKEN.sub("", raw_query).strip()
if remaining:
raise ValueError("unmatched quote or unsupported syntax")
for token in TOKEN.findall(raw_query):
if token.startswith('"'):
phrases.append(token[1:-1])
elif token.startswith("site:"):
match = SITE.fullmatch(token)
if match is None or site is not None:
raise ValueError("invalid site filter")
site = match.group(1).lower()
if site not in allowed_sites:
raise ValueError("site not available")
else:
terms.append(token)
if not terms and not phrases:
raise ValueError("query needs search text")
if len(terms) + len(phrases) > 47:
raise ValueError("too many clauses")
return SearchRequest(tuple(terms), tuple(phrases), site)
request = parse_search('P-47/AC "seal pressure" site:plant-a', {"plant-a"})
assert request.terms == ("P-47/AC",)
assert request.phrases == ("seal pressure",)
assert request.site == "plant-a"Performance and operating cost
For N query characters, tokenization and parsing take O(N) time and O(N) space. The backend's cost depends on posting-list size, phrase positions, filters and top-K ranking; parsing is rarely the expensive part. The demonstration describes a deliberately narrow grammar, not a full search-language parser. Its caller must still enforce tenant authorization and compile the typed values through the backend's safe query API.
Common Mistakes
- Passing raw user text to a strict backend query-language parser.
- Using a user-supplied site filter as an access-control decision.
- Dropping punctuation from an exact serial number before literal matching.
- Silently falling back to unrestricted search after a syntax error.
Validation drill
Collect 63 redacted archive queries containing IDs, quotes and filters. Label each intended interpretation, then test parser acceptance, exact-token retention and permission enforcement before comparing top-12 recall.
Read next
- Lexical retrieval: analyzers, fields and exact identifiers
- Query expansion: add recall terms without changing the user's question
- Retrieval corpus contracts: identity, permissions and document lifecycle
- Retrieval traces: locate the stage that lost the answer
