FT.* and VSET — vector search¶
HNSW with SIMD INT8 kernels, the RediSearch-shaped FT.* protocol, BM25 and
hybrid retrieval, and Redis 8 vector sets (one set per key — see below). One index per server; L2 and
COSINE, anything else refused at FT.CREATE.
FT.*¶
Pion is wire-compatible with Redis Stack's vector search subset. Commands are dispatched in slow_path.mojo by matching tl (token length) and the first bytes of tp (token pointer).
FT.CREATE¶
FT.CREATE <index> [ON HASH] [PREFIX <n> <prefix>...] [SKIPINITIALSCAN] SCHEMA
<field> VECTOR HNSW|FLAT <count> TYPE FLOAT32 DIM <d> DISTANCE_METRIC L2|COSINE
[M <m>] [EF_CONSTRUCTION <ef>] [EF_RUNTIME <ef>] [INITIAL_CAP <n>] ...
<field> TAG [SEPARATOR <c>] [CASESENSITIVE] [SORTABLE [UNF]] [NOINDEX]
<field> NUMERIC [SORTABLE [UNF]] [NOINDEX]
<field> TEXT | GEO | GEOSHAPE ...
FT.CREATE changes nothing. From 1.0.4 every part of it is applied or
refused. Before, the handler picked out the words it knew and took every other
word for a field name, so an option it did not know answered +OK and changed
nothing (tests/test_ft_differential.py compares every option with
RediSearch's own answer):
- Applied:
ON HASH,PREFIX,SKIPINITIALSCAN; oneVECTORfield withTYPE FLOAT32,DIM,DISTANCE_METRIC L2orCOSINE,EF_CONSTRUCTION;TAGwithSEPARATORandCASESENSITIVE,NUMERIC,TEXT(for BM25), andNOINDEX(the field matches no filter, as in RediSearch).SORTABLE,UNFandMchange nothing Pion answers. - Accepted, with no effect on an answer Pion gives: the full-text index's
options (
LANGUAGE,LANGUAGE_FIELD,SCORE,SCORE_FIELD,PAYLOAD_FIELD,MAXTEXTFIELDS,NOOFFSETS,NOHL,NOFIELDS,NOFREQS,STOPWORDS), aTEXTfield'sWEIGHT,NOSTEMandPHONETIC,INDEXEMPTY,INDEXMISSING,WITHSUFFIXTRIE, theFLATandSVS-VAMANAalgorithms (built as HNSW) and their attributes, andGEOandGEOSHAPEfields, whose queries Pion refuses. -
Refused:
ON JSON,FILTER,TEMPORARY,ASaliases, a vectorTYPEother thanFLOAT32,DISTANCE_METRIC IP, a secondVECTORfield, an unknown option, field type or vector algorithm, a vector attribute count that does not match its attributes, a missingTYPEorDIM,DIM 0, a missing or emptySCHEMA, a field named twice, a field name over 32 bytes, and more than 16 fields besides the vector. The errors are RediSearch's words where it has some. -
Captures
<index>(first token after the command) ashnsw.index_name, and theVECTORfield's name asvector_field_name. - The schema's fields, with their kind,
SEPARATORand flags, go to the shared view (schema_field_*), where every worker's filters read them, and are saved with the index (index-file word 25, bit 10), so a restart keeps them. An index file written before 1.0.4 has no schema: it loads as before, and its filters then read any hash field. DISTANCE_METRIC— resolved in a pre-scan, before any index state is written, so refusing one is a true no-op.L2→distance_metric = 0,COSINE→1, anything else →-ERR unsupported DISTANCE_METRIC. Omitting the keyword givesL2.
The search itself is unchanged either way: the beam kernels compute
query_norm + node_norm - 2·dot, i.e. squared L2 over affinely-quantized
codes, so L2 is what this engine has always answered. COSINE is
implemented by L2-normalizing the FP32 vector at ingest and the query at
quantization time — on unit vectors, L2 ordering is cosine ordering.
It is done there and not in the distance function because the quantizer is
affine with an offset: an offset cancels in a difference but not in a dot
product, so a cosine computed from quantized dots would be wrong. The metric
is persisted in index-file header word 24 (a warm restart that forgot it
would query a normalized graph with a raw query) and published to
SharedHNSWView.pre_distance_metric so a cross-worker HSET normalizes the
same way the querying worker will.
- Sets
hnsw.index_ready = True. - Subsequent multi-field HSET calls will route the matching field to the HNSW index.
- The hashes already in the keyspace are indexed too, as RediSearch does:
every hash whose vector field has
DIMfloat32s, on every worker. The worker that ranFT.CREATEindexes its own before it answers+OK; the others index theirs at their next housekeeping tick (tens of milliseconds). The server log says[vector] FT.CREATE: indexed N existing hashes from worker W's keyspace in M ms.SKIPINITIALSCAN, placed beforeSCHEMA, turns this off: only hashes written afterwards are indexed. Re-issuingFT.CREATEfor the index being built adds nothing, since a hash already in it is skipped. Over a large keyspace this blocks the worker while it runs, asFT.OPTIMIZEdoes. PREFIX <n> <prefix> …(from 1.0.3). Only a hash whose key starts with one of the prefixes is indexed, as in RediSearch, whether it was written beforeFT.CREATEor after:- The match is byte for byte and case-sensitive, and a key equal to a prefix matches. Several prefixes are ORed.
PREFIX 0, an empty prefix, or noPREFIXat all means every key.- A hash renamed out of the prefixes leaves the index, and one renamed in joins it.
- A write outside the prefixes is not this index's, so it is not counted in
vector_unindexed_writeseither. - The list is saved in the index file, so a restart keeps it.
- At most 16 prefixes of up to 63 bytes each. A longer list, a longer
prefix, or a count that is not a number is refused, and the
FT.CREATEchanges nothing. FT.CREATEwith a different prefix list replaces the index, as a different name orDIMdoes. The new index then takes the hashes its list covers. Re-issuing the same list changes nothing.
Before 1.0.3, PREFIX was accepted and not applied, so an index took every
hash with its vector field and DIM. An index file written before 1.0.3
holds no list, so it keeps answering for every key until FT.DROPINDEX
followed by FT.CREATE. A client that re-creates its index at startup with
a PREFIX replaces it once, and the new index is built from the hashes
under the prefix.
Before 1.0.1, FT.CREATE indexed only what was written after it, so an index
created over existing documents answered [0]. That included the restart
of an index whose DIM differs from the server's --dim. Its file is not
restored, and re-issuing FT.CREATE after the restart is the way back.
HSET (multi-field, fast path)¶
- Handled infast_path.mojo when num_args >= 6 and (num_args - 2) % 2 == 0.
- Each field is stored in the HASH in keyspace.
- If a field's name matches vector_field_name and its byte length equals hnsw.dim * 4, it is routed to hnsw.add_vector(key_id, fp32_ptr).
- Non-vector fields (id, metadata, …) are stored normally in the hash.
- Returns :N\r\n where N = number of fields written.
FT.SEARCH¶
FT.SEARCH <index> "<prefilter>=>[KNN <k> @<field> $blob [EF_RUNTIME <ef>] [AS score]]"
PARAMS 2 blob <float32_bytes> [FILTER ...] [RETURN ...] [NOCONTENT] [WITHSCORES]
[SORTBY <field> [ASC|DESC]] [LIMIT <offset> <count>] [DIALECT 2] [TIMEOUT <ms>]
<index> must be the index this server holds, registered by FT.CREATE or
FT.OPTIMIZE and removed by FT.DROPINDEX. Another name gets
no such index (or, when another index is served, an error naming it). Before
1.0.4, after an FT.DROPINDEX or a refused FT.CREATE, FT.SEARCH answered
from the vectors the dropped definition kept routing while FT.INFO said
Unknown index name.
- Extracts k from the query's KNN clause, and EF_RUNTIME <ef> if present
(else hnsw.ef_runtime). Resolves the query's $<param> (and an EF_RUNTIME
$<param>) against PARAMS by name; the vector must be hnsw.dim * 4 bytes.
- Calls hnsw.search_fp32_scored(blob_ptr, k, dist_scores, ef_query) for the k
nearest. KNN 0 returns an empty result.
- SORTBY <field> [ASC|DESC] then orders those k hits: by the KNN score
(its AS alias or __<field>_score; DESC reverses), or by a schema field,
NUMERIC as a number, TAG and TEXT by their bytes. As in RediSearch, documents
without the field come last in both directions, and ties go by document
order (reversed by DESC). A field that is not in the schema is refused
(Property ... not loaded nor in schema). Before 1.0.4 SORTBY was read and
dropped: the hits came back by distance whatever was asked.
- LIMIT <offset> <count> then takes the page, and the reply's total is
every hit, as in RediSearch. Both numbers must be integers of 0 or more.
Without LIMIT, every hit is returned (KNN 20 returns 20). Before 1.0.4 the
offset was ignored (LIMIT 2 3 answered with the first three), and the total
was the page's size.
- Without SORTBY, Pion returns the hits by distance. RediSearch returns them
in its internal document order, so a LIMIT page without SORTBY holds
different hits on the two. Clients that page (RedisVL, LangChain) send
SORTBY on the score.
- Options that change nothing a KNN query answers are accepted: DIALECT,
TIMEOUT, and the text query's VERBATIM, NOSTOPWORDS, INORDER, SLOP,
LANGUAGE, SCORER, EXPANDER, PAYLOAD, INFIELDS, SUMMARIZE and
HIGHLIGHT. INKEYS, GEOFILTER, WITHPAYLOADS, WITHSORTKEYS and
EXPLAINSCORE are refused, and so is any other option (RediSearch's
Unknown argument `X`). Before 1.0.4 an option FT.SEARCH did not know was
skipped, so INKEYS and GEOFILTER answered as if absent.
- A document past its key's TTL is gone, as for any read: the search expires
it (Redis's lazy expiry) and does not return it. It used to come back until
the active sweep reached the key.
- Every query is read as DIALECT 2. RediSearch 8 defaults to dialect 1, where
the KNN syntax is an error; clients send DIALECT 2.
- After an automatic build the graph's hits are scored from the FP32 rows the
build keeps, so the scores are exact. They came from the INT8 codes, a little
off the true distance, when no vector had been written since the build.
- Returns RediSearch's reply. In RESP2:
*(1 + N*(1 + W + C))\r\n :N\r\n
[for each result:
$<len>\r\n<doc key>\r\n
(WITHSCORES) $1\r\n0\r\n ← the query's text score, as below
(unless NOCONTENT) *2M\r\n <M field/value pairs>
]
W is 1 with WITHSCORES, C is 0 with NOCONTENT (or RETURN 0). The fields are:
RETURN n field [AS name] ...: the named hash fields, renamed byAS. The KNN score is the field named by the clause'sASalias, or__<vector field>_scorewithout one, and comes first when named, as in RediSearch. A field the hash lacks is left out.ncounts every token after it; a bad or short count answers RediSearch's own error (Bad arguments for RETURN: ...).- No RETURN: the KNN score (under the clause's
ASalias, or__<vector field>_score), then every field of the hash, the embedding included, as RediSearch sends. A caller that needs only the keys should passRETURN 1 idorNOCONTENT, and one that reads the score by name should name it withAS. WITHSCORESreports the query's text score, not the distance, as RediSearch does:0for*=>[KNN …]. RediSearch reports a text score for a filter prefix too; Pion computes none and reports0.
On a RESP3 connection (HELLO 3, and redis-py 8 by default) the reply is RediSearch's map: attributes *0, format +STRING, results (one map per document: id, score with WITHSCORES as a double, extra_attributes with the fields above unless NOCONTENT, values *0), total_results, warning *0. The BM25 and HYBRID forms of FT.SEARCH, and FT.HYBRID, are Pion's own syntax: they ignore RETURN, NOCONTENT and WITHSCORES and send id (the doc hash's own id field, when it has one) and score.
This shape is emitted at every worker count. Each document's key comes from
the slot→key map every worker shares (hk_keys_buf, written by the ingest
that took the slot), then the answering worker's own slot map (see "The
index's records are not keys"), then the numeric slot id. Before 1.0.6 the
shared map held keys of up to 31 bytes, so under -w N a longer key was the
slot number (0, 17) on every worker but the one that ingested it: every
LangChain key (doc:<index>:<uuid hex>) and nearly every RedisVL key. Field values come
from the doc hash on the worker answering the query. Under -w N the keyspace
is per worker, so a worker that does not hold a document's hash sends none of
its fields, as Redis leaves out a field a document lacks: it never substitutes
the key or slot for a field it cannot see.
tests/test_ft_search_replies.py checks every case against RediSearch's
replies (--oracle runs the cases against RediSearch itself).
FT.INFO¶
Returnsindex_name and num_docs (the documents FT.SEARCH answers from: the built graph's, plus any it answers exactly, so before a build every vector ingested, less the documents that left: deleted, expired, renamed or given a new vector; 0 before any): a 4-element array of bulk strings in RESP2, a map with num_docs an integer in RESP3. Returns -ERR Unknown index name for a name the server does not hold. RediSearch's FT.INFO has more fields (attributes, sizes, statistics); Pion sends these two.
num_docs counts documents with a vector. RediSearch also counts a hash it indexed only by its other fields (one without the vector field, or whose vector was removed). Before 1.0.4 num_docs counted every slot ever written, so it only grew: 40 documents, two of them deleted and one updated, read 41.
FT._LIST¶
The names of the indexes this server holds: the one index, or none. RedisVL calls it to see whether an index exists beforeFT.CREATE. Added in 1.0.4; it was an unknown command.
FT.OPTIMIZE¶
Builds the graph now, from everything in the FP32 ingest buffer. Callshnsw.build_index_from_shared() (if shared buffer has data) or hnsw.build_index() (local). After build: compact_vectors() reorders vectors in BFS order, publish_to_shared() makes the index available to other workers via SharedHNSWView. Returns +OK. With nothing ingested since the served index was built, it keeps that index and returns +OK.
FT.OPTIMIZE is optional: without it the index answers exactly and then builds itself (see "Searching without FT.OPTIMIZE" below). Send it to have the graph built at once, and to say that ingest is over.
After FT.OPTIMIZE, ingest is over. The FP32 ingest buffer is freed after the build, so an HSET issued after FT.OPTIMIZE is stored as a hash but not indexed: FT.SEARCH will not find it, and INFO counts it as vector_unindexed_writes. This holds after a restart too (see below). For incremental inserts, leave FT.OPTIMIZE out (the automatic build keeps the buffer, across restarts as well), or FT.DROPINDEX → re-ingest everything → FT.OPTIMIZE again. Re-issuing FT.CREATE for the index being served changes nothing, and does not reopen ingest — unless that index is empty (built with no documents), which has nothing to protect: then ingest opens again. FT.OPTIMIZE with no index defined (no FT.CREATE, nothing ingested, no graph) answers Unknown index name; it used to build and serve an empty index named by its argument, under which the real index's FT.CREATE would not open ingest.
Deletions do follow the keyspace (#46). A document leaves the results when its hash leaves the keyspace, by DEL, UNLINK, expiry, FLUSHALL, or a write that replaces the key. It also leaves when the vector leaves the document: an HSET of a new vector, an HDEL of the field, or a field TTL. Writing the vector it already has (the same bytes: an ingest script run twice) keeps it indexed. A renamed document leaves too: its slot names the old key, and after the build the new name is not indexed. Before the build, a renamed, copied (COPY) or restored (RESTORE) hash is ingested under its new name, as an HSET would be.
Mechanics:
- The hash records its slot. The slot dies with the hash, or with its vector field.
- A dead slot is one byte in an array all workers share, so a search on any worker skips it at once.
- The graph is not changed. Dead nodes still route the beam, as HNSW soft deletes do, and FT.SEARCH filters them out of the results. The KNN path widens its candidates until it has k live documents.
- Each worker records the slots it killed as <build id>:<slot>, in a table beside the keyspace (WAL record 47). The WAL, snapshots and replication carry it.
- A restart applies the members whose build id matches the loaded index. Each FT.OPTIMIZE draws a new build id, saved in index header word 31.
The index's records are not keys¶
Each document the index ingests gets a slot, and the worker that ingested it keeps the slot's key in a slot map, beside the keyspace. BM25 and RERANK read it to find the document's hash on that worker. After a restart it links each hash back to its slot, which is what lets a DEL after the restart remove the document. The dead slots above live beside it. FT.SEARCH names documents from the map every worker shares, which holds keys of any length since 1.0.6 (a key over 31 bytes is a heap copy its 32-byte entry points to).
A slot map describes one slot numbering. FT.DROPINDEX, or an FT.CREATE that replaces the index, starts the numbering again, and every worker drops its own map and dead slots before it next records anything (WAL record 48). Before 1.0.6 only the worker that ran the command did. Under -w N another worker's map then named slots of the new index: that worker answered a new long-key document with an old document's key, and after a restart it linked its old hashes to the new index's slots, so deleting an old document took a new one out of the results. A restart also links a hash only when the shared map names its key, so a record of an older numbering links nothing.
Until 1.0.5 both were keys: __hk__<slot> held the document's key, and the set __hk_dead__ held the dead slots. So DBSIZE, KEYS, SCAN, RANDOMKEY and INFO's key count saw twice the keys a client wrote, and a client's own key named __hk__7 was overwritten when slot 7 was ingested. Deleting them, with SCAN MATCH and DEL or any cleanup of unknown keys, left every document deleted after the next restart in the results. FLUSHALL keeps both tables, as it keeps the index; its documents die with their hashes.
Persistence: WAL records 46 (a slot's key), 47 (a dead slot) and 48 (clear the dead slots, or the whole map); every snapshot and BGREWRITEAOF writes them. A data directory an older server wrote loads as it is (see doc/operations.md §3c). tests/test_vector_slot_map.py checks the keyspace, a client's __hk__7, restarts through the WAL, SAVE and BGREWRITEAOF, DD, -w 4, a replica, and both upgrade paths.
Searching without FT.OPTIMIZE¶
A stock Redis client (RedisVL, LangChain, VectorDBBench's own) creates the index, HSETs documents and searches. It never sends FT.OPTIMIZE. The index answers it anyway (src/network/vector_auto.mojo):
- Before a graph is built,
FT.SEARCHis exact. It scans the FP32 ingest buffer and returns the true nearest neighbours, in the same reply shape and score units as the graph (1 - cosunder COSINE, squared L2 under L2). Deleted documents andFILTERare honoured;EF_RUNTIMEdoes not apply. The scan reads every vector once per query, so it slows as the index grows. - Once inserts pause for 200 ms, the graph builds in the background. One worker runs the same build
FT.OPTIMIZEruns, on its own thread, while every worker keeps answering exactly. That worker then publishes the graph, and the thread saves it topion.hnsw.0. The server log says[vector] auto-build: indexing N vectorsandN vectors indexed in M ms. - Vectors written after that build are found at once. The ingest buffer is kept.
FT.SEARCHscans the vectors written since the build exactly and merges them with the graph's results. Both sides are scored from the FP32 rows for that merge: the graph's own scores come from INT8 codes, which are close to the exact distance but not equal to it, and a merge needs both sides on the same footing. When they reach a tenth of the index and inserts pause again, the graph is rebuilt the same way. During a rebuild, searches are exact again.
INFO reports the state process-wide: vector_index (none, empty, exact, building, graph, or graph+delta), vector_graph_rows, vector_exact_rows, vector_auto_builds and vector_unindexed_writes.
Costs and limits:
- The kept buffer costs dim × 4 bytes per vector: 6 KB at 1536 dimensions, about 300 MB at 50K. An explicit FT.OPTIMIZE frees it.
- An exact scan reads every vector it covers, so an index searched before its graph exists, or during a rebuild, serves far fewer queries per second than the graph does. Measured on an EPYC 8124P at 500K vectors of 1,536 dimensions, one worker and one client (benchmarks/results/2026-10-20-linux-epyc-8124p/drop_in/): a query takes 1.6 ms from the graph alone, 3.8 ms with 10,000 vectors written since the build (about 0.18 ms per 1,000), and 190 ms during the 84 s rebuild of 551,000.
- Link lanes: the build uses one per online CPU, from 4 to 16. PION_BUILD_LANES=N overrides it.
- A restart leaves the index as its build left it (from 1.0.2). The graph loads from pion.hnsw.0 and serves, and an automatically built index keeps indexing. Before any worker serves, each one puts back the FP32 rows of the documents it holds: the file has the graph, not those rows. The documents written after the build, or rewritten since, become the delta again. A vector written after the restart is found at once, and the index rebuilds itself as before. The log says [vector] index '<name>' loaded (N vectors, built automatically): it keeps indexing. The refill reads every hash once, and the server answers nothing until it is done, as during WAL replay. If none of the index's documents is in the keyspace (a server run with --no-wal), the index serves as loaded, with ingest closed.
- An index FT.OPTIMIZE built keeps ingest closed after a restart, as that command says. A vector written to it afterwards is stored, not indexed, and counted in vector_unindexed_writes. The log says loaded (N vectors) with ingest closed. A file written before 1.0.2 loads the same way, because it does not record how its index was built. FT.DROPINDEX followed by FT.CREATE indexes every hash in the keyspace, and the file of the next automatic build records it. Before 1.0.2, every index loaded closed after a restart, and the writes it missed were not counted.
Only the worker whose graph holds the published index rebuilds it. FT.CREATE, FT.DROPINDEX and FT.OPTIMIZE wait for a running build. A worker that borrowed another worker's index gives its buffers back before it builds or resets. It used to build straight into them.
FT.DROPINDEX¶
DD also deletes the index's documents, as in RediSearch: each live document's key goes as with DEL (WAL record, WATCH). Any drop also clears every worker's slot map and dead slots, which describe the dropped index (each worker clears its own; before 1.0.6 only the worker that ran the drop did). Ingest pauses for the drop: an HSET on another worker meanwhile is stored, not indexed, as RediSearch has no index then. Before 1.0.4 DD was read and dropped, so the documents stayed. Under -w N each worker holds its own documents, and one worker cannot delete another's: DD is refused there. Any other argument is refused (it used to drop the index anyway).
Calls hnsw.reset_index() — zeroes num_nodes, resets entry_point_id = -1, clears node_map and visited_map, resets index_name_len = 0, resets global_min/max to calibration defaults, sets index_ready = False. Returns +OK. It also deletes the index file, pion.hnsw.0, so a restart does not bring the dropped index back. Before 1.0.2 the file stayed, and after a restart FT.INFO and FT.SEARCH answered from the dropped index. An FT.CREATE that replaces an index of another name or DIM deletes its file the same way.
FT.HYBRID — Hybrid Vector + BM25 Search¶
Executes parallel BM25 full-text search and HNSW vector search in a single command, fusing results via Reciprocal Rank Fusion (RRF).Parameters:
- <index> — index name (must match a previously created FT.CREATE index)
- <text_query> — plain-text query string for BM25 scoring
- <vector_blob> — raw Float32 bytes (dim * 4 bytes) for HNSW nearest-neighbor search
- K <k> — number of results to return (default 10)
- ALPHA <a> — blending weight: 0.0 = full vector, 1.0 = full BM25, 0.5 = equal (default 0.5)
Fusion formula (RRF):
wherevec_weight = 1 - alpha and bm25_weight = alpha. The constant 60 is the standard RRF damping factor.
Internal behavior:
1. HNSW search with K * 4 oversampling (retrieves 4x candidates for quality)
2. BM25 search with K * 4 oversampling
3. RRF fusion: candidates from both result sets are merged by document ID, scored, and sorted
4. Top-K results returned
Response format: Standard FT.SEARCH RESP2 format with RRF combined scores (same wire format as FT.SEARCH).
Example:
redis-cli FT.HYBRID myindex "machine learning transformers" \
$(python3 -c "import struct; print(struct.pack('1536f', *[0.01]*1536))") \
K 10 ALPHA 0.5
See also: doc/embeddings.md for text embedding generation.
BM25 and hybrid retrieval¶
Pion includes a built-in BM25 full-text search engine, constructed during FT.OPTIMIZE from the TEXT schema field declared in FT.CREATE. The schema's first TEXT field is the one indexed.
Ingest — two paths, both work¶
The doc set is union(HNSW nodes, FT.ADDTEXT registrations), so a corpus needs no vectors at all to be lexically searchable.
FT.CREATE idx SCHEMA body TEXT vec VECTOR HNSW 6 TYPE FLOAT32 DIM 512 DISTANCE_METRIC L2
# (a) text-only — no vector, no embedding sidecar needed
FT.ADDTEXT idx 7 "the --fa-window flag caps the sliding attention span"
# (b) alongside a vector — any key shape; the slot map the vector HSET
# writes is what points BM25 at the text
HSET doc:7 vec <512 float32 LE>
HSET doc:7 body "the --fa-window flag caps the sliding attention span"
FT.OPTIMIZE idx # builds the inverted index — required after ingest
FT.SEARCH idx BM25 "sliding attention" K 10
FT.ADDTEXT doc ids must be non-negative integers to be BM25-indexable — hits are returned as integer ext_ids, so a string id has nothing to map back to. A string id still works for FT.SEARCHTEXT, which searches the semantic-cache HNSW rather than the inverted index.
FT.SEARCHTEXT runs against that separate, per-worker semantic-cache graph, and it comes with limits the BM25 side does not have: 10,000 documents per worker, no clearing on FT.DROPINDEX, and O(N²) bulk ingest. See doc/embeddings.md § "FT.ADDTEXT / FT.SEARCHTEXT limits and gotchas" before building a text knowledge store on it.
FT.SEARCH … BM25 against an index with no inverted index at all returns an error naming the missing step, not an empty array — a caller could not otherwise tell "never optimized" from "matched nothing". A built index that genuinely matches nothing still returns the empty form.
BM25 state is per-worker and not persisted: it is never published to the shared view and save_to_disk does not carry it, so re-run FT.OPTIMIZE after a restart, and prefer -w 1 for lexical workloads.
One index per server¶
A Pion server holds one index at a time. FT.CREATE overwrites the shared schema, FT.OPTIMIZE rebuilds the single HNSW graph and the single set of BM25 postings, and pion.hnsw.0 is written by whichever index optimized last. Running FT.OPTIMIZE on index B therefore replaces whatever was serving index A — including a concurrently-serving production index.
This is the contract, not a bug, and a query naming the displaced index gets an error rather than *0, which would be indistinguishable from a genuine miss:
FT.SEARCH clobA BM25 "alpha bravo"
-ERR index 'clobA' has no BM25 postings - this server holds one index at a time and the
current postings belong to 'clobB' (a later FT.OPTIMIZE replaced them); re-ingest
and FT.OPTIMIZE 'clobA' to serve it again
FT.SEARCH clobA *=>[KNN 2 @vec $q] PARAMS 2 q <blob>
-ERR index 'clobA' is not the index loaded on this server - it holds one index at a
time and currently serves 'clobB' (a later FT.CREATE/FT.OPTIMIZE replaced it)
FT.HYBRID refuses the same way rather than quietly degrading to a vector-only result scored against another index's postings. Index names are compared byte-exactly (case-sensitive), matching the pre-existing KNN check. The BM25 [<index>]: N terms, M docs log line names its index so a cross-index rebuild is identifiable after the fact.
Recovery is what the error says: re-ingest the displaced index's documents and re-run FT.OPTIMIZE for it. Ownership is recorded at build time, so FT.CREATE B alone does not displace A's postings — only FT.OPTIMIZE does.
Operational consequence: do not point a scratch/probe index at a server that is serving a real one. A 2-document probe's FT.OPTIMIZE replaces a 300-passage index.
Indexing¶
- Built automatically by
FT.OPTIMIZE, from scratch each time - Tokenization: hard-split on whitespace and structural punctuation (
" ' \( ) [ ] { } < > | \ , ; : ! ?); the remaining punctuation (- . _ + = * / & % @ # ~ $ ^) is trimmed from token edges but **kept inside** a token, so--fa-windowindexes asfa-windowrather thanfa+window`. Tokens are lowercased and hashed with FNV-1a. Index-time and query-time tokenization go through one function and cannot drift. - No caps. Vocabulary and per-document term count grow on demand, and token length is unbounded.
Scoring¶
- BM25 with defaults
k1 = 1.2,b = 0.75, tunable per query (see below) - IDF:
log(1 + (N - df + 0.5) / (df + 0.5))where N = documents in the BM25 doc set, df = document frequency. This is Lucene's non-negative form;rank_bm25'sBM25Okapiinstead useslog(N - df + 0.5) - log(df + 0.5)with an epsilon floor for negative values. The difference is measurable but small (see below). - Lookup: term hashes are stored sorted; query terms resolve by binary search, O(log V) per term. Up to 64 unique query terms are scored.
Querying¶
FT.SEARCH <index> BM25 "query text" [K <k>] [K1 <f>] [B <f>]
FT.HYBRID <index> "query text" <vector blob> [K <k>] [ALPHA <a>] [K1 <f>] [B <f>]
K1 (0–100) sets term-frequency saturation; B (0–1) sets length normalisation, where B 0 disables it entirely. Out-of-range values are rejected rather than silently clamped. Omitting both reproduces the documented defaults exactly.
Metadata filters¶
FT.SEARCH filters a KNN query by TAG and NUMERIC fields declared in the FT.CREATE schema. Every form below is applied; anything else is refused with an error, never ignored.
FT.SEARCH idx "*=>[KNN 10 @vec $v]" FILTER @price:[10 50] PARAMS 2 v <blob> DIALECT 2
FT.SEARCH idx "(@price:[10 50] @cat:{a|b})=>[KNN 10 @vec $v]" PARAMS 2 v <blob> DIALECT 2
FT.SEARCH idx "*=>[KNN 10 @vec $v]" FILTER price 10 50 PARAMS 2 v <blob> # RediSearch legacy
FT.SEARCH idx "*=>[KNN 10 @vec $v]" FILTER cat=a PARAMS 2 v <blob>
FT.SEARCH idx "*=>[KNN 10 @vec $v]" FILTER price [10 50] PARAMS 2 v <blob>
- NUMERIC
@f:[lo hi]is inclusive;(makes a bound exclusive (@f:[(10 20],FILTER f (10 20);-inf/+infwork, and so does1e400(infinity, as strtod reads it). Bounds and values are doubles: a stored value that is not a number fails the clause. Before 1.0.4(was refused and both sides were Float32, which cannot tell 1,700,000,014 from 1,700,000,000, so a timestamp range matched documents outside it. - TAG values are tag lists, as RediSearch indexes them: the stored value is split at the field's
SEPARATOR(,by default), each tag is trimmed of spaces, and@f:{a}matches a document with the taga, ignoring ASCII case unless the field isCASESENSITIVE.@f:{a|b}matches either. Before 1.0.4 the whole value was compared byte for byte, soa,bmatched neither{a}nor{b}, and{A}did not matcha. RediSearch also folds non-ASCII letters; Pion folds only A-Z. - The field must be in the index's schema, and of the clause's kind: a range on a NUMERIC field, a tag set on a TAG field. Anything else is RediSearch's error (
Unknown field,Expected a NUMERIC field,Field is not a numeric field). ANOINDEXfield matches nothing. An index loaded from a file written before 1.0.4 has no saved schema: there a clause reads any hash field, as before. - Up to 4 clauses, ANDed — several
FILTERarguments and/or clauses in the query prefix.|between clauses (OR) and negation are refused. - Filtering is applied to KNN candidates, widening the candidate set (4×, 16×, … up to 16,384 or the whole index) until
krows pass — a selective filter costs more search, it does not silently return fewer rows while matches exist below that bound. Each candidate's fields are read from its hash, so a field changed after a build counts at once. The build used to keep a copy of each document's TAG and NUMERIC values, which went stale when a field changed. - Field names are case-sensitive, as in the hash.
FILTER f=value,FILTER @f:[lo hi]andFILTER f [lo hi]are Pion's own forms; RediSearch'sFILTERtakesfield lo hionly.
The query itself must be <prefilter>=>[KNN k @field $param [EF_RUNTIME n] [AS alias]] with the vector in PARAMS by name; an unknown form, an unknown vector field, a missing $param or a blob of the wrong size is an error.
Differences from RediSearch¶
tests/test_ft_differential.py sends every FT.* option to Pion and to RediSearch (Redis 8's search module) and compares the answers. Where they differ on purpose, tests/ft_differential_known.tsv says why. Besides what Pion refuses (above), these remain:
FT.CREATEfor the index already served answers+OKand changes nothing; RediSearch answersIndex already exists. Clients re-create defensively, and both answers let them.DISTANCE_METRICmay be left out, and is thenL2; RediSearch requires it.FLUSHALLkeeps the index definition (num_docs0, no hits); RediSearch drops its indexes.- A hash whose NUMERIC field is not a number stays in the index for KNN (a range filter skips it); RediSearch does not index the document at all.
num_docscounts documents with a vector; RediSearch also counts hashes it indexed by their other fields only.- The vector field's name is matched ignoring case (
Vecandvecare one field); RediSearch matches it exactly. - Punctuation in a tag query is read literally (
@f:{x;y}); RediSearch needs it escaped. - Without
SORTBY, hits come back by distance; RediSearch returns them in its internal document order.SORTBYties go by document order: RediSearch numbers a document again on every write, Pion when its vector is written. RETURNof a NUMERIC field returns the bytes stored, asHGETdoes; RediSearch reformats the number (51.0comes back as51).- Every query is read as
DIALECT 2. - Without
LIMIT,FT.SEARCHreturns every KNN hit; RediSearch returns 10 (LIMIT 0 10is its default). Clients sendLIMIT. - FT.INFO sends
index_nameandnum_docsonly.FT.ALTER,FT.AGGREGATE,FT.EXPLAIN,FT.PROFILE,FT.TAGVALS,FT.ALIAS*,FT.CONFIG,FT.SPELLCHECK,FT.SYN*,FT.DICT*,FT.SUG*andFT.CURSORare unknown commands. A query without aKNNclause (*,@cat:{a}) is refused.
Scores are the index metric's distance for each returned row — squared L2 under L2, 1 - cos under COSINE — computed from the stored vectors (FP32 re-rank copy, or the INT8 codes dequantized), not the beam's internal quantized distance. Rows are sorted by that score. From INT8 codes, the score compares them with the query clamped to the calibrated range, because the codes are clipped to it: the calibration (mean ± 8 sigma) leaves an embedding's few near-constant outlier dimensions outside, which cancel between documents but used to add their clipped part to every score.
Vector sets (Redis 8 VSET commands)¶
One vector set per key, created by its first VADD, with its own dimension. Search is exact — every element is scored against the query — so there is no recall loss and nothing to tune, at a cost linear in the set's size. Scores are Redis's: (1 + cos) / 2, where 1 is identical. Options that only steer Redis's HNSW graph (Q8, NOQUANT, BIN, M, EF) are accepted and change nothing; REDUCE, FILTER, VEMB … RAW and VLINKS are refused with an error rather than ignored. Vector sets are WAL-persisted and snapshotted: they survive a restart.
| Command | Redis 8 | Valkey 8 | Pion | Pion path | Notes |
|---|---|---|---|---|---|
| VADD | ✅ | ❌ | ✅ | SLOW | VADD key (FP32 <blob> \| VALUES n v…) <element> [SETATTR json] — :1 new, :0 updated; Q8/NOQUANT/BIN/M/EF/CAS accepted (no effect); REDUCE refused |
| VSIM | ✅ | ❌ | ✅ | SLOW | VSIM key (ELE e \| FP32 blob \| VALUES n v…) [WITHSCORES] [WITHATTRIBS] [COUNT n] [EPSILON d] — exact scan; score (1+cos)/2; FILTER refused |
| VCARD | ✅ | ❌ | ✅ | SLOW | Elements in the set; 0 for a missing key |
| VDIM | ✅ | ❌ | ✅ | SLOW | The set's dimension (fixed by its first VADD) |
| VINFO | ✅ | ❌ | ✅ | SLOW | Redis's nine fields; quant-type f32, graph fields 0 (no graph) |
| VISMEMBER | ✅ | ❌ | ✅ | SLOW | 1 / 0 |
| VSETATTR | ✅ | ❌ | ✅ | SLOW | 1 set, 0 missing key or element; empty string removes |
| VGETATTR | ✅ | ❌ | ✅ | SLOW | JSON string or nil |
| VEMB | ✅ | ❌ | ✅ | SLOW | The stored vector as floats; RAW refused |
| VRANDMEMBER | ✅ | ❌ | ✅ | SLOW | Random element(s); count>0 distinct, count<0 with repeats |
| VREM | ✅ | ❌ | ✅ | SLOW | 1 / 0; the last element removes the key |
| VRANGE | ✅ | ❌ | ✅ | SLOW | VRANGE key start end [count] — lexicographic (-, +, [x, (x) |
| VLINKS | ✅ | ❌ | — | SLOW | Refused: an exact set has no HNSW graph |
Vector sets are separate from FT.* indexes and need no FT.CREATE. Persisted like every other type: VADD/VREM/VSETATTR are WAL-logged and SAVE / BGREWRITEAOF serialize the set.
Engine internals and benchmarks: Vector engine.