Skip to content

createElasticsearchKeyset

function createElasticsearchKeyset(input): ElasticsearchKeyset;

Defined in: filters/elasticsearch.ts:473

Build a search_after keyset helper from a sort spec + the field each logical key sorts on. The last sort column MUST be unique (a tiebreaker such as a keyword copy of the id) so the cursor is stable. sort(direction) gives the sort array ("backward" flips every column) and searchAfter(cursor) the matching search_after values. The seek happens in the engine, so it composes with any query (including buildQuery’s). Sort keys without a field in fields are skipped (keep fields complete: search_after must line up with sort).

Parameter Type
input { fields: Record<string, string>; sort: KeysetSortColumn[]; }
input.fields Record<string, string>
input.sort KeysetSortColumn[]

ElasticsearchKeyset

import { createElasticsearchKeyset } from "@xtandard/lib/filters/elasticsearch";
const keyset = createElasticsearchKeyset({
sort: [{ key: "createdAt", order: "desc" }, { key: "id", order: "desc" }], // unique tiebreaker last
fields: { createdAt: "createdAt", id: "id" },
});
keyset.sort(); // → [{ createdAt: { order: "desc" } }, { id: { order: "desc" } }]
keyset.sort("backward"); // → [{ createdAt: { order: "asc" } }, { id: { order: "asc" } }]
keyset.searchAfter(null); // → undefined (first page)
keyset.searchAfter({ createdAt: new Date("2026-06-18T00:00:00Z"), id: "p_9" }); // → [1781740800000, "p_9"]
// in an app: client.search({ index, query, sort: keyset.sort(direction), search_after: keyset.searchAfter(cursor), size: limit + 1 })