From ab1f72ab0af633e92386059311ce6bfb444572ad Mon Sep 17 00:00:00 2001 From: ytkimirti Date: Thu, 15 Oct 2026 14:25:17 +0300 Subject: [PATCH 1/2] fix: export search results as key, score, data rows --- src/lib/export-search-results.test.ts | 24 ++++++++++++----- src/lib/export-search-results.ts | 39 ++++++++++----------------- 2 files changed, 32 insertions(+), 31 deletions(-) diff --git a/src/lib/export-search-results.test.ts b/src/lib/export-search-results.test.ts index 3b1e732..f767054 100644 --- a/src/lib/export-search-results.test.ts +++ b/src/lib/export-search-results.test.ts @@ -40,27 +40,39 @@ describe("exportSearchResults", () => { const redis = fakeRedis({ total: 1, values: { "*": '{"name":"Ann","meta":{"age":3}}' } }) expect(JSON.parse(await content(redis, "json"))).toEqual([ - { key: "k:0", name: "Ann", meta: { age: 3 } }, + { key: "k:0", score: 1, data: { name: "Ann", meta: { age: 3 } } }, ]) - expect(await content(redis, "json", "csv")).toBe("key,meta.age,name\nk:0,3,Ann") + expect(await content(redis, "json", "csv")).toBe( + "key,score,data.meta.age,data.name\nk:0,1,3,Ann" + ) }) test("keeps every digit of integers past 2^53", async () => { const redis = fakeRedis({ total: 1, values: { "*": '{"big":12345678901234567890,"n":1.5}' } }) expect(await content(redis, "json")).toContain('"big": 12345678901234567890,') - expect(await content(redis, "json", "csv")).toBe("key,big,n\nk:0,12345678901234567890,1.5") + expect(await content(redis, "json", "csv")).toBe( + "key,score,data.big,data.n\nk:0,1,12345678901234567890,1.5" + ) }) test("keeps a top-level big integer as the value", async () => { const redis = fakeRedis({ total: 1, values: { "*": "12345678901234567890" } }) - expect(await content(redis, "string")).toContain('"value": 12345678901234567890') - expect(await content(redis, "string", "csv")).toBe("key,value\nk:0,12345678901234567890") + expect(await content(redis, "string")).toContain('"data": 12345678901234567890') + expect(await content(redis, "string", "csv")).toBe("key,score,data\nk:0,1,12345678901234567890") }) test("keeps non-json string values as-is", async () => { const redis = fakeRedis({ total: 1, values: { "*": "plain" } }) - expect(await content(redis, "string", "csv")).toBe("key,value\nk:0,plain") + expect(await content(redis, "string", "csv")).toBe("key,score,data\nk:0,1,plain") + }) + + test("hash fields named key or score don't overwrite the document key", async () => { + const redis = fakeRedis({ total: 1, values: { "*": { key: "field", score: "x" } } }) + + expect(JSON.parse(await content(redis, "hash"))).toEqual([ + { key: "k:0", score: 1, data: { key: "field", score: "x" } }, + ]) }) }) diff --git a/src/lib/export-search-results.ts b/src/lib/export-search-results.ts index f133f90..1b62dec 100644 --- a/src/lib/export-search-results.ts +++ b/src/lib/export-search-results.ts @@ -163,16 +163,14 @@ export const estimateExportBytes = ( return Math.round(perRow * count) } -const serializeJson = (docs: SearchDoc[]): string => { - const rows = docs.map((d) => ({ - key: d.key, - // A top-level big integer is a rawJSON object, but it's a value, not fields - ...(d.data && typeof d.data === "object" && !isRawJSON?.(d.data) - ? (d.data as Record) - : { value: d.data }), - })) - return JSON.stringify(rows, undefined, 2) -} +// Same { key, score, data } shape as SDK query results, so document fields can't +// clobber `key` or `score`. +const serializeJson = (docs: SearchDoc[]): string => + JSON.stringify( + docs.map(({ key, score, data }) => ({ key, score, data })), + undefined, + 2 + ) const flatten = ( value: unknown, @@ -205,32 +203,23 @@ const escapeCsvCell = (value: unknown): string => { return str } +// Columns mirror the JSON rows flattened with dot paths: key, score, data.... const serializeCsv = (docs: SearchDoc[]): string => { - const flatRows = docs.map((d) => { - const out: Record = {} - if (d.data && typeof d.data === "object" && !isRawJSON?.(d.data)) { - flatten(d.data, "", out) - } else { - out.value = d.data - } - return out - }) + const flatRows = docs.map((d) => flatten(d.data, "data", {})) const dataColumns = new Set() for (const row of flatRows) { for (const col of Object.keys(row)) dataColumns.add(col) } - const columns = ["key", ...[...dataColumns].sort()] + const columns = [...dataColumns].sort() const lines: string[] = [] - lines.push(columns.map((c) => escapeCsvCell(c)).join(",")) + lines.push(["key", "score", ...columns].map((c) => escapeCsvCell(c)).join(",")) for (const [i, doc] of docs.entries()) { const row = flatRows[i] - const cells = columns.map((col) => - col === "key" ? escapeCsvCell(doc.key) : escapeCsvCell(row[col]) - ) - lines.push(cells.join(",")) + const cells = [doc.key, doc.score, ...columns.map((col) => row[col])] + lines.push(cells.map((c) => escapeCsvCell(c)).join(",")) } return lines.join("\n") From 2b098924b83f36904cd22bce0ed08ab3455ba89a Mon Sep 17 00:00:00 2001 From: ytkimirti Date: Thu, 15 Oct 2026 14:25:55 +0300 Subject: [PATCH 2/2] fix: stop search export at the offset limit --- .../search/export-results-button.tsx | 32 ++++++++++++++++--- src/lib/export-search-results.test.ts | 21 ++++++++++-- src/lib/export-search-results.ts | 20 ++++++++++-- 3 files changed, 63 insertions(+), 10 deletions(-) diff --git a/src/components/databrowser/components/search/export-results-button.tsx b/src/components/databrowser/components/search/export-results-button.tsx index 2e86b08..50f5cf5 100644 --- a/src/components/databrowser/components/search/export-results-button.tsx +++ b/src/components/databrowser/components/search/export-results-button.tsx @@ -11,6 +11,7 @@ import { estimateExport, estimateExportBytes, exportSearchResults, + MAX_EXPORT_RESULTS, } from "@/lib/export-search-results" import { parseJSObjectLiteral } from "@/lib/utils" import { Button } from "@/components/ui/button" @@ -46,13 +47,15 @@ export const ExportResultsButton = () => { const [progress, setProgress] = useState<{ count: number; bytes: number }>({ count: 0, bytes: 0 }) const [estimate, setEstimate] = useState<{ count: number; sampleDocs: SampleDoc[] }>() const [errorMsg, setErrorMsg] = useState() + const [truncated, setTruncated] = useState(false) const exportControllerRef = useRef() const estimateControllerRef = useRef() const isExporting = status === "exporting" + const exportCount = estimate && Math.min(estimate.count, MAX_EXPORT_RESULTS) const estimatedBytes = estimate - ? estimateExportBytes(estimate.count, estimate.sampleDocs, format) + ? estimateExportBytes(exportCount ?? 0, estimate.sampleDocs, format) : undefined const getFilter = () => parseJSObjectLiteral>(valuesSearch.query) ?? {} @@ -90,6 +93,7 @@ export const ExportResultsButton = () => { setStatus("idle") setProgress({ count: 0, bytes: 0 }) setErrorMsg(undefined) + setTruncated(false) setEstimate(undefined) setOpen(true) void runEstimate() @@ -107,13 +111,14 @@ export const ExportResultsButton = () => { setStatus("exporting") setErrorMsg(undefined) + setTruncated(false) setProgress({ count: 0, bytes: 0 }) const controller = new AbortController() exportControllerRef.current = controller try { - const { content, count, bytes } = await exportSearchResults({ + const { content, count, bytes, truncated } = await exportSearchResults({ searchRedis: redisNoPipeline, readRedis: redis, indexName, @@ -131,8 +136,13 @@ export const ExportResultsButton = () => { ) setProgress({ count, bytes }) + setTruncated(truncated) setStatus("done") - toast({ description: `Exported ${formatResults(count)}` }) + toast({ + description: truncated + ? `Exported the first ${formatResults(count)}, the search limit` + : `Exported ${formatResults(count)}`, + }) } catch (error) { if (error instanceof Error && error.name === "AbortError") { setStatus("idle") @@ -206,11 +216,18 @@ export const ExportResultsButton = () => { {status === "idle" && estimate && estimate.count > 0 && (
- Estimated output: ~{formatResults(estimate.count)} + Estimated output: ~{formatResults(exportCount ?? 0)} {estimatedBytes ? ` ยท ~${bytesLib(estimatedBytes)}` : ""}
)} + {status === "idle" && estimate && estimate.count > MAX_EXPORT_RESULTS && ( +
+ Search can only page through the first {formatResults(MAX_EXPORT_RESULTS)}, so the + export will stop there. Narrow the query to export the rest. +
+ )} + {status === "idle" && estimate?.count === 0 && (
This index has no results to export.
)} @@ -225,6 +242,13 @@ export const ExportResultsButton = () => { )} + {status === "done" && truncated && ( +
+ Stopped at the search limit of {formatResults(MAX_EXPORT_RESULTS)}. Narrow the query + to export the rest. +
+ )} + {status === "error" && errorMsg && (
{errorMsg}
)} diff --git a/src/lib/export-search-results.test.ts b/src/lib/export-search-results.test.ts index f767054..8b57f17 100644 --- a/src/lib/export-search-results.test.ts +++ b/src/lib/export-search-results.test.ts @@ -1,17 +1,21 @@ import type { Redis } from "@upstash/redis" import { describe, expect, test } from "bun:test" -import { exportSearchResults } from "./export-search-results" +import { exportSearchResults, MAX_EXPORT_RESULTS } from "./export-search-results" // Mimics the app's client (automaticDeserialization: false): JSON and string values are raw text. +// SEARCH.QUERY rejects OFFSET above 10,000 like the server does. const fakeRedis = (opts: { total: number; values: Record }) => { const keys = Array.from({ length: opts.total }, (_, i) => `k:${i}`) const raw = (key: string) => opts.values[key] ?? opts.values["*"] return { search: { index: () => ({ - query: async ({ limit, offset }: { limit: number; offset: number }) => - keys.slice(offset, offset + limit).map((key) => ({ key, score: 1 })), + query: async ({ limit, offset }: { limit: number; offset: number }) => { + if (offset > 10_000) throw new Error("ERR value is not an integer or out of range") + return keys.slice(offset, offset + limit).map((key) => ({ key, score: 1 })) + }, + count: async () => ({ count: opts.total }), }), }, json: { get: async (key: string) => raw(key) }, @@ -75,4 +79,15 @@ describe("exportSearchResults", () => { { key: "k:0", score: 1, data: { key: "field", score: "x" } }, ]) }) + + test("stops at the search offset limit instead of failing", async () => { + const exact = await run( + fakeRedis({ total: MAX_EXPORT_RESULTS, values: { "*": "v" } }), + "string" + ) + expect(exact).toMatchObject({ count: MAX_EXPORT_RESULTS, truncated: false }) + + const over = await run(fakeRedis({ total: 12_345, values: { "*": "v" } }), "string") + expect(over).toMatchObject({ count: MAX_EXPORT_RESULTS, truncated: true }) + }) }) diff --git a/src/lib/export-search-results.ts b/src/lib/export-search-results.ts index 1b62dec..cf07347 100644 --- a/src/lib/export-search-results.ts +++ b/src/lib/export-search-results.ts @@ -4,6 +4,10 @@ export type ExportFormat = "csv" | "json" const PAGE_SIZE = 1000 const SAMPLE_SIZE = 50 +// SEARCH.QUERY rejects OFFSET above 10,000 and has no cursor, so only the first +// MAX_OFFSET + PAGE_SIZE results of a query can be read. +const MAX_OFFSET = 10_000 +export const MAX_EXPORT_RESULTS = MAX_OFFSET + PAGE_SIZE type IndexDataType = "string" | "hash" | "json" @@ -65,7 +69,7 @@ export const exportSearchResults = async (opts: { format: ExportFormat signal?: AbortSignal onProgress?: (p: { count: number; bytes: number }) => void -}): Promise<{ content: string; count: number; bytes: number }> => { +}): Promise<{ content: string; count: number; bytes: number; truncated: boolean }> => { const { searchRedis, readRedis, indexName, filter, dataType, format, signal, onProgress } = opts const index = searchRedis.search.index({ name: indexName }) @@ -73,7 +77,7 @@ export const exportSearchResults = async (opts: { let offset = 0 let bytes = 0 - for (;;) { + while (offset <= MAX_OFFSET) { if (signal?.aborted) throw new DOMException("Aborted", "AbortError") // `select: {}` -> NOCONTENT -> returns just { key, score } for each match (the proven path). @@ -103,11 +107,21 @@ export const exportSearchResults = async (opts: { if (rows.length < PAGE_SIZE) break } + // Reading up to the offset cap means there may be more matches. + const truncated = + docs.length === MAX_EXPORT_RESULTS && + (await index.count({ filter }).then( + ({ count }) => count > docs.length, + () => true + )) + + if (signal?.aborted) throw new DOMException("Aborted", "AbortError") + const content = format === "csv" ? serializeCsv(docs) : serializeJson(docs) // Report the actual serialized output size (the running `bytes` above is a raw // approximation used only for live progress and won't match the final file). - return { content, count: docs.length, bytes: new Blob([content]).size } + return { content, count: docs.length, bytes: new Blob([content]).size, truncated } } /**