Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(meilisearch): add document and settings views

Freedom884744df4cbf
diff --git a/apps/desktop/src/components/common/JsonTree.vue b/apps/desktop/src/components/common/JsonTree.vue
index c881c94192..5af0c3684e 100644
--- a/apps/desktop/src/components/common/JsonTree.vue
+++ b/apps/desktop/src/components/common/JsonTree.vue
@@ -2,7 +2,7 @@
import { computed, defineComponent, h, nextTick, ref, shallowRef, watch, type VNodeChild } from "vue";
import { DynamicScroller, DynamicScrollerItem } from "vue-virtual-scroller";
import { ChevronDown, ChevronRight } from "@lucide/vue";
-import { createJsonTreeRoot, getJsonTreeChildren, getVisibleJsonTreeNodes, isJsonTreeContainer, isJsonTreeInitiallyExpanded, jsonTreeContainerKind, jsonTreeContainerSummary, type JsonTreeNode } from "@/lib/common/jsonTree";
+import { createJsonTreeRoot, getJsonTreeChildren, getVisibleJsonTreeNodes, isJsonTreeClosingNode, isJsonTreeContainer, isJsonTreeInitiallyExpanded, jsonTreeContainerKind, jsonTreeContainerSummary, type JsonTreeNode } from "@/lib/common/jsonTree";
import { isLosslessJsonNumber } from "@/lib/common/safeJsonFormat";
defineOptions({ name: "JsonTree" });
@@ -137,12 +137,21 @@ function renderJsonNode(node: JsonTreeNode): VNodeChild {
if (containerValue !== undefined) {
const kind = jsonTreeContainerKind(containerValue);
- rowChildren.push(h("span", { class: `json-tree-bracket is-${kind}` }, kind === "array" ? "[" : "{"), h("span", { class: "json-tree-summary" }, jsonTreeContainerSummary(containerValue, expanded)), h("span", { class: `json-tree-bracket is-${kind}` }, kind === "array" ? "]" : "}"));
+ rowChildren.push(h("span", { class: `json-tree-bracket is-${kind}` }, kind === "array" ? "[" : "{"));
+ if (!expanded) {
+ rowChildren.push(h("span", { class: "json-tree-summary" }, jsonTreeContainerSummary(containerValue)), h("span", { class: `json-tree-bracket is-${kind}` }, kind === "array" ? "]" : "}"));
+ }
} else {
rowChildren.push(highlightedJsonSpan(scalarClass(node.value), scalarText(node.value)));
}
- const children = containerValue !== undefined && expanded ? h("div", { class: "json-tree-children" }, getJsonTreeChildren(node).map(renderJsonNode)) : null;
+ const children =
+ containerValue !== undefined && expanded
+ ? h("div", { class: "json-tree-children" }, [
+ ...getJsonTreeChildren(node).map(renderJsonNode),
+ h("div", { class: "json-tree-row", style: { paddingInlineStart: indent } }, [h("span", { class: `json-tree-bracket json-tree-closing is-${jsonTreeContainerKind(containerValue)}` }, jsonTreeContainerKind(containerValue) === "array" ? "]" : "}")]),
+ ])
+ : null;
return h("div", { key: node.path, class: "json-tree-node", "data-json-path": node.path }, [h("div", { class: "json-tree-row", style: { paddingInlineStart: indent } }, rowChildren), children]);
}
@@ -154,7 +163,7 @@ const JsonTreeRoot = defineComponent({
},
});
-const visibleNodes = computed(() => getVisibleJsonTreeNodes(rootNode.value, isNodeExpanded));
+const visibleNodes = computed(() => getVisibleJsonTreeNodes(rootNode.value, isNodeExpanded, props.virtualized));
function refresh(resetScroll = false) {
if (!props.virtualized) return;
@@ -180,24 +189,31 @@ defineExpose({ expandAll, collapseAll, resetExpansion, refresh });
<DynamicScrollerItem :item="node" :active="active" :size-dependencies="[wordWrap, node.path, node.label, scalarText(node.value), isNodeExpanded(node)]" :data-index="index">
<div class="json-tree-node" :data-json-path="node.path">
<div class="json-tree-row" :style="{ paddingInlineStart: `${node.depth * 16}px` }">
- <button v-if="isJsonTreeContainer(node.value)" type="button" class="json-tree-toggle" :aria-expanded="isNodeExpanded(node)" :aria-label="nodeAccessibleLabel(node)" :title="nodeAccessibleLabel(node)" @click="toggleNode(node)">
- <ChevronDown v-if="isNodeExpanded(node)" class="h-3.5 w-3.5" aria-hidden="true" />
- <ChevronRight v-else class="h-3.5 w-3.5" aria-hidden="true" />
- </button>
- <span v-else class="json-tree-spacer" aria-hidden="true" />
-
- <template v-if="node.parentKind !== 'root'">
- <span v-if="node.parentKind === 'array'" class="json-tree-index">[{{ node.label }}]</span>
- <span v-else class="json-tree-key" v-html="highlightedJson(JSON.stringify(node.label))" />
- <span class="json-tree-punctuation">:</span>
+ <template v-if="isJsonTreeClosingNode(node)">
+ <span class="json-tree-bracket json-tree-closing" :class="`is-${jsonTreeContainerKind(node.value)}`">{{ jsonTreeContainerKind(node.value) === "array" ? "]" : "}" }}</span>
</template>
-
- <template v-if="isJsonTreeContainer(node.value)">
- <span class="json-tree-bracket" :class="`is-${jsonTreeContainerKind(node.value)}`">{{ jsonTreeContainerKind(node.value) === "array" ? "[" : "{" }}</span>
- <span class="json-tree-summary">{{ jsonTreeContainerSummary(node.value, isNodeExpanded(node)) }}</span>
- <span class="json-tree-bracket" :class="`is-${jsonTreeContainerKind(node.value)}`">{{ jsonTreeContainerKind(node.value) === "array" ? "]" : "}" }}</span>
+ <template v-else>
+ <button v-if="isJsonTreeContainer(node.value)" type="button" class="json-tree-toggle" :aria-expanded="isNodeExpanded(node)" :aria-label="nodeAccessibleLabel(node)" :title="nodeAccessibleLabel(node)" @click="toggleNode(node)">
+ <ChevronDown v-if="isNodeExpanded(node)" class="h-3.5 w-3.5" aria-hidden="true" />
+ <ChevronRight v-else class="h-3.5 w-3.5" aria-hidden="true" />
+ </button>
+ <span v-else class="json-tree-spacer" aria-hidden="true" />
+
+ <template v-if="node.parentKind !== 'root'">
+ <span v-if="node.parentKind === 'array'" class="json-tree-index">[{{ node.label }}]</span>
+ <span v-else class="json-tree-key" v-html="highlightedJson(JSON.stringify(node.label))" />
+ <span class="json-tree-punctuation">:</span>
+ </template>
+
+ <template v-if="isJsonTreeContainer(node.value)">
+ <span class="json-tree-bracket" :class="`is-${jsonTreeContainerKind(node.value)}`">{{ jsonTreeContainerKind(node.value) === "array" ? "[" : "{" }}</span>
+ <template v-if="!isNodeExpanded(node)">
+ <span class="json-tree-summary">{{ jsonTreeContainerSummary(node.value) }}</span>
+ <span class="json-tree-bracket" :class="`is-${jsonTreeContainerKind(node.value)}`">{{ jsonTreeContainerKind(node.value) === "array" ? "]" : "}" }}</span>
+ </template>
+ </template>
+ <span v-else :class="scalarClass(node.value)" v-html="highlightedJson(scalarText(node.value))" />
</template>
- <span v-else :class="scalarClass(node.value)" v-html="highlightedJson(scalarText(node.value))" />
</div>
</div>
</DynamicScrollerItem>
@@ -241,6 +257,9 @@ defineExpose({ expandAll, collapseAll, resetExpansion, refresh });
min-height: 24px;
align-items: flex-start;
gap: 4px;
+ padding-block: 2px;
+ /* Fixed line box so the hover background wraps the glyphs symmetrically. */
+ line-height: 20px;
border-radius: var(--dbx-radius-fixed-4);
}
@@ -249,7 +268,7 @@ defineExpose({ expandAll, collapseAll, resetExpansion, refresh });
}
.json-tree-toggle {
- margin-top: 1px;
+ align-self: center;
display: inline-flex;
height: 18px;
width: 18px;
@@ -275,6 +294,14 @@ defineExpose({ expandAll, collapseAll, resetExpansion, refresh });
flex: 0 0 auto;
}
+/* Closing brackets sit in the toggle's slot so they line up with the chevron above. */
+.json-tree-closing {
+ display: inline-flex;
+ width: 18px;
+ flex: 0 0 auto;
+ justify-content: center;
+}
+
.json-tree-key {
color: var(--json-tree-key);
}
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index c3dfd856b6..32358b2938 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -86,6 +86,7 @@ const ZooKeeperKeyBrowser = defineAsyncComponent(() => import("@/components/zook
const ConsulOverview = defineAsyncComponent(() => import("@/components/consul/ConsulOverview.vue"));
const ConsulWorkspace = defineAsyncComponent(() => import("@/components/consul/ConsulWorkspace.vue"));
const DocumentBrowser = defineAsyncComponent(() => import("@/components/document/DocumentBrowser.vue"));
+const MeilisearchIndexView = defineAsyncComponent(() => import("@/components/meilisearch/MeilisearchIndexView.vue"));
const MongoGridFsBrowser = defineAsyncComponent(() => import("@/components/document/MongoGridFsBrowser.vue"));
const MongoBucketBrowser = defineAsyncComponent(() => import("@/components/document/MongoBucketBrowser.vue"));
const VectorBrowser = defineAsyncComponent(() => import("@/components/vector/VectorBrowser.vue"));
@@ -2092,6 +2093,13 @@ defineExpose({
</div>
</template>
+ <!-- Meilisearch index detail -->
+ <template v-else-if="activeTab.mode === 'meilisearch'">
+ <div class="flex-1 min-h-0">
+ <MeilisearchIndexView :key="activeTab.id" :connection-id="activeTab.connectionId" :index="activeTab.sql" />
+ </div>
+ </template>
+
<template v-else-if="activeTab.mode === 'mongo-gridfs'">
<div class="flex-1 min-h-0">
<MongoGridFsBrowser :key="activeTab.id" :connection-id="activeTab.connectionId" :database="activeTab.database" />
diff --git a/apps/desktop/src/components/meilisearch/MeilisearchDocumentsPage.vue b/apps/desktop/src/components/meilisearch/MeilisearchDocumentsPage.vue
new file mode 100644
index 0000000000..852084df52
--- /dev/null
+++ b/apps/desktop/src/components/meilisearch/MeilisearchDocumentsPage.vue
@@ -0,0 +1,801 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
+import type { Component } from "vue";
+import { useI18n } from "vue-i18n";
+import { ArrowDown, ArrowUp, Braces, ChevronLeft, ChevronRight, Copy, Download, LayoutGrid, LoaderCircle, Pencil, Save, Search, Table2, Trash2 } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Switch } from "@/components/ui/switch";
+import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
+import ErrorBanner from "@/components/ui/ErrorBanner.vue";
+import QueryLoadingState from "@/components/common/QueryLoadingState.vue";
+import JsonTree from "@/components/common/JsonTree.vue";
+import RedisJsonEditor from "@/components/redis/RedisJsonEditor.vue";
+import * as api from "@/lib/backend/api";
+import { compactLocalTimestamp, sanitizeExportBaseName, saveTextFile } from "@/lib/export/saveTextFile";
+import { parseDocumentStoreJsonDocument, serializeDocumentStoreId, stringifyDocumentStoreValue } from "@/lib/app/documentJsonValues";
+import { parseJsonPreservingLargeNumbers, safeJsonFormat } from "@/lib/common/safeJsonFormat";
+import { useToast } from "@/composables/useToast";
+
+const props = defineProps<{
+ connectionId: string;
+ index: string;
+}>();
+
+const emit = defineEmits<{
+ "refresh-stats": [];
+}>();
+
+type ViewMode = "json" | "table" | "grid";
+/**
+ * Search hit from the backend: `id` is the primary-key value and `formatted` /
+ * `rankingScore` are requested response metadata — all kept outside `document`,
+ * which is always the pure user payload.
+ */
+type Hit = { id?: unknown; document: Record<string, any>; formatted?: Record<string, any>; rankingScore?: unknown };
+
+const { t } = useI18n();
+const { toast } = useToast();
+
+const q = ref("");
+const filter = ref("");
+const sort = ref("");
+const limit = ref(20);
+const offset = ref(0);
+
+const AUTO_REFRESH_INTERVAL_MS = 7_000;
+const autoRefresh = ref(false);
+let autoRefreshTimer: ReturnType<typeof setInterval> | null = null;
+
+const hybridOpen = ref(false);
+const hybridEnabled = ref(false);
+const hybridEmbedder = ref("");
+const hybridSemanticRatio = ref(0.5);
+const embedders = ref<string[]>([]);
+
+const showRankingScore = ref(false);
+const rankingScoreThreshold = ref(0);
+
+const hits = ref<Hit[]>([]);
+const totalHits = ref(0);
+const processingTimeMs = ref(0);
+const loading = ref(false);
+const error = ref("");
+const viewMode = ref<ViewMode>("json");
+
+const editOpen = ref(false);
+const editingHit = ref<Hit | null>(null);
+const editJson = ref("");
+const editError = ref("");
+const isSaving = ref(false);
+/** True while the canonical document is being fetched for the editor. */
+const editLoading = ref(false);
+
+const deleteOpen = ref(false);
+const deletingHit = ref<Hit | null>(null);
+const isDeleting = ref(false);
+
+const cellDetailOpen = ref(false);
+const cellDetailColumn = ref("");
+const cellDetailValue = ref<unknown>(null);
+
+function openCellDetail(hit: Hit, column: string) {
+ cellDetailColumn.value = column;
+ cellDetailValue.value = cellValue(hit, column);
+ cellDetailOpen.value = true;
+}
+
+/** Plain-text rendering of the cell value with highlight tags removed. */
+const cellDetailText = computed(() => String(stripSearchMarks(cellDetailValue.value) ?? ""));
+
+/** Smart-render a cell value: objects/arrays (or JSON strings) as a tree, plain text otherwise. */
+const cellDetailJson = computed<unknown>(() => {
+ const value = cellDetailValue.value;
+ if (value !== null && typeof value === "object") return value;
+ if (typeof value === "string") {
+ const trimmed = value.trim();
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
+ try {
+ return parseJsonPreservingLargeNumbers(trimmed);
+ } catch {
+ return undefined;
+ }
+ }
+ }
+ return undefined;
+});
+
+const views = computed<Array<{ value: ViewMode; label: string; icon: Component }>>(() => [
+ { value: "json", label: t("meilisearch.viewJson"), icon: Braces },
+ { value: "table", label: t("meilisearch.viewTable"), icon: Table2 },
+ { value: "grid", label: t("meilisearch.viewGrid"), icon: LayoutGrid },
+]);
+
+const page = computed(() => Math.max(0, Math.floor(offset.value / Math.max(1, limit.value))));
+const totalPages = computed(() => Math.max(1, Math.ceil(totalHits.value / Math.max(1, limit.value))));
+const canGoNext = computed(() => offset.value + limit.value < totalHits.value);
+
+const resultSummary = computed(() => t("meilisearch.resultSummary", { count: totalHits.value, time: processingTimeMs.value }));
+
+function escapeHtml(value: string): string {
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+}
+
+function formatCellValue(value: unknown): string {
+ if (value === null || value === undefined) return "";
+ if (typeof value === "object") {
+ try {
+ return stringifyDocumentStoreValue(value, "meilisearch");
+ } catch {
+ return String(value);
+ }
+ }
+ return String(value);
+}
+
+function renderMarkHtml(value: string): string {
+ return escapeHtml(value)
+ .replace(/&lt;mark&gt;/g, "<mark>")
+ .replace(/&lt;\/mark&gt;/g, "</mark>");
+}
+
+/**
+ * Display value for the JSON/grid cards: prefer the hoisted `formatted` payload
+ * so search `<mark>` highlights stay visible. `document` is already the pure
+ * user payload — no name-based stripping, so user fields named `_formatted` or
+ * `_rankingScore` survive untouched.
+ */
+function displayValue(hit: Hit): Record<string, any> {
+ const formatted = hit?.formatted;
+ return formatted && typeof formatted === "object" ? { ...formatted } : { ...hit.document };
+}
+
+/** Deep-remove `<mark>` search highlight tags to reconstruct the stored document. */
+function stripSearchMarks(value: unknown): unknown {
+ if (typeof value === "string") return value.replace(/<\/?mark>/g, "");
+ if (Array.isArray(value)) return value.map(stripSearchMarks);
+ if (value !== null && typeof value === "object") {
+ return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([key, entry]) => [key, stripSearchMarks(entry)]));
+ }
+ return value;
+}
+
+/** The user payload exactly as returned by the search — already free of dbx/Meilisearch metadata. */
+function rawDocument(hit: Hit): Record<string, unknown> {
+ return { ...hit.document };
+}
+
+function rankingScore(hit: Hit): number | null {
+ const value = hit?.rankingScore;
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
+}
+
+const tableColumns = computed(() => {
+ // Columns mirror the stored document fields in their natural order.
+ const keys: string[] = [];
+ const seen = new Set<string>();
+ for (const hit of hits.value) {
+ for (const key of Object.keys(displayValue(hit))) {
+ if (!seen.has(key)) {
+ seen.add(key);
+ keys.push(key);
+ }
+ }
+ }
+ return keys;
+});
+
+/** Grid cards show the stored document as flat field rows instead of a JSON tree. */
+function gridFields(hit: Hit): Array<[string, unknown]> {
+ return Object.entries(displayValue(hit));
+}
+
+function cellValue(hit: Hit, column: string): unknown {
+ const formatted = hit?.formatted;
+ if (formatted && typeof formatted === "object" && column in formatted) return formatted[column];
+ return hit?.document?.[column];
+}
+
+function isMarkedCell(hit: Hit, column: string): boolean {
+ const value = cellValue(hit, column);
+ return typeof value === "string" && value.includes("<mark>");
+}
+
+function markCellHtml(hit: Hit, column: string): string {
+ return renderMarkHtml(String(cellValue(hit, column)));
+}
+
+function cellText(hit: Hit, column: string): string {
+ return formatCellValue(cellValue(hit, column));
+}
+
+function documentId(hit: Hit | null | undefined): string {
+ const id = hit?.id;
+ if (id == null) return "";
+ // The store-id serializer prefixes string ids so the backend keeps their
+ // type — a string primary key like "123" must not round-trip as numeric 123.
+ return serializeDocumentStoreId(id, "meilisearch");
+}
+
+/** Search params shared by the results view and the export. */
+function buildSearchParams(batchLimit: number, batchOffset: number) {
+ return {
+ q: q.value.trim() || null,
+ filter: filter.value.trim() || null,
+ sort: sort.value.trim() || null,
+ limit: Math.max(1, batchLimit),
+ offset: Math.max(0, batchOffset),
+ hybridEmbedder: hybridEnabled.value && hybridEmbedder.value.trim() ? hybridEmbedder.value.trim() : null,
+ hybridSemanticRatio: hybridEnabled.value ? hybridSemanticRatio.value : null,
+ showRankingScore: showRankingScore.value,
+ rankingScoreThreshold: rankingScoreThreshold.value > 0 ? rankingScoreThreshold.value : null,
+ };
+}
+
+async function runSearch() {
+ loading.value = true;
+ error.value = "";
+ try {
+ const result = await api.meilisearchSearchDocuments(props.connectionId, props.index, buildSearchParams(limit.value, offset.value));
+ hits.value = result.hits ?? [];
+ totalHits.value = result.totalHits ?? 0;
+ processingTimeMs.value = result.processingTimeMs ?? 0;
+ } catch (e: any) {
+ hits.value = [];
+ totalHits.value = 0;
+ error.value = e?.message || String(e);
+ } finally {
+ loading.value = false;
+ }
+}
+
+function prevPage() {
+ offset.value = Math.max(0, offset.value - limit.value);
+ void runSearch();
+}
+
+function nextPage() {
+ offset.value = offset.value + limit.value;
+ void runSearch();
+}
+
+/**
+ * Open the editor with the canonical stored document. Search hits may be
+ * partial (`displayedAttributes`) and are never used as the write payload.
+ */
+async function startEdit(hit: Hit) {
+ const id = documentId(hit);
+ if (!id) return;
+ editingHit.value = hit;
+ editError.value = "";
+ editJson.value = "";
+ editOpen.value = true;
+ editLoading.value = true;
+ try {
+ const canonicalJson = await api.meilisearchGetDocument(props.connectionId, props.index, id);
+ editJson.value = safeJsonFormat(canonicalJson, 2);
+ } catch (e: any) {
+ editError.value = e?.message || String(e);
+ } finally {
+ editLoading.value = false;
+ }
+}
+
+/** Download every hit matching the current search as a JSON file of the stored documents. */
+const exporting = ref(false);
+
+const EXPORT_BATCH_SIZE = 1000;
+
+async function exportResults() {
+ if (exporting.value || totalHits.value === 0) return;
+ if (q.value.trim() || hybridEnabled.value || rankingScoreThreshold.value > 0) {
+ toast(t("meilisearch.exportSearchUnsupported"), 5000);
+ return;
+ }
+ exporting.value = true;
+ try {
+ const documents: Record<string, unknown>[] = [];
+ let batchOffset = 0;
+ while (true) {
+ const page = await api.meilisearchFetchDocuments(props.connectionId, props.index, {
+ filter: filter.value.trim() || null,
+ sort: sort.value.trim() || null,
+ limit: EXPORT_BATCH_SIZE,
+ offset: batchOffset,
+ });
+ const batch = page.documents ?? [];
+ documents.push(...batch);
+ if (batch.length < EXPORT_BATCH_SIZE) break;
+ batchOffset += batch.length;
+ }
+ const content = stringifyDocumentStoreValue(documents, "meilisearch", 2);
+ const baseName = sanitizeExportBaseName(props.index) || "search-results";
+ await saveTextFile(content, `${baseName}-${compactLocalTimestamp()}.json`, "JSON", "json");
+ } catch (e: any) {
+ toast(e?.message || String(e), 5000);
+ } finally {
+ exporting.value = false;
+ }
+}
+
+async function copyDocument(hit: Hit) {
+ try {
+ await navigator.clipboard.writeText(stringifyDocumentStoreValue(rawDocument(hit), "meilisearch", 2));
+ toast(t("meilisearch.copied"));
+ } catch {
+ // Clipboard may be unavailable (e.g. permission denied); stay silent.
+ }
+}
+
+async function copyCellDetail() {
+ const value = stripSearchMarks(cellDetailValue.value);
+ const text = value !== null && typeof value === "object" ? stringifyDocumentStoreValue(value, "meilisearch", 2) : String(value ?? "");
+ try {
+ await navigator.clipboard.writeText(text);
+ toast(t("meilisearch.copied"));
+ } catch {
+ // Clipboard may be unavailable (e.g. permission denied); stay silent.
+ }
+}
+
+async function saveEdit() {
+ const id = documentId(editingHit.value);
+ if (!id) {
+ editError.value = t("meilisearch.invalidJson");
+ return;
+ }
+ const parsed = parseDocumentStoreJsonDocument(editJson.value, "meilisearch");
+ if (!parsed.ok) {
+ editError.value = t("meilisearch.invalidJson");
+ return;
+ }
+
+ isSaving.value = true;
+ editError.value = "";
+ try {
+ await api.documentUpdateDocument(props.connectionId, "default", props.index, id, editJson.value);
+ toast(t("meilisearch.documentSaved"));
+ editOpen.value = false;
+ emit("refresh-stats");
+ await runSearch();
+ } catch (e: any) {
+ editError.value = e?.message || String(e);
+ } finally {
+ isSaving.value = false;
+ }
+}
+
+function startDelete(hit: Hit) {
+ deletingHit.value = hit;
+ deleteOpen.value = true;
+}
+
+async function confirmDelete() {
+ const id = documentId(deletingHit.value);
+ if (!id) return;
+ isDeleting.value = true;
+ try {
+ await api.documentDeleteDocument(props.connectionId, "default", props.index, id);
+ toast(t("meilisearch.documentDeleted"));
+ deleteOpen.value = false;
+ emit("refresh-stats");
+ await runSearch();
+ // Deleting the last row of a page leaves offset out of range; step back one page.
+ if (!error.value && hits.value.length === 0 && offset.value > 0) {
+ offset.value = Math.max(0, offset.value - limit.value);
+ await runSearch();
+ }
+ } catch (e: any) {
+ toast(e?.message || String(e), 5000);
+ } finally {
+ isDeleting.value = false;
+ }
+}
+
+function clearAutoRefreshTimer() {
+ if (autoRefreshTimer !== null) {
+ clearInterval(autoRefreshTimer);
+ autoRefreshTimer = null;
+ }
+}
+
+watch(autoRefresh, (enabled) => {
+ clearAutoRefreshTimer();
+ if (enabled) {
+ autoRefreshTimer = setInterval(() => {
+ if (!loading.value) void runSearch();
+ }, AUTO_REFRESH_INTERVAL_MS);
+ }
+});
+
+/** Sortable attributes advertised by the index settings, for the sort picker. */
+const sortableAttributes = ref<string[]>([]);
+
+async function loadIndexSettings() {
+ try {
+ const settings = await api.meilisearchGetIndexSettings(props.connectionId, props.index);
+ const configured = settings?.embedders;
+ embedders.value = configured && typeof configured === "object" && !Array.isArray(configured) ? Object.keys(configured) : [];
+ if (!hybridEmbedder.value && embedders.value.length > 0) {
+ hybridEmbedder.value = embedders.value[0];
+ }
+ const sortable = settings?.sortableAttributes;
+ sortableAttributes.value = Array.isArray(sortable) ? sortable.filter((item): item is string => typeof item === "string") : [];
+ } catch {
+ // Settings discovery is best-effort; the sort/filter inputs stay free-form.
+ sortableAttributes.value = [];
+ }
+}
+
+/** Hover/focus-driven sort picker anchored under the sort input. */
+const sortPickerOpen = ref(false);
+let sortPickerCloseTimer: ReturnType<typeof setTimeout> | undefined;
+
+function openSortPicker() {
+ if (sortPickerCloseTimer !== undefined) {
+ clearTimeout(sortPickerCloseTimer);
+ sortPickerCloseTimer = undefined;
+ }
+ sortPickerOpen.value = true;
+}
+
+function scheduleSortPickerClose() {
+ if (sortPickerCloseTimer !== undefined) clearTimeout(sortPickerCloseTimer);
+ // Small delay so the pointer can travel from the input into the panel.
+ sortPickerCloseTimer = setTimeout(() => {
+ sortPickerOpen.value = false;
+ sortPickerCloseTimer = undefined;
+ }, 150);
+}
+
+type SortDirection = "asc" | "desc";
+
+function parseSortEntries(): Array<{ field: string; direction: SortDirection }> {
+ return sort.value
+ .split(",")
+ .map((entry) => entry.trim())
+ .filter(Boolean)
+ .map((entry) => {
+ const separator = entry.lastIndexOf(":");
+ const field = (separator >= 0 ? entry.slice(0, separator) : entry).trim();
+ const direction: SortDirection =
+ separator >= 0 &&
+ entry
+ .slice(separator + 1)
+ .trim()
+ .toLowerCase() === "desc"
+ ? "desc"
+ : "asc";
+ return { field, direction };
+ })
+ .filter((entry) => entry.field.length > 0);
+}
+
+function sortDirectionFor(field: string): SortDirection | null {
+ return parseSortEntries().find((entry) => entry.field === field)?.direction ?? null;
+}
+
+/** Toggle `field:direction` in the sort expression; clicking the active direction removes it. */
+function toggleSortField(field: string, direction: SortDirection) {
+ const entries = parseSortEntries();
+ const index = entries.findIndex((entry) => entry.field === field);
+ if (index >= 0 && entries[index].direction === direction) entries.splice(index, 1);
+ else if (index >= 0) entries[index] = { field, direction };
+ else entries.push({ field, direction });
+ sort.value = entries.map((entry) => `${entry.field}:${entry.direction}`).join(", ");
+}
+
+onMounted(() => {
+ void runSearch();
+ void loadIndexSettings();
+});
+
+onBeforeUnmount(() => {
+ clearAutoRefreshTimer();
+ if (sortPickerCloseTimer !== undefined) clearTimeout(sortPickerCloseTimer);
+});
+</script>
+
+<template>
+ <div class="h-full flex flex-col overflow-hidden">
+ <!-- Search form -->
+ <div class="p-3 border-b shrink-0">
+ <div class="rounded-lg border bg-card p-3 space-y-3">
+ <div class="relative">
+ <Search class="pointer-events-none absolute top-1/2 left-2.5 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input v-model="q" class="pl-8" :placeholder="t('meilisearch.keywordPlaceholder')" autofocus @keydown.enter="runSearch" />
+ </div>
+
+ <div class="grid grid-cols-2 gap-2 lg:grid-cols-4">
+ <div class="space-y-1 min-w-0">
+ <Label class="text-xs text-muted-foreground">{{ t("meilisearch.filter") }}</Label>
+ <Input v-model="filter" :placeholder="t('meilisearch.filterPlaceholder')" @keydown.enter="runSearch" />
+ </div>
+ <div class="space-y-1 min-w-0">
+ <Label class="text-xs text-muted-foreground">{{ t("meilisearch.sort") }}</Label>
+ <Popover v-model:open="sortPickerOpen">
+ <PopoverAnchor as-child>
+ <Input v-model="sort" class="w-full" :placeholder="t('meilisearch.sortPlaceholder')" @keydown.enter="runSearch" @mouseenter="openSortPicker" @mouseleave="scheduleSortPickerClose" @focus="openSortPicker" />
+ </PopoverAnchor>
+ <PopoverContent side="bottom" align="start" class="w-(--reka-popover-anchor-width) p-0" @open-auto-focus.prevent @mouseenter="openSortPicker" @mouseleave="scheduleSortPickerClose">
+ <p class="border-b px-3 py-2 text-xs text-muted-foreground">{{ t("meilisearch.sortHint") }}</p>
+ <p v-if="sortableAttributes.length === 0" class="px-3 py-2 text-xs text-muted-foreground">{{ t("meilisearch.sortNoAttributes") }}</p>
+ <div v-else class="max-h-56 overflow-y-auto p-1">
+ <div v-for="attr in sortableAttributes" :key="attr" class="flex items-center gap-1 rounded px-2 py-1 hover:bg-muted/50">
+ <span class="min-w-0 flex-1 truncate font-mono text-xs" :title="attr">{{ attr }}</span>
+ <Button variant="ghost" size="icon" class="h-6 w-6 shrink-0" :title="t('meilisearch.sortAsc')" @click="toggleSortField(attr, 'asc')">
+ <ArrowUp class="h-3.5 w-3.5" :class="sortDirectionFor(attr) === 'asc' ? 'text-primary' : 'text-muted-foreground/50'" />
+ </Button>
+ <Button variant="ghost" size="icon" class="h-6 w-6 shrink-0" :title="t('meilisearch.sortDesc')" @click="toggleSortField(attr, 'desc')">
+ <ArrowDown class="h-3.5 w-3.5" :class="sortDirectionFor(attr) === 'desc' ? 'text-primary' : 'text-muted-foreground/50'" />
+ </Button>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ </div>
+ <div class="space-y-1 min-w-0">
+ <Label class="text-xs text-muted-foreground">{{ t("meilisearch.limit") }}</Label>
+ <Input v-model.number="limit" type="number" min="1" @keydown.enter="runSearch" />
+ </div>
+ <div class="space-y-1 min-w-0">
+ <Label class="text-xs text-muted-foreground">{{ t("meilisearch.offset") }}</Label>
+ <Input v-model.number="offset" type="number" min="0" @keydown.enter="runSearch" />
+ </div>
+ </div>
+
+ <div class="flex flex-wrap items-center justify-end gap-2">
+ <div class="flex shrink-0 items-center gap-1.5">
+ <span class="whitespace-nowrap text-xs text-muted-foreground">{{ t("meilisearch.showRankingScore") }}</span>
+ <Switch v-model="showRankingScore" />
+ </div>
+ <div class="flex shrink-0 items-center gap-1.5">
+ <span class="whitespace-nowrap text-xs text-muted-foreground">{{ t("meilisearch.rankingScoreThreshold") }}</span>
+ <Input v-model.number="rankingScoreThreshold" type="number" min="0" max="1" step="0.1" class="h-8 w-16" @keydown.enter="runSearch" />
+ </div>
+ <div class="flex shrink-0 items-center gap-1.5">
+ <span class="whitespace-nowrap text-xs text-muted-foreground">{{ t("meilisearch.autoRefresh") }}</span>
+ <Switch v-model="autoRefresh" />
+ </div>
+
+ <Popover v-model:open="hybridOpen">
+ <PopoverTrigger as-child>
+ <Button variant="outline" size="sm" class="h-8 shrink-0 gap-1.5">
+ {{ t("meilisearch.hybrid") }}
+ <Badge :variant="hybridEnabled ? 'default' : 'secondary'" class="h-4 px-1 text-[10px]">{{ hybridEnabled ? "ON" : "OFF" }}</Badge>
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" class="w-64 space-y-3 p-3">
+ <div class="flex items-center justify-between gap-2">
+ <Label class="text-xs">{{ t("meilisearch.hybrid") }}</Label>
+ <Switch v-model="hybridEnabled" />
+ </div>
+ <div class="space-y-1">
+ <Label class="text-xs text-muted-foreground">{{ t("meilisearch.hybridEmbedder") }}</Label>
+ <div v-if="embedders.length > 0" class="flex flex-wrap gap-1">
+ <button
+ v-for="embedder in embedders"
+ :key="embedder"
+ type="button"
+ class="rounded-md border px-2 py-0.5 font-mono text-xs transition-colors disabled:opacity-50"
+ :class="hybridEmbedder === embedder ? 'border-primary/40 bg-primary/10 text-primary' : 'text-muted-foreground hover:bg-muted/70 hover:text-foreground'"
+ :disabled="!hybridEnabled"
+ @click="hybridEmbedder = embedder"
+ >
+ {{ embedder }}
+ </button>
+ </div>
+ <template v-else>
+ <Input v-model="hybridEmbedder" :disabled="!hybridEnabled" placeholder="default" />
+ <p class="text-xs text-muted-foreground">{{ t("meilisearch.hybridNoEmbedders") }}</p>
+ </template>
+ </div>
+ <div class="space-y-1">
+ <div class="flex items-center justify-between gap-2">
+ <Label class="text-xs text-muted-foreground">{{ t("meilisearch.hybridSemanticRatio") }}</Label>
+ <span class="text-xs tabular-nums text-foreground/80">{{ hybridSemanticRatio.toFixed(2) }}</span>
+ </div>
+ <input v-model.number="hybridSemanticRatio" type="range" min="0" max="1" step="0.05" :disabled="!hybridEnabled" class="w-full accent-primary" />
+ </div>
+ </PopoverContent>
+ </Popover>
+
+ <Button size="sm" class="h-8 shrink-0 gap-1" :disabled="loading" @click="runSearch">
+ <LoaderCircle v-if="loading" class="h-3.5 w-3.5 animate-spin" />
+ <Search v-else class="h-3.5 w-3.5" />
+ {{ t("meilisearch.search") }}
+ </Button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Result toolbar -->
+ <div class="flex items-center gap-3 px-3 pt-3 shrink-0">
+ <span class="text-sm font-semibold">{{ t("meilisearch.results") }}</span>
+ <div class="grid w-auto grid-cols-3 rounded-md bg-muted/40 p-0.5">
+ <button
+ v-for="view in views"
+ :key="view.value"
+ type="button"
+ class="inline-flex h-5 min-w-0 items-center gap-1 truncate whitespace-nowrap rounded-[5px] px-1.5 text-xs transition-colors"
+ :class="viewMode === view.value ? 'bg-background font-semibold text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
+ @click="viewMode = view.value"
+ >
+ <component :is="view.icon" class="h-3 w-3 shrink-0" />
+ <span>{{ view.label }}</span>
+ </button>
+ </div>
+ <div class="flex-1" />
+ <Button v-if="totalHits > 0" variant="ghost" size="sm" class="h-6 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground" :disabled="exporting" @click="exportResults">
+ <Download class="h-3.5 w-3.5" />
+ {{ t("meilisearch.exportResults") }} ({{ totalHits }})
+ </Button>
+ <span v-if="!loading && !error" class="text-muted-foreground text-xs tabular-nums">{{ resultSummary }}</span>
+ </div>
+
+ <!-- Results -->
+ <div class="meilisearch-results flex-1 min-h-0 overflow-y-auto px-3 pb-3 pt-2">
+ <QueryLoadingState v-if="loading" class="h-full" />
+ <ErrorBanner v-else-if="error" :message="error" />
+
+ <div v-else-if="hits.length === 0" class="rounded-md border border-dashed px-3 py-4 text-center text-xs text-muted-foreground">
+ {{ t("meilisearch.empty") }}
+ </div>
+
+ <!-- JSON view -->
+ <div v-else-if="viewMode === 'json'" class="space-y-3">
+ <div v-for="(hit, idx) in hits" :key="documentId(hit) || idx" class="group relative rounded-lg border bg-card p-3">
+ <Badge v-if="rankingScore(hit) != null" variant="secondary" class="absolute right-2 bottom-2 tabular-nums" :title="t('meilisearch.showRankingScore')">
+ {{ rankingScore(hit)!.toFixed(2) }}
+ </Badge>
+ <div class="absolute right-2 top-2 flex items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100">
+ <Button variant="ghost" size="icon" class="h-6 w-7" :title="t('meilisearch.copyDocument')" @click="copyDocument(hit)">
+ <Copy class="h-3.5 w-3.5" />
+ </Button>
+ <Button variant="ghost" size="icon" class="h-6 w-7" :title="t('meilisearch.editDocument')" :disabled="!documentId(hit)" @click="startEdit(hit)">
+ <Pencil class="h-3.5 w-3.5" />
+ </Button>
+ <Button variant="ghost" size="icon" class="h-6 w-7 text-destructive" :title="t('meilisearch.deleteDocument')" :disabled="!documentId(hit)" @click="startDelete(hit)">
+ <Trash2 class="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ <JsonTree :value="displayValue(hit)" :highlight-json="renderMarkHtml" :initial-expanded-depth="2" class="font-mono text-xs" />
+ </div>
+ </div>
+
+ <!-- Table view -->
+ <div v-else-if="viewMode === 'table'" class="rounded-lg border bg-card overflow-hidden">
+ <div class="overflow-x-auto">
+ <table class="w-full table-fixed text-xs">
+ <thead>
+ <tr class="border-b bg-muted/40 text-left text-muted-foreground">
+ <th v-for="column in tableColumns" :key="column" class="px-3 py-2 font-medium">
+ <span class="block truncate" :title="column">{{ column }}</span>
+ </th>
+ <th class="w-24 px-3 py-2" />
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="(hit, idx) in hits" :key="documentId(hit) || idx" class="group/row border-b last:border-b-0 hover:bg-muted/30">
+ <td v-for="column in tableColumns" :key="column" class="cursor-pointer px-3 py-2 font-mono" @click="openCellDetail(hit, column)">
+ <div class="truncate">
+ <span v-if="isMarkedCell(hit, column)" v-html="markCellHtml(hit, column)" />
+ <template v-else>{{ cellText(hit, column) }}</template>
+ </div>
+ </td>
+ <td class="px-2 py-1">
+ <div class="flex items-center justify-end gap-0.5 opacity-0 transition-opacity group-hover/row:opacity-100">
+ <Button variant="ghost" size="icon" class="h-6 w-6" :title="t('meilisearch.copyDocument')" @click="copyDocument(hit)">
+ <Copy class="h-3.5 w-3.5" />
+ </Button>
+ <Button variant="ghost" size="icon" class="h-6 w-6" :title="t('meilisearch.editDocument')" :disabled="!documentId(hit)" @click="startEdit(hit)">
+ <Pencil class="h-3.5 w-3.5" />
+ </Button>
+ <Button variant="ghost" size="icon" class="h-6 w-6 text-destructive" :title="t('meilisearch.deleteDocument')" :disabled="!documentId(hit)" @click="startDelete(hit)">
+ <Trash2 class="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <!-- Grid view -->
+ <div v-else class="grid grid-cols-2 gap-4 lg:grid-cols-3">
+ <div v-for="(hit, idx) in hits" :key="documentId(hit) || idx" class="group relative rounded-lg border bg-card px-4 py-3.5">
+ <Badge v-if="rankingScore(hit) != null" variant="secondary" class="absolute right-2 bottom-2 tabular-nums" :title="t('meilisearch.showRankingScore')">
+ {{ rankingScore(hit)!.toFixed(2) }}
+ </Badge>
+ <div class="absolute right-2 top-2 flex items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100">
+ <Button variant="ghost" size="icon" class="h-6 w-7" :title="t('meilisearch.copyDocument')" @click="copyDocument(hit)">
+ <Copy class="h-3.5 w-3.5" />
+ </Button>
+ <Button variant="ghost" size="icon" class="h-6 w-7" :title="t('meilisearch.editDocument')" :disabled="!documentId(hit)" @click="startEdit(hit)">
+ <Pencil class="h-3.5 w-3.5" />
+ </Button>
+ <Button variant="ghost" size="icon" class="h-6 w-7 text-destructive" :title="t('meilisearch.deleteDocument')" :disabled="!documentId(hit)" @click="startDelete(hit)">
+ <Trash2 class="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ <dl class="space-y-2">
+ <div v-for="[key, value] in gridFields(hit)" :key="key" class="flex cursor-pointer items-baseline gap-3 rounded px-1.5 py-1 text-xs hover:bg-muted/40" @click="openCellDetail(hit, key)">
+ <dt class="w-28 shrink-0 truncate text-right text-muted-foreground" :title="key">{{ key }}</dt>
+ <dd class="min-w-0 flex-1 truncate font-mono" :title="formatCellValue(stripSearchMarks(value))">
+ <span v-if="isMarkedCell(hit, key)" v-html="markCellHtml(hit, key)" />
+ <template v-else>{{ formatCellValue(stripSearchMarks(value)) }}</template>
+ </dd>
+ </div>
+ </dl>
+ </div>
+ </div>
+ </div>
+
+ <!-- Pagination -->
+ <div class="h-9 flex items-center justify-end gap-1 px-3 border-t shrink-0 text-xs text-muted-foreground">
+ <Button variant="ghost" size="icon" class="h-5 w-5" :disabled="offset <= 0" @click="prevPage">
+ <ChevronLeft class="h-3 w-3" />
+ </Button>
+ <span class="tabular-nums">{{ page + 1 }} / {{ totalPages }}</span>
+ <Button variant="ghost" size="icon" class="h-5 w-5" :disabled="!canGoNext" @click="nextPage">
+ <ChevronRight class="h-3 w-3" />
+ </Button>
+ </div>
+
+ <!-- Edit dialog -->
+ <Dialog v-model:open="editOpen">
+ <DialogContent class="sm:max-w-2xl h-[70vh] max-h-[70vh] flex flex-col">
+ <DialogHeader>
+ <DialogTitle>{{ t("meilisearch.editDocument") }}</DialogTitle>
+ </DialogHeader>
+ <div class="flex-1 min-h-0 overflow-hidden rounded-md border bg-muted/20">
+ <QueryLoadingState v-if="editLoading" class="h-full" />
+ <RedisJsonEditor v-else v-model="editJson" class="h-full" :read-only="isSaving" />
+ </div>
+ <div v-if="editError" class="shrink-0 text-xs text-destructive">{{ editError }}</div>
+ <DialogFooter class="shrink-0">
+ <Button variant="outline" :disabled="isSaving" @click="editOpen = false">{{ t("common.cancel") }}</Button>
+ <Button class="gap-1" :disabled="isSaving || editLoading || !editJson" @click="saveEdit">
+ <Save class="h-3.5 w-3.5" />
+ {{ t("common.save") }}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <!-- Cell detail dialog -->
+ <Dialog v-model:open="cellDetailOpen">
+ <DialogContent class="sm:max-w-2xl max-h-[70vh] flex flex-col">
+ <DialogHeader>
+ <DialogTitle class="flex items-center gap-2 font-mono text-sm">
+ <span class="min-w-0 truncate">{{ cellDetailColumn }}</span>
+ <Button variant="ghost" size="icon" class="h-6 w-6 shrink-0" :title="t('common.copy')" @click="copyCellDetail">
+ <Copy class="h-3.5 w-3.5" />
+ </Button>
+ </DialogTitle>
+ </DialogHeader>
+ <div class="min-h-0 flex-1 overflow-auto rounded-md border bg-muted/20">
+ <JsonTree v-if="cellDetailJson !== undefined" :value="cellDetailJson" :highlight-json="renderMarkHtml" class="p-3 font-mono text-xs" />
+ <div v-else class="whitespace-pre-wrap break-words p-3 font-mono text-xs">{{ cellDetailText }}</div>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ <!-- Delete confirm -->
+ <DangerConfirmDialog v-model:open="deleteOpen" :message="t('meilisearch.deleteDocumentMessage')" :confirm-label="t('meilisearch.deleteDocument')" :loading="isDeleting" @confirm="confirmDelete" />
+ </div>
+</template>
+
+<style scoped>
+.meilisearch-results :deep(mark) {
+ background: color-mix(in srgb, var(--primary) 20%, transparent);
+ color: var(--foreground);
+ border-radius: var(--dbx-radius-sm);
+ padding-inline: 0.125rem;
+}
+</style>
diff --git a/apps/desktop/src/components/meilisearch/MeilisearchIndexView.vue b/apps/desktop/src/components/meilisearch/MeilisearchIndexView.vue
new file mode 100644
index 0000000000..65d48de85b
--- /dev/null
+++ b/apps/desktop/src/components/meilisearch/MeilisearchIndexView.vue
@@ -0,0 +1,145 @@
+<script setup lang="ts">
+import { computed, onMounted, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import dayjs from "dayjs";
+import relativeTime from "dayjs/plugin/relativeTime";
+import "dayjs/locale/zh-cn";
+import "dayjs/locale/zh-tw";
+import "dayjs/locale/es";
+import "dayjs/locale/it";
+import "dayjs/locale/ja";
+import "dayjs/locale/ko";
+import "dayjs/locale/pt-br";
+import { Copy, FileText, Settings } from "@lucide/vue";
+import * as api from "@/lib/backend/api";
+import type { MeilisearchIndexOverview } from "@/lib/backend/tauri";
+import { formatBytes } from "@/lib/database/serverMetrics";
+import { useToast } from "@/composables/useToast";
+import MeilisearchDocumentsPage from "./MeilisearchDocumentsPage.vue";
+import MeilisearchSettingsPage from "./MeilisearchSettingsPage.vue";
+
+dayjs.extend(relativeTime);
+
+const DAYJS_LOCALES: Record<string, string> = {
+ "zh-CN": "zh-cn",
+ "zh-TW": "zh-tw",
+ "pt-BR": "pt-br",
+ es: "es",
+ it: "it",
+ ja: "ja",
+ ko: "ko",
+};
+
+const props = defineProps<{
+ connectionId: string;
+ index: string;
+}>();
+
+type ActiveSection = "documents" | "settings";
+
+const { t, locale } = useI18n();
+const { toast } = useToast();
+
+const activeSection = ref<ActiveSection>("documents");
+const overview = ref<MeilisearchIndexOverview | null>(null);
+
+const navSections = computed<Array<{ value: ActiveSection; label: string; icon: typeof FileText }>>(() => [
+ { value: "documents", label: t("meilisearch.documents"), icon: FileText },
+ { value: "settings", label: t("meilisearch.settings"), icon: Settings },
+]);
+
+const updatedAtLabel = computed(() => {
+ const value = overview.value?.updatedAt;
+ if (!value) return "-";
+ return dayjs(value)
+ .locale(DAYJS_LOCALES[locale.value] ?? "en")
+ .fromNow();
+});
+
+async function refreshStats() {
+ try {
+ overview.value = await api.meilisearchGetIndexOverview(props.connectionId, props.index);
+ } catch {
+ // Overview is best-effort; the tab still works without it.
+ }
+}
+
+async function copyText(value: string | null | undefined) {
+ if (!value) return;
+ try {
+ await navigator.clipboard.writeText(value);
+ toast(t("meilisearch.copied"));
+ } catch {
+ // Clipboard may be unavailable (e.g. permission denied); stay silent.
+ }
+}
+
+onMounted(() => {
+ void refreshStats();
+});
+</script>
+
+<template>
+ <div class="h-full flex overflow-hidden">
+ <!-- Left column: index meta + navigation -->
+ <nav class="w-44 shrink-0 border-r flex flex-col gap-1 overflow-y-auto p-2">
+ <div class="px-1 pb-2">
+ <div class="truncate text-sm font-semibold text-foreground" :title="index">{{ index }}</div>
+ <div v-if="overview?.isIndexing" class="mt-0.5 text-xs text-primary">{{ t("meilisearch.isIndexing") }}</div>
+ </div>
+
+ <div class="space-y-2.5 px-1 pb-2 text-xs">
+ <div>
+ <div class="text-muted-foreground">{{ t("meilisearch.uid") }}</div>
+ <div class="mt-0.5 flex items-center gap-1">
+ <span class="min-w-0 truncate font-mono text-foreground/80" :title="overview?.uid ?? index">{{ overview?.uid ?? index }}</span>
+ <button type="button" class="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground" :title="t('common.copy')" @click="copyText(overview?.uid ?? index)">
+ <Copy class="h-3 w-3" />
+ </button>
+ </div>
+ </div>
+ <div>
+ <div class="text-muted-foreground">{{ t("meilisearch.updatedAt") }}</div>
+ <div class="mt-0.5 text-foreground/80" :title="overview?.updatedAt ?? undefined">{{ updatedAtLabel }}</div>
+ </div>
+ <div>
+ <div class="text-muted-foreground">{{ t("meilisearch.primaryKey") }}</div>
+ <div class="mt-0.5 flex items-center gap-1">
+ <span class="min-w-0 truncate font-mono text-foreground/80" :title="overview?.primaryKey ?? undefined">{{ overview?.primaryKey ?? "-" }}</span>
+ <button v-if="overview?.primaryKey" type="button" class="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground" :title="t('common.copy')" @click="copyText(overview.primaryKey)">
+ <Copy class="h-3 w-3" />
+ </button>
+ </div>
+ </div>
+ <div>
+ <div class="text-muted-foreground">{{ t("meilisearch.documentCountLabel") }}</div>
+ <div class="mt-0.5 tabular-nums text-foreground/80">{{ overview ? overview.numberOfDocuments : "-" }}</div>
+ </div>
+ <div v-if="overview?.databaseSize != null">
+ <div class="text-muted-foreground">{{ t("meilisearch.databaseSize") }}</div>
+ <div class="mt-0.5 tabular-nums text-foreground/80">{{ formatBytes(overview.databaseSize) }}</div>
+ </div>
+ </div>
+
+ <div class="mx-1 border-t border-border/60" />
+
+ <button
+ v-for="section in navSections"
+ :key="section.value"
+ type="button"
+ class="mt-1 flex items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-xs transition-colors"
+ :class="activeSection === section.value ? 'bg-accent text-foreground font-medium' : 'text-muted-foreground hover:bg-muted/70 hover:text-foreground'"
+ @click="activeSection = section.value"
+ >
+ <component :is="section.icon" class="h-3.5 w-3.5 shrink-0" />
+ <span>{{ section.label }}</span>
+ </button>
+ </nav>
+
+ <!-- Content -->
+ <div class="flex-1 min-h-0 min-w-0 overflow-hidden">
+ <MeilisearchDocumentsPage v-if="activeSection === 'documents'" :connection-id="connectionId" :index="index" @refresh-stats="refreshStats" />
+ <MeilisearchSettingsPage v-else :connection-id="connectionId" :index="index" @refresh-stats="refreshStats" />
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/meilisearch/MeilisearchSettingsPage.vue b/apps/desktop/src/components/meilisearch/MeilisearchSettingsPage.vue
new file mode 100644
index 0000000000..9f74b99732
--- /dev/null
+++ b/apps/desktop/src/components/meilisearch/MeilisearchSettingsPage.vue
@@ -0,0 +1,184 @@
+<script setup lang="ts">
+import { onMounted, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import { Save } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
+import ErrorBanner from "@/components/ui/ErrorBanner.vue";
+import QueryLoadingState from "@/components/common/QueryLoadingState.vue";
+import JsonTree from "@/components/common/JsonTree.vue";
+import RedisJsonEditor from "@/components/redis/RedisJsonEditor.vue";
+import * as api from "@/lib/backend/api";
+import { useToast } from "@/composables/useToast";
+import { useQueryStore } from "@/stores/queryStore";
+
+const props = defineProps<{
+ connectionId: string;
+ index: string;
+}>();
+
+const emit = defineEmits<{
+ "refresh-stats": [];
+}>();
+
+const { t } = useI18n();
+const { toast } = useToast();
+const queryStore = useQueryStore();
+
+const settingsText = ref("");
+const settingsValue = ref<Record<string, any>>({});
+const loading = ref(false);
+const error = ref("");
+const editMode = ref(false);
+const isSaving = ref(false);
+const saveError = ref("");
+
+const clearConfirmOpen = ref(false);
+const isClearing = ref(false);
+const deleteIndexConfirmOpen = ref(false);
+const isDeletingIndex = ref(false);
+
+async function loadSettings() {
+ loading.value = true;
+ error.value = "";
+ try {
+ const settings = await api.meilisearchGetIndexSettings(props.connectionId, props.index);
+ settingsValue.value = settings ?? {};
+ settingsText.value = JSON.stringify(settingsValue.value, null, 2);
+ } catch (e: any) {
+ settingsValue.value = {};
+ settingsText.value = "{}";
+ error.value = e?.message || String(e);
+ } finally {
+ loading.value = false;
+ }
+}
+
+function startEdit() {
+ saveError.value = "";
+ editMode.value = true;
+}
+
+function cancelEdit() {
+ saveError.value = "";
+ editMode.value = false;
+}
+
+async function saveSettings() {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(settingsText.value);
+ } catch {
+ saveError.value = t("meilisearch.invalidJson");
+ return;
+ }
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
+ saveError.value = t("meilisearch.invalidJson");
+ return;
+ }
+
+ isSaving.value = true;
+ saveError.value = "";
+ try {
+ await api.meilisearchUpdateIndexSettings(props.connectionId, props.index, parsed as Record<string, any>);
+ toast(t("meilisearch.settingsSaved"));
+ settingsValue.value = parsed as Record<string, any>;
+ settingsText.value = JSON.stringify(parsed, null, 2);
+ editMode.value = false;
+ } catch (e: any) {
+ saveError.value = e?.message || String(e);
+ } finally {
+ isSaving.value = false;
+ }
+}
+
+async function confirmClearDocuments() {
+ isClearing.value = true;
+ try {
+ await api.meilisearchDeleteAllDocuments(props.connectionId, props.index);
+ toast(t("meilisearch.documentsCleared"));
+ clearConfirmOpen.value = false;
+ emit("refresh-stats");
+ } catch (e: any) {
+ toast(e?.message || String(e), 5000);
+ } finally {
+ isClearing.value = false;
+ }
+}
+
+async function confirmDeleteIndex() {
+ // Capture the owning tab id up front: the delete is awaited, and the user
+ // may switch tabs meanwhile, so reading the active tab afterwards could
+ // close an unrelated tab.
+ const ownerTabId = queryStore.activeTabId;
+ isDeletingIndex.value = true;
+ try {
+ await api.meilisearchDeleteIndex(props.connectionId, props.index);
+ toast(t("meilisearch.indexDeleted"));
+ deleteIndexConfirmOpen.value = false;
+ // The tab may have been closed while the delete was in flight.
+ if (ownerTabId && queryStore.tabs.some((tab) => tab.id === ownerTabId)) queryStore.closeTab(ownerTabId);
+ } catch (e: any) {
+ toast(e?.message || String(e), 5000);
+ } finally {
+ isDeletingIndex.value = false;
+ }
+}
+
+onMounted(() => {
+ void loadSettings();
+});
+</script>
+
+<template>
+ <div class="h-full flex flex-col overflow-hidden">
+ <div class="flex-1 min-h-0 overflow-y-auto p-3 space-y-3">
+ <QueryLoadingState v-if="loading" class="py-8" />
+ <ErrorBanner v-else-if="error" :message="error" />
+
+ <template v-else>
+ <!-- Settings JSON -->
+ <div class="rounded-lg border bg-card p-3 space-y-2">
+ <div class="flex items-center justify-between gap-2">
+ <div class="text-sm font-medium">{{ t("meilisearch.settingsJson") }}</div>
+ <div class="flex items-center gap-1">
+ <template v-if="!editMode">
+ <Button variant="ghost" size="sm" class="h-6 text-xs" @click="startEdit">{{ t("common.edit") }}</Button>
+ </template>
+ <template v-else>
+ <Button variant="ghost" size="sm" class="h-6 text-xs" :disabled="isSaving" @click="cancelEdit">{{ t("common.cancel") }}</Button>
+ <Button size="sm" class="h-6 gap-1 text-xs" :disabled="isSaving" @click="saveSettings">
+ <Save class="h-3 w-3" />
+ {{ t("common.save") }}
+ </Button>
+ </template>
+ </div>
+ </div>
+ <div v-if="!editMode" class="max-h-[60vh] overflow-auto rounded-md border bg-muted/20 p-3 font-mono text-xs">
+ <JsonTree :value="settingsValue" />
+ </div>
+ <div v-else class="h-[60vh] min-h-0 overflow-hidden rounded-md border bg-muted/20">
+ <RedisJsonEditor v-model="settingsText" class="h-full" :read-only="isSaving" />
+ </div>
+ <div v-if="saveError" class="text-xs text-destructive">{{ saveError }}</div>
+ </div>
+
+ <!-- Danger zone -->
+ <div class="rounded-lg border border-destructive/40 bg-destructive/5 p-3 space-y-2">
+ <div class="text-sm font-medium text-destructive">{{ t("meilisearch.dangerZone") }}</div>
+ <div class="flex flex-wrap items-center gap-2">
+ <Button variant="destructive" size="sm" class="h-7 text-xs" @click="clearConfirmOpen = true">
+ {{ t("meilisearch.clearDocuments") }}
+ </Button>
+ <Button variant="destructive" size="sm" class="h-7 text-xs" @click="deleteIndexConfirmOpen = true">
+ {{ t("meilisearch.deleteIndex") }}
+ </Button>
+ </div>
+ </div>
+ </template>
+ </div>
+
+ <DangerConfirmDialog v-model:open="clearConfirmOpen" :message="t('meilisearch.clearDocumentsConfirmMessage')" :confirm-label="t('meilisearch.clearDocuments')" :loading="isClearing" @confirm="confirmClearDocuments" />
+ <DangerConfirmDialog v-model:open="deleteIndexConfirmOpen" :title="t('meilisearch.deleteIndex')" :message="t('meilisearch.deleteIndexConfirmMessage')" :confirm-label="t('meilisearch.deleteIndex')" :loading="isDeletingIndex" @confirm="confirmDeleteIndex" />
+ </div>
+</template>
diff --git a/apps/desktop/src/components/meilisearch/__tests__/MeilisearchDocumentsPage.export.spec.ts b/apps/desktop/src/components/meilisearch/__tests__/MeilisearchDocumentsPage.export.spec.ts
new file mode 100644
index 0000000000..3f24c0033d
--- /dev/null
+++ b/apps/desktop/src/components/meilisearch/__tests__/MeilisearchDocumentsPage.export.spec.ts
@@ -0,0 +1,135 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, nextTick, type Component } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ searchDocuments: vi.fn(),
+ fetchDocuments: vi.fn(),
+ getIndexSettings: vi.fn(),
+ saveTextFile: vi.fn(),
+ toast: vi.fn(),
+}));
+
+function passthrough(tag: string): Component {
+ return defineComponent({
+ inheritAttrs: false,
+ setup(_, { attrs, slots }) {
+ return () => h(tag, attrs, slots.default?.());
+ },
+ });
+}
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({ t: (key: string) => key }),
+}));
+vi.mock("@lucide/vue", () => ({
+ ArrowDown: passthrough("span"),
+ ArrowUp: passthrough("span"),
+ Braces: passthrough("span"),
+ ChevronLeft: passthrough("span"),
+ ChevronRight: passthrough("span"),
+ Copy: passthrough("span"),
+ Download: passthrough("span"),
+ LayoutGrid: passthrough("span"),
+ LoaderCircle: passthrough("span"),
+ Pencil: passthrough("span"),
+ Save: passthrough("span"),
+ Search: passthrough("span"),
+ Table2: passthrough("span"),
+ Trash2: passthrough("span"),
+}));
+vi.mock("@/components/ui/button", () => ({ Button: passthrough("button") }));
+vi.mock("@/components/ui/badge", () => ({ Badge: passthrough("span") }));
+vi.mock("@/components/ui/input", () => ({ Input: passthrough("input") }));
+vi.mock("@/components/ui/label", () => ({ Label: passthrough("label") }));
+vi.mock("@/components/ui/switch", () => ({ Switch: passthrough("div") }));
+vi.mock("@/components/ui/popover", () => ({
+ Popover: passthrough("div"),
+ PopoverAnchor: passthrough("div"),
+ PopoverContent: passthrough("div"),
+ PopoverTrigger: passthrough("div"),
+}));
+vi.mock("@/components/ui/dialog", () => ({
+ Dialog: passthrough("div"),
+ DialogContent: passthrough("div"),
+ DialogFooter: passthrough("div"),
+ DialogHeader: passthrough("div"),
+ DialogTitle: passthrough("div"),
+}));
+vi.mock("@/components/editor/DangerConfirmDialog.vue", () => ({ default: passthrough("div") }));
+vi.mock("@/components/ui/ErrorBanner.vue", () => ({ default: passthrough("div") }));
+vi.mock("@/components/common/QueryLoadingState.vue", () => ({ default: passthrough("div") }));
+vi.mock("@/components/common/JsonTree.vue", () => ({ default: passthrough("div") }));
+vi.mock("@/components/redis/RedisJsonEditor.vue", () => ({ default: passthrough("div") }));
+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
+vi.mock("@/lib/export/saveTextFile", () => ({
+ saveTextFile: mocks.saveTextFile,
+ compactLocalTimestamp: () => "20260101-000000",
+ sanitizeExportBaseName: (value: string) => value,
+}));
+vi.mock("@/lib/backend/api", () => ({
+ meilisearchSearchDocuments: mocks.searchDocuments,
+ meilisearchFetchDocuments: mocks.fetchDocuments,
+ meilisearchGetIndexSettings: mocks.getIndexSettings,
+}));
+
+import MeilisearchDocumentsPage from "@/components/meilisearch/MeilisearchDocumentsPage.vue";
+
+let app: ReturnType<typeof createApp> | undefined;
+let root: HTMLDivElement | undefined;
+
+beforeEach(() => {
+ mocks.getIndexSettings.mockResolvedValue({});
+ mocks.saveTextFile.mockResolvedValue(undefined);
+});
+
+afterEach(() => {
+ app?.unmount();
+ root?.remove();
+ app = undefined;
+ root = undefined;
+ vi.clearAllMocks();
+});
+
+describe("MeilisearchDocumentsPage export", () => {
+ it("uses full-document pagination instead of capped displayed search hits", async () => {
+ const batch = (size: number, from: number) => Array.from({ length: size }, (_, index) => ({ movie_id: from + index, title: `Movie ${from + index}`, internal_notes: `note ${from + index}` }));
+ mocks.searchDocuments.mockResolvedValue({
+ hits: [{ id: 0, document: { movie_id: 0, title: "Movie 0" } }],
+ totalHits: 1000,
+ processingTimeMs: 1,
+ });
+ mocks.fetchDocuments.mockImplementation((_connectionId: string, _index: string, params: { limit: number; offset: number }) => {
+ if (params.offset === 0) return Promise.resolve({ documents: batch(1000, 0), total: 1300 });
+ if (params.offset === 1000) return Promise.resolve({ documents: batch(300, 1000), total: 1300 });
+ return Promise.resolve({ documents: [], total: 1300 });
+ });
+
+ root = document.createElement("div");
+ document.body.append(root);
+ app = createApp(MeilisearchDocumentsPage, { connectionId: "c1", index: "movies" });
+ app.mount(root);
+
+ await vi.waitFor(() => expect(mocks.searchDocuments).toHaveBeenCalledTimes(1));
+ await nextTick();
+
+ const exportButton = Array.from(root.querySelectorAll("button")).find((button) => button.textContent?.includes("meilisearch.exportResults"));
+ expect(exportButton?.textContent).toContain("1000");
+ exportButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+
+ await vi.waitFor(() => expect(mocks.saveTextFile).toHaveBeenCalledTimes(1));
+
+ expect(mocks.searchDocuments).toHaveBeenCalledTimes(1);
+ const offsets = mocks.fetchDocuments.mock.calls.map((call) => (call[2] as { offset: number }).offset);
+ expect(offsets).toEqual([0, 1000]);
+
+ const [content, fileName] = mocks.saveTextFile.mock.calls[0] as [string, string];
+ expect(fileName).toBe("movies-20260101-000000.json");
+ const exported = JSON.parse(content) as Array<Record<string, unknown>>;
+ expect(exported).toHaveLength(1300);
+ // Exported entries are the stored documents, without search metadata.
+ expect(exported[0]).toEqual({ movie_id: 0, title: "Movie 0", internal_notes: "note 0" });
+ expect(exported[1299]).toEqual({ movie_id: 1299, title: "Movie 1299", internal_notes: "note 1299" });
+ });
+});
diff --git a/apps/desktop/src/components/meilisearch/__tests__/MeilisearchDocumentsPage.identity.spec.ts b/apps/desktop/src/components/meilisearch/__tests__/MeilisearchDocumentsPage.identity.spec.ts
new file mode 100644
index 0000000000..d324f7e82d
--- /dev/null
+++ b/apps/desktop/src/components/meilisearch/__tests__/MeilisearchDocumentsPage.identity.spec.ts
@@ -0,0 +1,172 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, nextTick, type Component } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ searchDocuments: vi.fn(),
+ getIndexSettings: vi.fn(),
+ getDocument: vi.fn(),
+ deleteDocument: vi.fn(),
+ toast: vi.fn(),
+}));
+
+function passthrough(tag: string): Component {
+ return defineComponent({
+ inheritAttrs: false,
+ setup(_, { attrs, slots }) {
+ return () => h(tag, attrs, slots.default?.());
+ },
+ });
+}
+
+/** Renders a confirm trigger while open, so tests drive the danger dialog. */
+function confirmDialog(): Component {
+ return defineComponent({
+ inheritAttrs: false,
+ emits: ["confirm", "update:open"],
+ setup(_, { attrs, emit }) {
+ return () => (attrs.open ? h("button", { "data-confirm-dialog": String(attrs.confirmLabel ?? ""), onClick: () => emit("confirm") }, "confirm") : null);
+ },
+ });
+}
+
+/** Editor stub that exposes the current model value as text for assertions. */
+function jsonEditor(): Component {
+ return defineComponent({
+ inheritAttrs: false,
+ setup(_, { attrs }) {
+ return () => h("pre", { "data-json-editor": "true" }, String(attrs.modelValue ?? ""));
+ },
+ });
+}
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({ t: (key: string) => key }),
+}));
+vi.mock("@lucide/vue", () => ({
+ ArrowDown: passthrough("span"),
+ ArrowUp: passthrough("span"),
+ Braces: passthrough("span"),
+ ChevronLeft: passthrough("span"),
+ ChevronRight: passthrough("span"),
+ Copy: passthrough("span"),
+ Download: passthrough("span"),
+ LayoutGrid: passthrough("span"),
+ LoaderCircle: passthrough("span"),
+ Pencil: passthrough("span"),
+ Save: passthrough("span"),
+ Search: passthrough("span"),
+ Table2: passthrough("span"),
+ Trash2: passthrough("span"),
+}));
+vi.mock("@/components/ui/button", () => ({ Button: passthrough("button") }));
+vi.mock("@/components/ui/badge", () => ({ Badge: passthrough("span") }));
+vi.mock("@/components/ui/input", () => ({ Input: passthrough("input") }));
+vi.mock("@/components/ui/label", () => ({ Label: passthrough("label") }));
+vi.mock("@/components/ui/switch", () => ({ Switch: passthrough("div") }));
+vi.mock("@/components/ui/popover", () => ({
+ Popover: passthrough("div"),
+ PopoverAnchor: passthrough("div"),
+ PopoverContent: passthrough("div"),
+ PopoverTrigger: passthrough("div"),
+}));
+vi.mock("@/components/ui/dialog", () => ({
+ Dialog: passthrough("div"),
+ DialogContent: passthrough("div"),
+ DialogFooter: passthrough("div"),
+ DialogHeader: passthrough("div"),
+ DialogTitle: passthrough("div"),
+}));
+vi.mock("@/components/editor/DangerConfirmDialog.vue", () => ({ default: confirmDialog() }));
+vi.mock("@/components/ui/ErrorBanner.vue", () => ({ default: passthrough("div") }));
+vi.mock("@/components/common/QueryLoadingState.vue", () => ({ default: passthrough("div") }));
+vi.mock("@/components/common/JsonTree.vue", () => ({ default: passthrough("div") }));
+vi.mock("@/components/redis/RedisJsonEditor.vue", () => ({ default: jsonEditor() }));
+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
+vi.mock("@/lib/backend/api", () => ({
+ meilisearchSearchDocuments: mocks.searchDocuments,
+ meilisearchGetIndexSettings: mocks.getIndexSettings,
+ meilisearchGetDocument: mocks.getDocument,
+ documentDeleteDocument: mocks.deleteDocument,
+}));
+
+import MeilisearchDocumentsPage from "@/components/meilisearch/MeilisearchDocumentsPage.vue";
+
+let app: ReturnType<typeof createApp> | undefined;
+let root: HTMLDivElement | undefined;
+
+beforeEach(() => {
+ mocks.getIndexSettings.mockResolvedValue({});
+ mocks.getDocument.mockResolvedValue('{"movie_id":"123","title":"Alien","internal_notes":"canonical only"}');
+ mocks.deleteDocument.mockResolvedValue(1);
+ // The search hit is partial: it lacks the `internal_notes` field.
+ mocks.searchDocuments.mockResolvedValue({
+ hits: [{ id: "123", document: { movie_id: "123", title: "Alien" } }],
+ totalHits: 1,
+ processingTimeMs: 1,
+ });
+});
+
+afterEach(() => {
+ app?.unmount();
+ root?.remove();
+ app = undefined;
+ root = undefined;
+ vi.clearAllMocks();
+});
+
+async function mountPage(): Promise<HTMLDivElement> {
+ root = document.createElement("div");
+ document.body.append(root);
+ app = createApp(MeilisearchDocumentsPage, { connectionId: "c1", index: "movies" });
+ app.mount(root);
+ await vi.waitFor(() => expect(mocks.searchDocuments).toHaveBeenCalledTimes(1));
+ await nextTick();
+ return root;
+}
+
+function findButton(container: HTMLElement, title: string): HTMLButtonElement {
+ const button = Array.from(container.querySelectorAll("button")).find((candidate) => candidate.title === title);
+ if (!button) throw new Error(`button not found: ${title}`);
+ return button;
+}
+
+describe("MeilisearchDocumentsPage identity and canonical documents", () => {
+ it("serializes numeric-looking string ids with the store-id serializer on delete", async () => {
+ const container = await mountPage();
+
+ findButton(container, "meilisearch.deleteDocument").dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ const confirm = container.querySelector("[data-confirm-dialog]");
+ confirm?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+
+ await vi.waitFor(() => expect(mocks.deleteDocument).toHaveBeenCalledTimes(1));
+ // The string id "123" must not round-trip as numeric 123.
+ expect(mocks.deleteDocument).toHaveBeenCalledWith("c1", "default", "movies", '__dbx_meilisearch_string_id__"123"');
+ });
+
+ it("edits the canonical document instead of the partial search hit", async () => {
+ const container = await mountPage();
+
+ findButton(container, "meilisearch.editDocument").dispatchEvent(new MouseEvent("click", { bubbles: true }));
+
+ await vi.waitFor(() => expect(mocks.getDocument).toHaveBeenCalledTimes(1));
+ expect(mocks.getDocument).toHaveBeenCalledWith("c1", "movies", '__dbx_meilisearch_string_id__"123"');
+ await vi.waitFor(() => {
+ const editor = container.querySelector("[data-json-editor]");
+ expect(editor?.textContent).toContain("internal_notes");
+ });
+ // The editor content comes from the canonical fetch, not the partial hit.
+ const editor = container.querySelector("[data-json-editor]");
+ expect(editor?.textContent).toContain('"title": "Alien"');
+ });
+
+ it("disables edit and delete when the hit has no identity", async () => {
+ mocks.searchDocuments.mockResolvedValue({ hits: [{ document: { title: "No PK" } }], totalHits: 1, processingTimeMs: 1 });
+ const container = await mountPage();
+
+ expect(findButton(container, "meilisearch.editDocument").disabled).toBe(true);
+ expect(findButton(container, "meilisearch.deleteDocument").disabled).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/components/meilisearch/__tests__/MeilisearchSettingsPage.spec.ts b/apps/desktop/src/components/meilisearch/__tests__/MeilisearchSettingsPage.spec.ts
new file mode 100644
index 0000000000..efc07d3a1e
--- /dev/null
+++ b/apps/desktop/src/components/meilisearch/__tests__/MeilisearchSettingsPage.spec.ts
@@ -0,0 +1,142 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, nextTick, reactive, type Component } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ deleteIndex: vi.fn(),
+ getIndexSettings: vi.fn(),
+ closeTab: vi.fn(),
+ toast: vi.fn(),
+}));
+
+function passthrough(tag: string): Component {
+ return defineComponent({
+ inheritAttrs: false,
+ setup(_, { attrs, slots }) {
+ return () => h(tag, attrs, slots.default?.());
+ },
+ });
+}
+
+/** Renders a confirm trigger while open, so tests drive the danger dialogs. */
+function confirmDialog(): Component {
+ return defineComponent({
+ inheritAttrs: false,
+ emits: ["confirm", "update:open"],
+ setup(_, { attrs, emit }) {
+ return () =>
+ attrs.open
+ ? h(
+ "button",
+ {
+ "data-confirm-dialog": String(attrs.confirmLabel ?? ""),
+ onClick: () => emit("confirm"),
+ },
+ "confirm",
+ )
+ : null;
+ },
+ });
+}
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({ t: (key: string) => key }),
+}));
+vi.mock("@lucide/vue", () => ({ Save: passthrough("span") }));
+vi.mock("@/components/ui/button", () => ({ Button: passthrough("button") }));
+vi.mock("@/components/editor/DangerConfirmDialog.vue", () => ({ default: confirmDialog() }));
+vi.mock("@/components/ui/ErrorBanner.vue", () => ({ default: passthrough("div") }));
+vi.mock("@/components/common/QueryLoadingState.vue", () => ({ default: passthrough("div") }));
+vi.mock("@/components/common/JsonTree.vue", () => ({ default: passthrough("div") }));
+vi.mock("@/components/redis/RedisJsonEditor.vue", () => ({ default: passthrough("div") }));
+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
+vi.mock("@/lib/backend/api", () => ({
+ meilisearchGetIndexSettings: mocks.getIndexSettings,
+ meilisearchDeleteIndex: mocks.deleteIndex,
+}));
+
+const store = reactive({
+ activeTabId: "tab-a" as string | null,
+ tabs: [{ id: "tab-a" }] as Array<{ id: string }>,
+ closeTab: mocks.closeTab,
+});
+
+vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => store }));
+
+import MeilisearchSettingsPage from "@/components/meilisearch/MeilisearchSettingsPage.vue";
+
+let app: ReturnType<typeof createApp> | undefined;
+let root: HTMLDivElement | undefined;
+
+beforeEach(() => {
+ store.activeTabId = "tab-a";
+ store.tabs = [{ id: "tab-a" }];
+ mocks.getIndexSettings.mockResolvedValue({});
+});
+
+afterEach(() => {
+ app?.unmount();
+ root?.remove();
+ app = undefined;
+ root = undefined;
+ vi.clearAllMocks();
+});
+
+async function mountPage(): Promise<HTMLDivElement> {
+ root = document.createElement("div");
+ document.body.append(root);
+ app = createApp(MeilisearchSettingsPage, { connectionId: "c1", index: "movies" });
+ app.mount(root);
+ await vi.waitFor(() => expect(mocks.getIndexSettings).toHaveBeenCalledTimes(1));
+ await nextTick();
+ return root;
+}
+
+async function confirmDeleteIndex(container: HTMLDivElement) {
+ const deleteButton = Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.trim() === "meilisearch.deleteIndex");
+ deleteButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ const confirmButton = container.querySelector("[data-confirm-dialog]");
+ confirmButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+}
+
+describe("MeilisearchSettingsPage index deletion", () => {
+ it("closes the tab that started the delete even after switching tabs mid-flight", async () => {
+ let resolveDelete!: () => void;
+ mocks.deleteIndex.mockImplementation(() => new Promise<void>((resolve) => (resolveDelete = resolve)));
+
+ const container = await mountPage();
+ await confirmDeleteIndex(container);
+ await vi.waitFor(() => expect(mocks.deleteIndex).toHaveBeenCalledTimes(1));
+
+ // The user switches to another tab while the delete is in flight.
+ store.tabs.push({ id: "tab-b" });
+ store.activeTabId = "tab-b";
+
+ resolveDelete();
+ await vi.waitFor(() => expect(mocks.closeTab).toHaveBeenCalledTimes(1));
+
+ expect(mocks.closeTab).toHaveBeenCalledWith("tab-a");
+ expect(mocks.closeTab).not.toHaveBeenCalledWith("tab-b");
+ });
+
+ it("does not close anything when the owning tab is already gone", async () => {
+ let resolveDelete!: () => void;
+ mocks.deleteIndex.mockImplementation(() => new Promise<void>((resolve) => (resolveDelete = resolve)));
+
+ const container = await mountPage();
+ await confirmDeleteIndex(container);
+ await vi.waitFor(() => expect(mocks.deleteIndex).toHaveBeenCalledTimes(1));
+
+ // The user closed the tab themselves while the delete was in flight.
+ store.tabs = [];
+ store.activeTabId = null;
+
+ resolveDelete();
+ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith("meilisearch.indexDeleted"));
+ await nextTick();
+
+ expect(mocks.closeTab).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index 0a59a8e9ec..b5dbb7ec82 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -826,8 +826,13 @@ async function toggle(requestId = beginNavigationRequest()) {
await connectionStore.loadTableGroups(node.connectionId, node.database, node.label, node.schema, node.id);
} else if (node.type === "elasticsearch-index" && node.connectionId) {
await connectionStore.ensureConnected(node.connectionId);
- const tab = queryStore.createTab(node.connectionId, node.database || "default", node.label, "mongo");
- queryStore.updateSql(tab, node.label);
+ if (connectionStore.getConfig(node.connectionId)?.db_type === "meilisearch") {
+ const tab = queryStore.createTab(node.connectionId, node.database || "default", node.label, "meilisearch");
+ queryStore.updateSql(tab, node.label);
+ } else {
+ const tab = queryStore.createTab(node.connectionId, node.database || "default", node.label, "mongo");
+ queryStore.updateSql(tab, node.label);
+ }
} else if (node.type === "vector-collection" && node.connectionId) {
await connectionStore.ensureConnected(node.connectionId);
const collectionRef = (node.meta as { collectionId?: string } | undefined)?.collectionId ?? node.label;
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 2ba1bc72ca..62a3220dab 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -4591,6 +4591,60 @@ export default {
filterPlaceholder: "Filter...",
sortPlaceholder: "Sort...",
},
+ meilisearch: {
+ documents: "Documents",
+ settings: "Settings",
+ search: "Search",
+ keywordPlaceholder: "Search documents...",
+ filter: "Filter",
+ filterPlaceholder: 'status = "published"',
+ sort: "Sort",
+ sortPlaceholder: "field:asc",
+ sortHint: "Separate multiple sort expressions with commas (,)",
+ sortNoAttributes: "No sortable attributes configured for this index",
+ sortAsc: "Ascending",
+ sortDesc: "Descending",
+ limit: "Limit",
+ offset: "Offset",
+ resultSummary: "About {count} results · {time} ms",
+ viewJson: "JSON",
+ viewTable: "Table",
+ viewGrid: "Grid",
+ empty: "No documents found",
+ editDocument: "Edit document",
+ deleteDocument: "Delete document",
+ deleteDocumentMessage: "Delete this document? This action cannot be undone.",
+ documentDeleted: "Document deleted",
+ documentSaved: "Document saved",
+ settingsSaved: "Settings saved",
+ invalidJson: "Invalid JSON",
+ settingsJson: "Settings JSON",
+ dangerZone: "Danger zone",
+ clearDocuments: "Clear all documents",
+ clearDocumentsConfirmMessage: "This removes every document from the index. This action cannot be undone.",
+ documentsCleared: "All documents cleared",
+ deleteIndex: "Delete index",
+ deleteIndexConfirmMessage: "This permanently deletes the index and all its documents.",
+ indexDeleted: "Index deleted",
+ isIndexing: "Indexing",
+ uid: "UID",
+ updatedAt: "Updated",
+ primaryKey: "Primary key",
+ documentCountLabel: "Documents",
+ databaseSize: "Database size",
+ copyDocument: "Copy JSON",
+ copied: "Copied",
+ autoRefresh: "Auto refresh",
+ hybrid: "Hybrid search",
+ hybridEmbedder: "Embedder",
+ hybridSemanticRatio: "Semantic ratio",
+ hybridNoEmbedders: "No embedders configured in index settings; enter one manually.",
+ showRankingScore: "Ranking score",
+ rankingScoreThreshold: "Score threshold",
+ results: "Results",
+ exportResults: "Export results",
+ exportSearchUnsupported: "Full export is unavailable for text, hybrid, or score-threshold searches because Meilisearch caps search pagination. Clear those options to export every filtered document.",
+ },
dynamodb: {
tableMetadataUnavailable: "DynamoDB table metadata is not loaded. Refresh and try again.",
keyRequired: "DynamoDB items require the key attribute {key}",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index d86dba3c78..81e83e8ef4 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -4433,6 +4433,60 @@ export default withEnglishFallback({
indexOtherOptions: "Otras opciones",
indexPropertiesUnavailable: "El controlador Legacy de MongoDB no puede informar disperso, expiración, background o tamaño de bucket. Conéctese con el controlador nativo para verlos.",
},
+ meilisearch: {
+ documents: "Documentos",
+ settings: "Ajustes",
+ search: "Buscar",
+ keywordPlaceholder: "Buscar documentos...",
+ filter: "Filtro",
+ filterPlaceholder: 'status = "published"',
+ sort: "Orden",
+ sortPlaceholder: "campo:asc",
+ sortHint: "Separa varias expresiones de ordenación con comas (,)",
+ sortNoAttributes: "Este índice no tiene atributos ordenables configurados",
+ sortAsc: "Ascendente",
+ sortDesc: "Descendente",
+ limit: "Límite",
+ offset: "Desplazamiento",
+ resultSummary: "Aprox. {count} resultados · {time} ms",
+ viewJson: "JSON",
+ viewTable: "Tabla",
+ viewGrid: "Cuadrícula",
+ empty: "No se encontraron documentos",
+ editDocument: "Editar documento",
+ deleteDocument: "Eliminar documento",
+ deleteDocumentMessage: "¿Eliminar este documento? Esta acción no se puede deshacer.",
+ documentDeleted: "Documento eliminado",
+ documentSaved: "Documento guardado",
+ settingsSaved: "Ajustes guardados",
+ invalidJson: "JSON no válido",
+ settingsJson: "JSON de ajustes",
+ dangerZone: "Zona de peligro",
+ clearDocuments: "Vaciar todos los documentos",
+ clearDocumentsConfirmMessage: "Esto elimina todos los documentos del índice. No se puede deshacer.",
+ documentsCleared: "Documentos eliminados",
+ deleteIndex: "Eliminar índice",
+ deleteIndexConfirmMessage: "Esto elimina permanentemente el índice y todos sus documentos.",
+ indexDeleted: "Índice eliminado",
+ isIndexing: "Indexando",
+ uid: "UID",
+ updatedAt: "Actualizado",
+ primaryKey: "Clave primaria",
+ documentCountLabel: "Documentos",
+ databaseSize: "Tamaño de la base de datos",
+ copyDocument: "Copiar JSON",
+ copied: "Copiado",
+ autoRefresh: "Actualización automática",
+ hybrid: "Búsqueda híbrida",
+ hybridEmbedder: "Embedder",
+ hybridSemanticRatio: "Proporción semántica",
+ hybridNoEmbedders: "No hay embedders configurados en los ajustes del índice; introdúcelo manualmente.",
+ showRankingScore: "Puntuación de ranking",
+ rankingScoreThreshold: "Umbral de puntuación",
+ results: "Resultados",
+ exportResults: "Exportar resultados",
+ exportSearchUnsupported: "Meilisearch limita la paginación de búsquedas de texto, híbridas o con umbral de puntuación. Borre esas opciones para exportar todos los documentos filtrados.",
+ },
dynamodb: {
tableMetadataUnavailable: "Los metadatos de la tabla DynamoDB no se han cargado. Actualice e inténtelo de nuevo.",
keyRequired: "Los elementos de DynamoDB requieren el atributo de clave {key}",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 08b1aec925..4f2a893ac3 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -4431,6 +4431,60 @@ export default withEnglishFallback({
indexOtherOptions: "Altre opzioni",
indexPropertiesUnavailable: "Il driver Legacy di MongoDB non può riportare sparsità, scadenza, background o dimensione bucket. Connettersi con il driver nativo per vederli.",
},
+ meilisearch: {
+ documents: "Documenti",
+ settings: "Impostazioni",
+ search: "Cerca",
+ keywordPlaceholder: "Cerca documenti...",
+ filter: "Filtro",
+ filterPlaceholder: 'status = "published"',
+ sort: "Ordinamento",
+ sortPlaceholder: "campo:asc",
+ sortHint: "Separa più espressioni di ordinamento con la virgola (,)",
+ sortNoAttributes: "Nessun attributo ordinabile configurato per questo indice",
+ sortAsc: "Crescente",
+ sortDesc: "Decrescente",
+ limit: "Limite",
+ offset: "Scostamento",
+ resultSummary: "Circa {count} risultati · {time} ms",
+ viewJson: "JSON",
+ viewTable: "Tabella",
+ viewGrid: "Griglia",
+ empty: "Nessun documento trovato",
+ editDocument: "Modifica documento",
+ deleteDocument: "Elimina documento",
+ deleteDocumentMessage: "Eliminare questo documento? L'operazione non può essere annullata.",
+ documentDeleted: "Documento eliminato",
+ documentSaved: "Documento salvato",
+ settingsSaved: "Impostazioni salvate",
+ invalidJson: "JSON non valido",
+ settingsJson: "JSON impostazioni",
+ dangerZone: "Zona pericolosa",
+ clearDocuments: "Svuota tutti i documenti",
+ clearDocumentsConfirmMessage: "Questa operazione rimuove tutti i documenti dall'indice e non può essere annullata.",
+ documentsCleared: "Documenti eliminati",
+ deleteIndex: "Elimina indice",
+ deleteIndexConfirmMessage: "Questa operazione elimina definitivamente l'indice e tutti i suoi documenti.",
+ indexDeleted: "Indice eliminato",
+ isIndexing: "Indicizzazione",
+ uid: "UID",
+ updatedAt: "Aggiornato",
+ primaryKey: "Chiave primaria",
+ documentCountLabel: "Documenti",
+ databaseSize: "Dimensione del database",
+ copyDocument: "Copia JSON",
+ copied: "Copiato",
+ autoRefresh: "Aggiornamento automatico",
+ hybrid: "Ricerca ibrida",
+ hybridEmbedder: "Embedder",
+ hybridSemanticRatio: "Rapporto semantico",
+ hybridNoEmbedders: "Nessun embedder configurato nelle impostazioni dell'indice; inseriscilo manualmente.",
+ showRankingScore: "Punteggio di ranking",
+ rankingScoreThreshold: "Soglia del punteggio",
+ results: "Risultati",
+ exportResults: "Esporta risultati",
+ exportSearchUnsupported: "Meilisearch limita la paginazione delle ricerche testuali, ibride o con soglia di punteggio. Rimuovi queste opzioni per esportare tutti i documenti filtrati.",
+ },
dynamodb: {
tableMetadataUnavailable: "I metadati della tabella DynamoDB non sono caricati. Aggiorna e riprova.",
keyRequired: "Gli elementi DynamoDB richiedono l'attributo chiave {key}",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index ee87ded752..59b512c90e 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -4461,6 +4461,60 @@ export default withEnglishFallback({
indexOtherOptions: "その他のオプション",
indexPropertiesUnavailable: "MongoDB Legacy ドライバーはスパース、有効期限、バックグラウンド、バケットサイズを報告できません。ネイティブドライバーで接続して確認してください。",
},
+ meilisearch: {
+ documents: "ドキュメント",
+ settings: "設定",
+ search: "検索",
+ keywordPlaceholder: "ドキュメントを検索...",
+ filter: "フィルター",
+ filterPlaceholder: 'status = "published"',
+ sort: "並び替え",
+ sortPlaceholder: "field:asc",
+ sortHint: "複数のソート式は半角カンマ(,)で区切ります",
+ sortNoAttributes: "このインデックスにソート可能な属性が設定されていません",
+ sortAsc: "昇順",
+ sortDesc: "降順",
+ limit: "件数",
+ offset: "オフセット",
+ resultSummary: "約 {count} 件 · {time} ms",
+ viewJson: "JSON",
+ viewTable: "テーブル",
+ viewGrid: "グリッド",
+ empty: "ドキュメントが見つかりません",
+ editDocument: "ドキュメントを編集",
+ deleteDocument: "ドキュメントを削除",
+ deleteDocumentMessage: "このドキュメントを削除しますか?この操作は元に戻せません。",
+ documentDeleted: "ドキュメントを削除しました",
+ documentSaved: "ドキュメントを保存しました",
+ settingsSaved: "設定を保存しました",
+ invalidJson: "無効な JSON",
+ settingsJson: "設定 JSON",
+ dangerZone: "危険ゾーン",
+ clearDocuments: "すべてのドキュメントを消去",
+ clearDocumentsConfirmMessage: "インデックス内のすべてのドキュメントが削除されます。この操作は元に戻せません。",
+ documentsCleared: "すべてのドキュメントを削除しました",
+ deleteIndex: "インデックスを削除",
+ deleteIndexConfirmMessage: "インデックスとそのすべてのドキュメントが完全に削除されます。",
+ indexDeleted: "インデックスを削除しました",
+ isIndexing: "インデックス中",
+ uid: "UID",
+ updatedAt: "更新日時",
+ primaryKey: "主キー",
+ documentCountLabel: "ドキュメント数",
+ databaseSize: "データベースサイズ",
+ copyDocument: "JSON をコピー",
+ copied: "コピーしました",
+ autoRefresh: "自動更新",
+ hybrid: "ハイブリッド検索",
+ hybridEmbedder: "エンベッダー",
+ hybridSemanticRatio: "セマンティック比率",
+ hybridNoEmbedders: "インデックス設定にエンベッダーが設定されていません。手動で入力してください。",
+ showRankingScore: "ランキングスコア",
+ rankingScoreThreshold: "スコアしきい値",
+ results: "検索結果",
+ exportResults: "結果をエクスポート",
+ exportSearchUnsupported: "Meilisearch はテキスト検索、ハイブリッド検索、スコアしきい値付き検索のページングを制限します。すべての絞り込み済みドキュメントを出力するには、これらの条件を解除してください。",
+ },
dynamodb: {
tableMetadataUnavailable: "DynamoDB テーブルのメタデータが読み込まれていません。更新して再試行してください。",
keyRequired: "DynamoDB 項目にはキー属性 {key} が必要です",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 8c208aafc1..afb31cb60a 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -4075,6 +4075,60 @@ export default withEnglishFallback({
indexOtherOptions: "기타 옵션",
indexPropertiesUnavailable: "MongoDB Legacy 드라이버는 희소, 만료, 백그라운드 또는 버킷 크기를 보고할 수 없습니다. 네이티브 드라이버로 연결하여 확인하세요.",
},
+ meilisearch: {
+ documents: "문서",
+ settings: "설정",
+ search: "검색",
+ keywordPlaceholder: "문서 검색...",
+ filter: "필터",
+ filterPlaceholder: 'status = "published"',
+ sort: "정렬",
+ sortPlaceholder: "필드:asc",
+ sortHint: "여러 정렬식은 반각 쉼표(,)로 구분합니다",
+ sortNoAttributes: "이 인덱스에 설정된 정렬 가능 속성이 없습니다",
+ sortAsc: "오름차순",
+ sortDesc: "내림차순",
+ limit: "제한",
+ offset: "오프셋",
+ resultSummary: "약 {count}개 결과 · {time}ms",
+ viewJson: "JSON",
+ viewTable: "표",
+ viewGrid: "그리드",
+ empty: "문서를 찾을 수 없습니다",
+ editDocument: "문서 편집",
+ deleteDocument: "문서 삭제",
+ deleteDocumentMessage: "이 문서를 삭제할까요? 이 작업은 되돌릴 수 없습니다.",
+ documentDeleted: "문서가 삭제되었습니다",
+ documentSaved: "문서가 저장되었습니다",
+ settingsSaved: "설정이 저장되었습니다",
+ invalidJson: "잘못된 JSON",
+ settingsJson: "설정 JSON",
+ dangerZone: "위험 구역",
+ clearDocuments: "모든 문서 비우기",
+ clearDocumentsConfirmMessage: "인덱스의 모든 문서가 제거됩니다. 이 작업은 되돌릴 수 없습니다.",
+ documentsCleared: "모든 문서가 삭제되었습니다",
+ deleteIndex: "인덱스 삭제",
+ deleteIndexConfirmMessage: "인덱스와 모든 문서가 영구적으로 삭제됩니다.",
+ indexDeleted: "인덱스가 삭제되었습니다",
+ isIndexing: "인덱싱 중",
+ uid: "UID",
+ updatedAt: "업데이트됨",
+ primaryKey: "기본 키",
+ documentCountLabel: "문서 수",
+ databaseSize: "데이터베이스 크기",
+ copyDocument: "JSON 복사",
+ copied: "복사됨",
+ autoRefresh: "자동 새로고침",
+ hybrid: "하이브리드 검색",
+ hybridEmbedder: "임베더",
+ hybridSemanticRatio: "의미 비율",
+ hybridNoEmbedders: "인덱스 설정에 구성된 임베더가 없습니다. 직접 입력하세요.",
+ showRankingScore: "랭킹 점수",
+ rankingScoreThreshold: "점수 임계값",
+ results: "검색 결과",
+ exportResults: "결과보내기",
+ exportSearchUnsupported: "Meilisearch는 텍스트, 하이브리드 또는 점수 임계값 검색의 페이지 탐색을 제한합니다. 필터링된 모든 문서를 내보내려면 해당 옵션을 지우세요.",
+ },
dynamodb: {
tableMetadataUnavailable: "DynamoDB 테이블 메타데이터가 로드되지 않았습니다. 새로 고친 후 다시 시도하세요.",
keyRequired: "DynamoDB 항목에는 키 속성 {key}이(가) 필요합니다",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 6906865782..36a5c9af2a 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -4433,6 +4433,60 @@ export default withEnglishFallback({
indexOtherOptions: "Outras opções",
indexPropertiesUnavailable: "O driver Legacy do MongoDB não pode informar esparso, expiração, background ou tamanho do bucket. Conecte-se com o driver nativo para vê-los.",
},
+ meilisearch: {
+ documents: "Documentos",
+ settings: "Configurações",
+ search: "Buscar",
+ keywordPlaceholder: "Buscar documentos...",
+ filter: "Filtro",
+ filterPlaceholder: 'status = "published"',
+ sort: "Ordenação",
+ sortPlaceholder: "campo:asc",
+ sortHint: "Separe várias expressões de ordenação com vírgulas (,)",
+ sortNoAttributes: "Nenhum atributo ordenável configurado para este índice",
+ sortAsc: "Crescente",
+ sortDesc: "Decrescente",
+ limit: "Limite",
+ offset: "Deslocamento",
+ resultSummary: "Cerca de {count} resultados · {time} ms",
+ viewJson: "JSON",
+ viewTable: "Tabela",
+ viewGrid: "Grade",
+ empty: "Nenhum documento encontrado",
+ editDocument: "Editar documento",
+ deleteDocument: "Excluir documento",
+ deleteDocumentMessage: "Excluir este documento? Esta ação não pode ser desfeita.",
+ documentDeleted: "Documento excluído",
+ documentSaved: "Documento salvo",
+ settingsSaved: "Configurações salvas",
+ invalidJson: "JSON inválido",
+ settingsJson: "JSON de configurações",
+ dangerZone: "Zona de perigo",
+ clearDocuments: "Limpar todos os documentos",
+ clearDocumentsConfirmMessage: "Isso remove todos os documentos do índice. Esta ação não pode ser desfeita.",
+ documentsCleared: "Documentos excluídos",
+ deleteIndex: "Excluir índice",
+ deleteIndexConfirmMessage: "Isso exclui permanentemente o índice e todos os seus documentos.",
+ indexDeleted: "Índice excluído",
+ isIndexing: "Indexando",
+ uid: "UID",
+ updatedAt: "Atualizado",
+ primaryKey: "Chave primária",
+ documentCountLabel: "Documentos",
+ databaseSize: "Tamanho do banco de dados",
+ copyDocument: "Copiar JSON",
+ copied: "Copiado",
+ autoRefresh: "Atualização automática",
+ hybrid: "Busca híbrida",
+ hybridEmbedder: "Embedder",
+ hybridSemanticRatio: "Proporção semântica",
+ hybridNoEmbedders: "Nenhum embedder configurado nas configurações do índice; insira manualmente.",
+ showRankingScore: "Pontuação de ranking",
+ rankingScoreThreshold: "Limite de pontuação",
+ results: "Resultados",
+ exportResults: "Exportar resultados",
+ exportSearchUnsupported: "O Meilisearch limita a paginação de buscas por texto, híbridas ou com limite de pontuação. Limpe essas opções para exportar todos os documentos filtrados.",
+ },
dynamodb: {
tableMetadataUnavailable: "Os metadados da tabela DynamoDB não foram carregados. Atualize e tente novamente.",
keyRequired: "Os itens do DynamoDB exigem o atributo de chave {key}",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index e8d075678a..0789c61016 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -4578,6 +4578,60 @@ export default withEnglishFallback({
filterPlaceholder: "过滤条件...",
sortPlaceholder: "排序条件...",
},
+ meilisearch: {
+ documents: "文档",
+ settings: "设置",
+ search: "搜索",
+ keywordPlaceholder: "搜索文档...",
+ filter: "过滤",
+ filterPlaceholder: 'status = "published"',
+ sort: "排序",
+ sortPlaceholder: "field:asc",
+ sortHint: "使用半角逗号(,)分隔多个排序表达式",
+ sortNoAttributes: "索引未配置可排序字段",
+ sortAsc: "升序",
+ sortDesc: "降序",
+ limit: "条数",
+ offset: "偏移",
+ resultSummary: "约 {count} 条结果 · {time} 毫秒",
+ viewJson: "JSON",
+ viewTable: "表格",
+ viewGrid: "网格",
+ empty: "未找到文档",
+ editDocument: "编辑文档",
+ deleteDocument: "删除文档",
+ deleteDocumentMessage: "确定删除此文档?此操作无法撤销。",
+ documentDeleted: "文档已删除",
+ documentSaved: "文档已保存",
+ settingsSaved: "设置已保存",
+ invalidJson: "无效的 JSON",
+ settingsJson: "设置 JSON",
+ dangerZone: "危险区域",
+ clearDocuments: "清空全部文档",
+ clearDocumentsConfirmMessage: "这将移除索引中的全部文档,且无法撤销。",
+ documentsCleared: "全部文档已清空",
+ deleteIndex: "删除索引",
+ deleteIndexConfirmMessage: "这将永久删除该索引及其全部文档。",
+ indexDeleted: "索引已删除",
+ isIndexing: "索引中",
+ uid: "UID",
+ updatedAt: "更新于",
+ primaryKey: "主键",
+ documentCountLabel: "文档数",
+ databaseSize: "数据库大小",
+ copyDocument: "复制 JSON",
+ copied: "已复制",
+ autoRefresh: "自动刷新",
+ hybrid: "混合搜索",
+ hybridEmbedder: "嵌入模型(Embedder)",
+ hybridSemanticRatio: "语义权重",
+ hybridNoEmbedders: "索引设置中未配置嵌入模型,可手动输入。",
+ showRankingScore: "排名分数",
+ rankingScoreThreshold: "分数阈值",
+ results: "搜索结果",
+ exportResults: "导出结果",
+ exportSearchUnsupported: "Meilisearch 会限制文本、混合或分数阈值搜索的分页,无法保证完整导出。请清除这些选项后导出全部筛选文档。",
+ },
dynamodb: {
tableMetadataUnavailable: "尚未加载 DynamoDB 表结构,请刷新后重试",
keyRequired: "DynamoDB 项目必须填写键字段 {key}",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 7f6a2ff5ea..760920b386 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -3760,6 +3760,60 @@ export default withEnglishFallback({
invalidNativeJson: "原生 JSON 格式無效:{error}",
nativeDocumentRequired: "原生 JSON 的最上層必須是文件物件。",
},
+ meilisearch: {
+ documents: "文件",
+ settings: "設定",
+ search: "搜尋",
+ keywordPlaceholder: "搜尋文件...",
+ filter: "篩選",
+ filterPlaceholder: 'status = "published"',
+ sort: "排序",
+ sortPlaceholder: "field:asc",
+ sortHint: "使用半形逗號(,)分隔多個排序表達式",
+ sortNoAttributes: "索引未設定可排序欄位",
+ sortAsc: "升序",
+ sortDesc: "降序",
+ limit: "筆數",
+ offset: "位移",
+ resultSummary: "約 {count} 筆結果 · {time} 毫秒",
+ viewJson: "JSON",
+ viewTable: "表格",
+ viewGrid: "網格",
+ empty: "找不到文件",
+ editDocument: "編輯文件",
+ deleteDocument: "刪除文件",
+ deleteDocumentMessage: "確定刪除此文件?此操作無法復原。",
+ documentDeleted: "文件已刪除",
+ documentSaved: "文件已儲存",
+ settingsSaved: "設定已儲存",
+ invalidJson: "無效的 JSON",
+ settingsJson: "設定 JSON",
+ dangerZone: "危險區域",
+ clearDocuments: "清空全部文件",
+ clearDocumentsConfirmMessage: "這將移除索引中的全部文件,且無法復原。",
+ documentsCleared: "全部文件已清空",
+ deleteIndex: "刪除索引",
+ deleteIndexConfirmMessage: "這將永久刪除該索引及其全部文件。",
+ indexDeleted: "索引已刪除",
+ isIndexing: "建立索引中",
+ uid: "UID",
+ updatedAt: "更新於",
+ primaryKey: "主鍵",
+ documentCountLabel: "文件數",
+ databaseSize: "資料庫大小",
+ copyDocument: "複製 JSON",
+ copied: "已複製",
+ autoRefresh: "自動重新整理",
+ hybrid: "混合搜尋",
+ hybridEmbedder: "嵌入模型(Embedder)",
+ hybridSemanticRatio: "語意權重",
+ hybridNoEmbedders: "索引設定中未設定嵌入模型,可手動輸入。",
+ showRankingScore: "排名分數",
+ rankingScoreThreshold: "分數閾值",
+ results: "搜尋結果",
+ exportResults: "匯出結果",
+ exportSearchUnsupported: "Meilisearch 會限制文字、混合或分數閾值搜尋的分頁,無法保證完整匯出。請清除這些選項後匯出全部篩選文件。",
+ },
dynamodb: {
tableMetadataUnavailable: "尚未載入 DynamoDB 表結構,請重新整理後再試",
keyRequired: "DynamoDB 項目必須填寫鍵欄位 {key}",
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index a9613bf4f5..0e8e14bc4a 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -728,6 +728,15 @@ export const mongoUpdateDocument = forward("mongoUpdateDocument");
export const mongoUpdateDocuments = forward("mongoUpdateDocuments");
export const documentDeleteDocument = forward("documentDeleteDocument");
export const documentSaveMeilisearchBatch = forward("documentSaveMeilisearchBatch");
+export const meilisearchSearchDocuments = forward("meilisearchSearchDocuments");
+export const meilisearchFetchDocuments = forward("meilisearchFetchDocuments");
+export const meilisearchGetDocument = forward("meilisearchGetDocument");
+export const meilisearchGetIndexSettings = forward("meilisearchGetIndexSettings");
+export const meilisearchUpdateIndexSettings = forward("meilisearchUpdateIndexSettings");
+export const meilisearchGetIndexStats = forward("meilisearchGetIndexStats");
+export const meilisearchGetIndexOverview = forward("meilisearchGetIndexOverview");
+export const meilisearchDeleteIndex = forward("meilisearchDeleteIndex");
+export const meilisearchDeleteAllDocuments = forward("meilisearchDeleteAllDocuments");
export const mongoDeleteDocument = forward("mongoDeleteDocument");
export const mongoDeleteDocuments = forward("mongoDeleteDocuments");
export const mongoFindOneAndUpdate = forward("mongoFindOneAndUpdate");
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index 6eae92a068..fbe71efa6c 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -47,6 +47,7 @@ import type {
} from "@/types/database";
import { normalizeRustMongoCommand, type MongoCommand } from "@/lib/mongo/mongoShellCommand";
import { BackendErrorException, type BackendError } from "@/lib/backend/errorUtils";
+import { decodeMeilisearchDocumentPage, decodeMeilisearchSearchResult, type MeilisearchDocumentPage, type MeilisearchDocumentPageWire, type MeilisearchSearchResult, type MeilisearchSearchWireResult } from "@/lib/backend/meilisearchTransport";
import type { CollectionInfo } from "@/types/database";
import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, TableDiff, FunctionDiff, SequenceDiff, RuleDiff, OwnerDiff } from "@/lib/schema/schemaDiff";
import type { SidebarObjectKind } from "@/lib/database/databaseObjectCapabilities";
@@ -139,6 +140,7 @@ import type {
AppSupportInfo,
PromptTemplate,
SshPromptResolution,
+ MeilisearchIndexOverview,
} from "@/lib/backend/tauri";
import type { QueryEditability } from "@/lib/sql/sqlAnalysis";
import { isTerminalTransferProgress } from "@/lib/backend/transferProgress";
@@ -3878,6 +3880,90 @@ export async function documentSaveMeilisearchBatch(connectionId: string, collect
});
}
+export async function meilisearchSearchDocuments(
+ connectionId: string,
+ index: string,
+ params: { q?: string | null; filter?: string | null; sort?: string | null; limit: number; offset: number; hybridEmbedder?: string | null; hybridSemanticRatio?: number | null; showRankingScore?: boolean; rankingScoreThreshold?: number | null },
+): Promise<MeilisearchSearchResult> {
+ const result = await post<MeilisearchSearchWireResult>("/api/document-store/meilisearch/search", {
+ connectionId,
+ index,
+ q: params.q ?? null,
+ filter: params.filter ?? null,
+ sort: params.sort ?? null,
+ limit: params.limit,
+ offset: params.offset,
+ hybridEmbedder: params.hybridEmbedder ?? null,
+ hybridSemanticRatio: params.hybridSemanticRatio ?? null,
+ showRankingScore: params.showRankingScore ?? false,
+ rankingScoreThreshold: params.rankingScoreThreshold ?? null,
+ });
+ return decodeMeilisearchSearchResult(result);
+}
+
+export async function meilisearchFetchDocuments(connectionId: string, index: string, params: { filter?: string | null; sort?: string | null; limit: number; offset: number }): Promise<MeilisearchDocumentPage> {
+ const page = await post<MeilisearchDocumentPageWire>("/api/document-store/meilisearch/documents/fetch", {
+ connectionId,
+ index,
+ filter: params.filter ?? null,
+ sort: params.sort ?? null,
+ limit: params.limit,
+ offset: params.offset,
+ });
+ return decodeMeilisearchDocumentPage(page);
+}
+
+export async function meilisearchGetDocument(connectionId: string, index: string, id: string): Promise<string> {
+ return post("/api/document-store/meilisearch/documents/get", {
+ connectionId,
+ index,
+ id,
+ });
+}
+
+export async function meilisearchGetIndexSettings(connectionId: string, index: string): Promise<Record<string, any>> {
+ return post("/api/document-store/meilisearch/settings/get", {
+ connectionId,
+ index,
+ });
+}
+
+export async function meilisearchUpdateIndexSettings(connectionId: string, index: string, settings: Record<string, any>): Promise<void> {
+ return post("/api/document-store/meilisearch/settings/update", {
+ connectionId,
+ index,
+ settings,
+ });
+}
+
+export async function meilisearchGetIndexStats(connectionId: string, index: string): Promise<{ numberOfDocuments: number; isIndexing: boolean; fieldDistribution: Record<string, number> } & Record<string, any>> {
+ return post("/api/document-store/meilisearch/stats", {
+ connectionId,
+ index,
+ });
+}
+
+export async function meilisearchGetIndexOverview(connectionId: string, index: string): Promise<MeilisearchIndexOverview> {
+ return post("/api/document-store/meilisearch/overview", {
+ connectionId,
+ index,
+ });
+}
+
+export async function meilisearchDeleteIndex(connectionId: string, index: string): Promise<void> {
+ return post("/api/document-store/meilisearch/index/delete", {
+ connectionId,
+ index,
+ });
+}
+
+export async function meilisearchDeleteAllDocuments(connectionId: string, index: string): Promise<void> {
+ return post("/api/document-store/meilisearch/documents/delete-all", {
+ connectionId,
+ index,
+ });
+}
+
export async function mongoDeleteDocuments(connectionId: string, database: string, collection: string, filterJson: string, many: boolean): Promise<{ affected_rows: number }> {
return post("/api/mongo/delete-documents", {
connectionId,
diff --git a/apps/desktop/src/lib/backend/meilisearchTransport.spec.ts b/apps/desktop/src/lib/backend/meilisearchTransport.spec.ts
new file mode 100644
index 0000000000..1a6ecf9cc3
--- /dev/null
+++ b/apps/desktop/src/lib/backend/meilisearchTransport.spec.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import { serializeDocumentStoreId, stringifyDocumentStoreValue } from "@/lib/app/documentJsonValues";
+import { decodeMeilisearchDocumentPage, decodeMeilisearchSearchResult } from "./meilisearchTransport";
+
+describe("Meilisearch transport", () => {
+ it("keeps large integer identities and document JSON exact", () => {
+ const result = decodeMeilisearchSearchResult({
+ hits: [
+ {
+ idJson: "9007199254740993",
+ documentJson: '{"movie_id":9007199254740993,"title":"Alien"}',
+ },
+ ],
+ totalHits: 1,
+ processingTimeMs: 1,
+ });
+
+ expect(serializeDocumentStoreId(result.hits[0].id, "meilisearch")).toBe("9007199254740993");
+ expect(stringifyDocumentStoreValue(result.hits[0].document, "meilisearch")).toBe('{"movie_id":9007199254740993,"title":"Alien"}');
+ });
+
+ it("decodes full-document export pages without rounding integers", () => {
+ const page = decodeMeilisearchDocumentPage({
+ documentsJson: ['{"movie_id":9007199254740993,"internal_notes":"secret"}'],
+ total: 1,
+ });
+
+ expect(stringifyDocumentStoreValue(page.documents, "meilisearch")).toBe('[{"movie_id":9007199254740993,"internal_notes":"secret"}]');
+ });
+});
diff --git a/apps/desktop/src/lib/backend/meilisearchTransport.ts b/apps/desktop/src/lib/backend/meilisearchTransport.ts
new file mode 100644
index 0000000000..363e98fd64
--- /dev/null
+++ b/apps/desktop/src/lib/backend/meilisearchTransport.ts
@@ -0,0 +1,63 @@
+import { parseJsonPreservingLargeNumbers } from "@/lib/common/safeJsonFormat";
+
+export type MeilisearchSearchHit = {
+ id?: unknown;
+ document: Record<string, unknown>;
+ formatted?: Record<string, unknown>;
+ rankingScore?: unknown;
+};
+
+export type MeilisearchSearchResult = {
+ hits: MeilisearchSearchHit[];
+ totalHits: number;
+ processingTimeMs: number;
+};
+
+export type MeilisearchSearchWireResult = {
+ hits: Array<{
+ idJson?: string;
+ documentJson: string;
+ formattedJson?: string;
+ rankingScoreJson?: string;
+ }>;
+ totalHits: number;
+ processingTimeMs: number;
+};
+
+export type MeilisearchDocumentPage = {
+ documents: Record<string, unknown>[];
+ total: number;
+};
+
+export type MeilisearchDocumentPageWire = {
+ documentsJson: string[];
+ total: number;
+};
+
+function parseJsonObject(json: string, context: string): Record<string, unknown> {
+ const value = parseJsonPreservingLargeNumbers(json);
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ throw new Error(`Invalid Meilisearch ${context} payload`);
+ }
+ return value as Record<string, unknown>;
+}
+
+export function decodeMeilisearchSearchResult(result: MeilisearchSearchWireResult): MeilisearchSearchResult {
+ return {
+ hits: result.hits.map((hit) => ({
+ id: hit.idJson === undefined ? undefined : parseJsonPreservingLargeNumbers(hit.idJson),
+ document: parseJsonObject(hit.documentJson, "document"),
+ formatted: hit.formattedJson === undefined ? undefined : parseJsonObject(hit.formattedJson, "formatted document"),
+ rankingScore: hit.rankingScoreJson === undefined ? undefined : parseJsonPreservingLargeNumbers(hit.rankingScoreJson),
+ })),
+ totalHits: result.totalHits,
+ processingTimeMs: result.processingTimeMs,
+ };
+}
+
+export function decodeMeilisearchDocumentPage(page: MeilisearchDocumentPageWire): MeilisearchDocumentPage {
+ return {
+ documents: page.documentsJson.map((document) => parseJsonObject(document, "document")),
+ total: page.total,
+ };
+}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 7ee125c1ed..c07cf2f848 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -4,6 +4,7 @@ import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { normalizeRustMongoCommand, type MongoCommand } from "@/lib/mongo/mongoShellCommand";
import { ExternalSqlFileTooLargeError } from "@/lib/sql/sqlFileOpen";
import { appendDebugLog, isDebugLoggingEnabled } from "@/lib/backend/debugLog";
+import { decodeMeilisearchDocumentPage, decodeMeilisearchSearchResult, type MeilisearchDocumentPage, type MeilisearchDocumentPageWire, type MeilisearchSearchResult, type MeilisearchSearchWireResult } from "@/lib/backend/meilisearchTransport";
/** Normalize Tauri rejections once at the public backend boundary. */
async function invokeBackend<T>(command: string, args?: Record<string, unknown>): Promise<T> {
@@ -3797,6 +3798,100 @@ export async function documentSaveMeilisearchBatch(connectionId: string, collect
});
}
+export async function meilisearchSearchDocuments(
+ connectionId: string,
+ index: string,
+ params: { q?: string | null; filter?: string | null; sort?: string | null; limit: number; offset: number; hybridEmbedder?: string | null; hybridSemanticRatio?: number | null; showRankingScore?: boolean; rankingScoreThreshold?: number | null },
+): Promise<MeilisearchSearchResult> {
+ const result = await invoke<MeilisearchSearchWireResult>("meilisearch_search_documents", {
+ connectionId,
+ index,
+ q: params.q ?? null,
+ filter: params.filter ?? null,
+ sort: params.sort ?? null,
+ limit: params.limit,
+ offset: params.offset,
+ hybridEmbedder: params.hybridEmbedder ?? null,
+ hybridSemanticRatio: params.hybridSemanticRatio ?? null,
+ showRankingScore: params.showRankingScore ?? false,
+ rankingScoreThreshold: params.rankingScoreThreshold ?? null,
+ });
+ return decodeMeilisearchSearchResult(result);
+}
+
+export async function meilisearchFetchDocuments(connectionId: string, index: string, params: { filter?: string | null; sort?: string | null; limit: number; offset: number }): Promise<MeilisearchDocumentPage> {
+ const page = await invoke<MeilisearchDocumentPageWire>("meilisearch_fetch_documents", {
+ connectionId,
+ index,
+ filter: params.filter ?? null,
+ sort: params.sort ?? null,
+ limit: params.limit,
+ offset: params.offset,
+ });
+ return decodeMeilisearchDocumentPage(page);
+}
+
+export async function meilisearchGetDocument(connectionId: string, index: string, id: string): Promise<string> {
+ return invoke("meilisearch_get_document", {
+ connectionId,
+ index,
+ id,
+ });
+}
+
+export async function meilisearchGetIndexSettings(connectionId: string, index: string): Promise<Record<string, any>> {
+ return invoke("meilisearch_get_index_settings", {
+ connectionId,
+ index,
+ });
+}
+
+export async function meilisearchUpdateIndexSettings(connectionId: string, index: string, settings: Record<string, any>): Promise<void> {
+ return invoke("meilisearch_update_index_settings", {
+ connectionId,
+ index,
+ settings,
+ });
+}
+
+export async function meilisearchGetIndexStats(connectionId: string, index: string): Promise<{ numberOfDocuments: number; isIndexing: boolean; fieldDistribution: Record<string, number> } & Record<string, any>> {
+ return invoke("meilisearch_get_index_stats", {
+ connectionId,
+ index,
+ });
+}
+
+export interface MeilisearchIndexOverview {
+ uid: string;
+ primaryKey: string | null;
+ createdAt: string | null;
+ updatedAt: string | null;
+ numberOfDocuments: number;
+ isIndexing: boolean;
+ databaseSize: number | null;
+}
+
+export async function meilisearchGetIndexOverview(connectionId: string, index: string): Promise<MeilisearchIndexOverview> {
+ return invoke("meilisearch_get_index_overview", {
+ connectionId,
+ index,
+ });
+}
+
+export async function meilisearchDeleteIndex(connectionId: string, index: string): Promise<void> {
+ return invoke("meilisearch_delete_index", {
+ connectionId,
+ index,
+ });
+}
+
+export async function meilisearchDeleteAllDocuments(connectionId: string, index: string): Promise<void> {
+ return invoke("meilisearch_delete_all_documents", {
+ connectionId,
+ index,
+ });
+}
+
export async function mongoDeleteDocuments(connectionId: string, database: string, collection: string, filterJson: string, many: boolean): Promise<{ affected_rows: number }> {
const affectedRows = await invoke<number>("mongo_delete_documents", {
connectionId,
diff --git a/apps/desktop/src/lib/common/__tests__/jsonTree.spec.ts b/apps/desktop/src/lib/common/__tests__/jsonTree.spec.ts
index 18d898cb36..aa97e68998 100644
--- a/apps/desktop/src/lib/common/__tests__/jsonTree.spec.ts
+++ b/apps/desktop/src/lib/common/__tests__/jsonTree.spec.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { appendJsonPointer, createJsonTreeRoot, getJsonTreeChildren, getVisibleJsonTreeNodes, isJsonTreeContainer, isJsonTreeInitiallyExpanded } from "../jsonTree";
+import { appendJsonPointer, createJsonTreeRoot, getJsonTreeChildren, getVisibleJsonTreeNodes, isJsonTreeClosingNode, isJsonTreeContainer, isJsonTreeInitiallyExpanded } from "../jsonTree";
import { parseJsonPreservingLargeNumbers } from "../safeJsonFormat";
describe("jsonTree", () => {
@@ -35,6 +35,15 @@ describe("jsonTree", () => {
expect(nodes.map((node) => node.path)).toEqual(["", "/first", "/second", "/second/0"]);
});
+ it("adds closing-bracket rows after expanded containers when requested", () => {
+ const root = createJsonTreeRoot({ first: { nested: true }, second: ["kept"] });
+ const nodes = getVisibleJsonTreeNodes(root, () => true, true);
+
+ expect(nodes.map((node) => node.path)).toEqual(["", "/first", "/first/nested", "/first/$close\0", "/second", "/second/0", "/second/$close\0", "/$close\0"]);
+ expect(isJsonTreeClosingNode(nodes[3])).toBe(true);
+ expect(isJsonTreeClosingNode(nodes[0])).toBe(false);
+ });
+
it("handles deeply nested expanded JSON without recursive traversal", () => {
let value: unknown = true;
for (let depth = 0; depth < 2_000; depth += 1) value = { child: value };
diff --git a/apps/desktop/src/lib/common/jsonTree.ts b/apps/desktop/src/lib/common/jsonTree.ts
index 62792d3f9c..0d03c53a2d 100644
--- a/apps/desktop/src/lib/common/jsonTree.ts
+++ b/apps/desktop/src/lib/common/jsonTree.ts
@@ -12,6 +12,8 @@ export interface JsonTreeNode {
/** Zero-based structural depth; the root value is at depth zero. */
depth: number;
parentKind: JsonTreeParentKind;
+ /** True only for the synthetic closing-bracket row of an expanded container. */
+ closing?: boolean;
}
export type JsonTreeContainer = Record<string, unknown> | unknown[];
@@ -36,9 +38,14 @@ export function jsonTreeContainerKind(value: JsonTreeContainer): JsonTreeContain
return Array.isArray(value) ? "array" : "object";
}
-export function jsonTreeContainerSummary(value: JsonTreeContainer, includeObjectLength = true): string {
+/** Compact summary shown between the brackets of a collapsed container. */
+export function jsonTreeContainerSummary(value: JsonTreeContainer): string {
if (Array.isArray(value)) return `Array(${value.length})`;
- return includeObjectLength ? `Object(${Object.keys(value).length})` : "Object";
+ return `Object(${Object.keys(value).length})`;
+}
+
+export function isJsonTreeClosingNode(node: JsonTreeNode): boolean {
+ return node.closing === true;
}
/** Escape a reference token according to RFC 6901. */
@@ -81,9 +88,10 @@ export function getJsonTreeChildren(node: JsonTreeNode): JsonTreeNode[] {
/**
* Flatten the currently expanded tree with an iterative traversal. This lets
* virtual renderers keep every node logically expanded without recursive DOM
- * creation or deep-call-stack failures.
+ * creation or deep-call-stack failures. When `includeClosingRows` is set, each
+ * expanded container is followed by a synthetic closing-bracket row.
*/
-export function getVisibleJsonTreeNodes(root: JsonTreeNode, isExpanded: (node: JsonTreeNode) => boolean): JsonTreeNode[] {
+export function getVisibleJsonTreeNodes(root: JsonTreeNode, isExpanded: (node: JsonTreeNode) => boolean, includeClosingRows = false): JsonTreeNode[] {
const nodes: JsonTreeNode[] = [];
const pending = [root];
@@ -92,7 +100,20 @@ export function getVisibleJsonTreeNodes(root: JsonTreeNode, isExpanded: (node: J
if (!node) continue;
nodes.push(node);
- if (!isJsonTreeContainer(node.value) || !isExpanded(node)) continue;
+ if (isJsonTreeClosingNode(node) || !isJsonTreeContainer(node.value) || !isExpanded(node)) continue;
+ if (includeClosingRows) {
+ pending.push({
+ // NUL suffix keeps synthetic closing rows from colliding with a real
+ // `$close` key that a document may legitimately contain.
+ key: `${node.key}$close\0`,
+ label: "",
+ value: node.value,
+ path: `${node.path}/$close\0`,
+ depth: node.depth,
+ parentKind: node.parentKind,
+ closing: true,
+ });
+ }
const children = getJsonTreeChildren(node);
for (let index = children.length - 1; index >= 0; index -= 1) pending.push(children[index]);
}
diff --git a/apps/desktop/src/lib/sidebar/sidebarActiveTabTarget.ts b/apps/desktop/src/lib/sidebar/sidebarActiveTabTarget.ts
index 59840cb9bb..cee76136e4 100644
--- a/apps/desktop/src/lib/sidebar/sidebarActiveTabTarget.ts
+++ b/apps/desktop/src/lib/sidebar/sidebarActiveTabTarget.ts
@@ -116,6 +116,17 @@ export function activeTabSidebarTarget(tab: QueryTab | undefined | null): Active
};
}
+ if (tab.mode === "meilisearch") {
+ const collectionName = tab.sql || tab.title;
+ if (!collectionName) return null;
+ return {
+ type: "mongo-collection",
+ connectionId: tab.connectionId,
+ database: tab.database,
+ collectionName,
+ };
+ }
+
if (tab.mode === "mongo-bucket") {
return {
type: "mongo-gridfs",
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index dadb0bf115..5db6a1182a 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -1186,6 +1186,7 @@ export interface QueryTab {
| "redis"
| "redis-dashboard"
| "mongo"
+ | "meilisearch"
| "mongo-gridfs"
| "mongo-bucket"
| "vector"
diff --git a/crates/dbx-core/src/db/meilisearch_driver.rs b/crates/dbx-core/src/db/meilisearch_driver.rs
index c8ceaf3598..cb116c434d 100644
--- a/crates/dbx-core/src/db/meilisearch_driver.rs
+++ b/crates/dbx-core/src/db/meilisearch_driver.rs
@@ -2,7 +2,8 @@ use percent_encoding::{percent_decode_str, utf8_percent_encode, AsciiSet, CONTRO
use reqwest::{Client as HttpClient, Method, RequestBuilder, StatusCode};
use serde::Deserialize;
use serde_json::{Map, Value};
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, HashMap};
+use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use super::{http_client_builder, ColumnInfo};
@@ -38,6 +39,9 @@ pub struct MeilisearchClient {
http: HttpClient,
base_url: String,
api_key: Option<String>,
+ /// Per-index metadata cache so repeat searches stay single-request. Shared
+ /// across clones of the pooled client; evicted when the index is deleted.
+ index_info_cache: Arc<Mutex<HashMap<String, IndexInfoResponse>>>,
}
impl MeilisearchClient {
@@ -54,7 +58,12 @@ impl MeilisearchClient {
}
let http = builder.build().map_err(|error| format!("Meilisearch HTTP client error: {error}"))?;
let api_key = api_key.map(str::trim).filter(|value| !value.is_empty()).map(str::to_string);
- Ok(Self { http, base_url: url.trim_end_matches('/').to_string(), api_key })
+ Ok(Self {
+ http,
+ base_url: url.trim_end_matches('/').to_string(),
+ api_key,
+ index_info_cache: Arc::new(Mutex::new(HashMap::new())),
+ })
}
pub fn new_for_config(
@@ -167,7 +176,7 @@ pub async fn test_connection(client: &MeilisearchClient, _timeout: Duration) ->
Ok(())
}
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct IndexInfoResponse {
uid: String,
@@ -183,13 +192,19 @@ struct IndexListResponse {
}
async fn index_info(client: &MeilisearchClient, index: &str) -> Result<IndexInfoResponse, String> {
+ if let Some(cached) = client.index_info_cache.lock().unwrap().get(index).cloned() {
+ return Ok(cached);
+ }
let response = client
.get(&format!("/indexes/{}", encode_path_segment(index)))
.send()
.await
.map_err(|error| format!("Meilisearch request failed: {error}"))?;
let value = response_json(response, "index lookup").await?;
- serde_json::from_value(value).map_err(|error| format!("Meilisearch index parse error: {error}"))
+ let info: IndexInfoResponse =
+ serde_json::from_value(value).map_err(|error| format!("Meilisearch index parse error: {error}"))?;
+ client.index_info_cache.lock().unwrap().insert(index.to_string(), info.clone());
+ Ok(info)
}
pub async fn list_indexes(client: &MeilisearchClient) -> Result<Vec<String>, String> {
@@ -222,24 +237,36 @@ struct DocumentsResponse {
total: u64,
}
-async fn fetch_documents_value(
- client: &MeilisearchClient,
- index: &str,
+fn meilisearch_fetch_body(
offset: u64,
limit: u64,
filter: Option<&str>,
sort: Option<&str>,
-) -> Result<(DocumentsResponse, Option<String>), String> {
- let index_info = index_info(client, index).await?;
+ primary_key: Option<&str>,
+) -> Result<Map<String, Value>, String> {
let mut body = Map::new();
body.insert("offset".to_string(), Value::Number(offset.into()));
body.insert("limit".to_string(), Value::Number(limit.into()));
- if let Some(filter) = meilisearch_filter_from_request(filter, index_info.primary_key.as_deref())? {
- body.insert("filter".to_string(), Value::String(filter));
+ body.insert("fields".to_string(), Value::Array(vec![Value::String("*".to_string())]));
+ if let Some(filter) = meilisearch_filter_from_request(filter, primary_key)? {
+ body.insert("filter".to_string(), filter);
}
- if let Some(sort) = meilisearch_sort_from_request(sort, index_info.primary_key.as_deref())? {
+ if let Some(sort) = meilisearch_sort_from_request(sort, primary_key)? {
body.insert("sort".to_string(), Value::Array(sort.into_iter().map(Value::String).collect()));
}
+ Ok(body)
+}
+
+async fn fetch_documents_value(
+ client: &MeilisearchClient,
+ index: &str,
+ offset: u64,
+ limit: u64,
+ filter: Option<&str>,
+ sort: Option<&str>,
+) -> Result<(DocumentsResponse, Option<String>), String> {
+ let index_info = index_info(client, index).await?;
+ let body = meilisearch_fetch_body(offset, limit, filter, sort, index_info.primary_key.as_deref())?;
let response = client
.post(&format!("/indexes/{}/documents/fetch", encode_path_segment(&index_info.uid)))
@@ -278,6 +305,21 @@ pub async fn find_documents(
})
}
+pub async fn fetch_document_page(
+ client: &MeilisearchClient,
+ index: &str,
+ offset: u64,
+ limit: u64,
+ filter: Option<&str>,
+ sort: Option<&str>,
+) -> Result<MeilisearchDocumentPage, String> {
+ let (result, _) = fetch_documents_value(client, index, offset, limit, filter, sort).await?;
+ Ok(MeilisearchDocumentPage {
+ documents_json: result.results.into_iter().map(|document| document.to_string()).collect(),
+ total: result.total,
+ })
+}
+
pub async fn get_columns(client: &MeilisearchClient, index: &str) -> Result<Vec<ColumnInfo>, String> {
let (result, primary_key) = fetch_documents_value(client, index, 0, FIELD_SAMPLE_SIZE, None, None).await?;
let mut fields = BTreeMap::<String, FieldType>::new();
@@ -380,6 +422,29 @@ fn inject_document_identity(document: Value, primary_key: Option<&str>) -> Resul
Ok(Value::Object(document))
}
+fn search_hit(hit: Value, primary_key: Option<&str>, highlight: bool, ranking_score: bool) -> MeilisearchSearchHit {
+ let id_json = primary_key.and_then(|primary_key| hit.get(primary_key)).map(Value::to_string);
+ let mut document = hit;
+ let mut formatted = None;
+ let mut ranking = None;
+ if let Some(object) = document.as_object_mut() {
+ // Hoist response metadata only when the request asked for it; without
+ // the flag a same-named key is a legitimate user field and stays put.
+ if highlight {
+ formatted = object.remove("_formatted");
+ }
+ if ranking_score {
+ ranking = object.remove("_rankingScore");
+ }
+ }
+ MeilisearchSearchHit {
+ id_json,
+ document_json: document.to_string(),
+ formatted_json: formatted.map(|value| value.to_string()),
+ ranking_score_json: ranking.map(|value| value.to_string()),
+ }
+}
+
fn parse_document_object(doc_json: &str) -> Result<Map<String, Value>, String> {
let value: Value =
serde_json::from_str(doc_json).map_err(|error| format!("Invalid Meilisearch document JSON: {error}"))?;
@@ -440,7 +505,13 @@ pub async fn update_document(client: &MeilisearchClient, index: &str, id: &str,
let primary_key =
index_info.primary_key.ok_or_else(|| format!("Meilisearch index '{}' has no primary key", index_info.uid))?;
let mut document = parse_document_object(doc_json)?;
- document.remove("_id");
+ // `_id` is only the dbx browse alias when it matches the target identity; a
+ // genuine user field with a different value must survive the update.
+ let is_identity_alias =
+ document.get("_id").map(|value| value_to_id(value) == value_to_id(&decoded_identity(id))).unwrap_or(false);
+ if is_identity_alias {
+ document.remove("_id");
+ }
document.insert(primary_key, decoded_identity(id));
// Meilisearch uses POST for full replacement and PUT for partial updates.
// DBX sends the complete edited document so removed fields must disappear.
@@ -448,6 +519,26 @@ pub async fn update_document(client: &MeilisearchClient, index: &str, id: &str,
Ok(1)
}
+/// Fetch the canonical stored document by identity. Search hits may be shaped
+/// by `displayedAttributes` and search options, so edits must round-trip
+/// through this record instead of a hit payload.
+pub async fn get_document(client: &MeilisearchClient, index: &str, id: &str) -> Result<String, String> {
+ let response = client
+ .get(&format!(
+ "/indexes/{}/documents/{}?fields=*",
+ encode_path_segment(index),
+ encode_path_segment(&identity_path(id))
+ ))
+ .send()
+ .await
+ .map_err(|error| format!("Meilisearch request failed: {error}"))?;
+ let document = response_json(response, "document lookup").await?;
+ if !document.is_object() {
+ return Err("Meilisearch returned a non-object document".to_string());
+ }
+ Ok(document.to_string())
+}
+
pub async fn delete_document(client: &MeilisearchClient, index: &str, id: &str) -> Result<u64, String> {
let response = client
.delete(&format!(
@@ -578,16 +669,26 @@ async fn wait_for_task(client: &MeilisearchClient, task_uid: u64) -> Result<(),
}
}
-fn meilisearch_filter_from_request(filter: Option<&str>, primary_key: Option<&str>) -> Result<Option<String>, String> {
+fn meilisearch_filter_from_request(filter: Option<&str>, primary_key: Option<&str>) -> Result<Option<Value>, String> {
let Some(filter) = filter.map(str::trim).filter(|value| !value.is_empty() && *value != "{}") else {
return Ok(None);
};
+ // Native Meilisearch filter syntax (e.g. `status = "published" AND rating >= 8`)
+ // is passed through; the server validates it. Same trust level as `$meiliFilter`.
+ if !filter.starts_with('{') && !filter.starts_with('[') {
+ return Ok(Some(Value::String(filter.to_string())));
+ }
let value: Value =
serde_json::from_str(filter).map_err(|error| format!("Invalid Meilisearch filter JSON: {error}"))?;
+ // Native filter arrays (e.g. [["rating > 3"], "status = \"published\""]) are
+ // passed through unchanged; the official search API accepts string or array.
+ if value.is_array() {
+ return Ok(Some(value));
+ }
if let Some(raw) = value.get("$meiliFilter").and_then(Value::as_str) {
- return Ok(Some(raw.to_string()));
+ return Ok(Some(Value::String(raw.to_string())));
}
- filter_expression(&value, primary_key).map(Some)
+ filter_expression(&value, primary_key).map(|expression| Some(Value::String(expression)))
}
fn filter_expression(value: &Value, primary_key: Option<&str>) -> Result<String, String> {
@@ -683,22 +784,170 @@ fn meilisearch_sort_from_request(sort: Option<&str>, primary_key: Option<&str>)
let Some(sort) = sort.map(str::trim).filter(|value| !value.is_empty() && *value != "{}") else {
return Ok(None);
};
- let value: Value = serde_json::from_str(sort).map_err(|error| format!("Invalid Meilisearch sort JSON: {error}"))?;
- let object = value.as_object().ok_or_else(|| "Meilisearch sort must be a JSON object".to_string())?;
- let mut result = Vec::new();
- for (field, direction) in object {
+
+ fn sort_field<'a>(field: &'a str, primary_key: Option<&'a str>) -> Result<&'a str, String> {
let field = if field == "_id" { primary_key.unwrap_or(field) } else { field };
validate_filter_field(field)?;
- let direction = match direction {
- Value::Number(number) if number.as_i64().unwrap_or(1) < 0 => "desc",
- Value::String(value) if value.eq_ignore_ascii_case("desc") => "desc",
- _ => "asc",
+ Ok(field)
+ }
+
+ // The generic document browser sends a JSON object like {"rating":-1}.
+ if sort.starts_with('{') || sort.starts_with('[') {
+ let value: Value =
+ serde_json::from_str(sort).map_err(|error| format!("Invalid Meilisearch sort JSON: {error}"))?;
+ let object = value.as_object().ok_or_else(|| "Meilisearch sort must be a JSON object".to_string())?;
+ let mut result = Vec::new();
+ for (field, direction) in object {
+ let field = sort_field(field, primary_key)?;
+ let direction = match direction {
+ Value::Number(number) if number.as_i64().unwrap_or(1) < 0 => "desc",
+ Value::String(value) if value.eq_ignore_ascii_case("desc") => "desc",
+ _ => "asc",
+ };
+ result.push(format!("{field}:{direction}"));
+ }
+ return Ok((!result.is_empty()).then_some(result));
+ }
+
+ // Native Meilisearch syntax: comma-separated `field:asc|desc` entries, bare field means asc.
+ let mut result = Vec::new();
+ for entry in sort.split(',') {
+ let entry = entry.trim();
+ if entry.is_empty() {
+ continue;
+ }
+ let (field, direction) = match entry.split_once(':') {
+ Some((field, direction)) => (field.trim(), direction.trim()),
+ None => (entry, "asc"),
+ };
+ let field = sort_field(field, primary_key)?;
+ let direction = match direction.to_ascii_lowercase().as_str() {
+ "asc" => "asc",
+ "desc" => "desc",
+ _ => return Err(format!("Unsupported Meilisearch sort direction: {direction}")),
};
result.push(format!("{field}:{direction}"));
}
Ok((!result.is_empty()).then_some(result))
}
+/// Search hit with dbx identity and Meilisearch response metadata kept outside
+/// the document payload: `document` is always the pure user payload, so a real
+/// `_id` / `_formatted` / `_rankingScore` field in the stored document is never
+/// shadowed or stripped. `formatted` / `rankingScore` are hoisted only when the
+/// request actually asked for them.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MeilisearchSearchHit {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub id_json: Option<String>,
+ pub document_json: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub formatted_json: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub ranking_score_json: Option<String>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MeilisearchSearchResult {
+ pub hits: Vec<MeilisearchSearchHit>,
+ pub total_hits: u64,
+ pub processing_time_ms: u64,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MeilisearchDocumentPage {
+ pub documents_json: Vec<String>,
+ pub total: u64,
+}
+
+#[derive(Debug, Clone)]
+pub struct MeilisearchHybrid {
+ pub embedder: String,
+ pub semantic_ratio: f64,
+}
+
+fn meilisearch_search_body(
+ q: Option<&str>,
+ offset: u64,
+ limit: u64,
+ filter: Option<&str>,
+ sort: Option<&str>,
+ primary_key: Option<&str>,
+ hybrid: Option<&MeilisearchHybrid>,
+ show_ranking_score: bool,
+ ranking_score_threshold: Option<f64>,
+) -> Result<Map<String, Value>, String> {
+ let mut body = Map::new();
+ let q = q.map(str::trim).filter(|value| !value.is_empty());
+ if let Some(q) = q {
+ body.insert("q".to_string(), Value::String(q.to_string()));
+ }
+ body.insert("offset".to_string(), Value::Number(offset.into()));
+ body.insert("limit".to_string(), Value::Number(limit.into()));
+ if let Some(filter) = meilisearch_filter_from_request(filter, primary_key)? {
+ body.insert("filter".to_string(), filter);
+ }
+ if let Some(sort) = meilisearch_sort_from_request(sort, primary_key)? {
+ body.insert("sort".to_string(), Value::Array(sort.into_iter().map(Value::String).collect()));
+ }
+ if let Some(hybrid) = hybrid {
+ let embedder = hybrid.embedder.trim();
+ if embedder.is_empty() {
+ return Err("Meilisearch hybrid search requires an embedder name".to_string());
+ }
+ let semantic_ratio =
+ if hybrid.semantic_ratio.is_finite() { hybrid.semantic_ratio.clamp(0.0, 1.0) } else { 0.5 };
+ let ratio =
+ serde_json::Number::from_f64(semantic_ratio).ok_or_else(|| "Invalid hybrid semantic ratio".to_string())?;
+ let mut hybrid_body = Map::new();
+ hybrid_body.insert("embedder".to_string(), Value::String(embedder.to_string()));
+ hybrid_body.insert("semanticRatio".to_string(), Value::Number(ratio));
+ body.insert("hybrid".to_string(), Value::Object(hybrid_body));
+ }
+ if show_ranking_score {
+ body.insert("showRankingScore".to_string(), Value::Bool(true));
+ }
+ if let Some(threshold) = ranking_score_threshold.filter(|value| value.is_finite() && *value > 0.0) {
+ let threshold = serde_json::Number::from_f64(threshold.clamp(0.0, 1.0))
+ .ok_or_else(|| "Invalid ranking score threshold".to_string())?;
+ body.insert("rankingScoreThreshold".to_string(), Value::Number(threshold));
+ }
+ // Highlighting is only meaningful with a query term; asking for `_formatted`
+ // on every search would double the response payload for plain browsing.
+ if q.is_some() {
+ body.insert("attributesToHighlight".to_string(), Value::Array(vec![Value::String("*".to_string())]));
+ body.insert("highlightPreTag".to_string(), Value::String("<mark>".to_string()));
+ body.insert("highlightPostTag".to_string(), Value::String("</mark>".to_string()));
+ }
+ Ok(body)
+}
+
+fn parse_meilisearch_search_response(
+ value: Value,
+ primary_key: Option<&str>,
+ highlight: bool,
+ ranking_score: bool,
+) -> Result<MeilisearchSearchResult, String> {
+ let hits = value
+ .get("hits")
+ .cloned()
+ .unwrap_or(Value::Null)
+ .as_array()
+ .cloned()
+ .ok_or_else(|| "Meilisearch search response 'hits' must be an array".to_string())?;
+ let total_hits = value
+ .get("estimatedTotalHits")
+ .or_else(|| value.get("totalHits"))
+ .and_then(Value::as_u64)
+ .ok_or_else(|| "Meilisearch search response is missing a hit total".to_string())?;
+ let processing_time_ms = value.get("processingTimeMs").and_then(Value::as_u64).unwrap_or(0);
+ let hits = hits.into_iter().map(|hit| search_hit(hit, primary_key, highlight, ranking_score)).collect();
+ Ok(MeilisearchSearchResult { hits, total_hits, processing_time_ms })
+}
+
pub async fn execute_rest_query(client: &MeilisearchClient, input: &str) -> Result<QueryResult, String> {
let start = Instant::now();
let input = input.trim();
@@ -719,6 +968,136 @@ pub async fn execute_rest_query(client: &MeilisearchClient, input: &str) -> Resu
Ok(raw_response_result(status, body, start, truncated))
}
+#[allow(clippy::too_many_arguments)]
+pub async fn search_documents(
+ client: &MeilisearchClient,
+ index: &str,
+ q: Option<&str>,
+ filter: Option<&str>,
+ sort: Option<&str>,
+ limit: u64,
+ offset: u64,
+ hybrid: Option<&MeilisearchHybrid>,
+ show_ranking_score: bool,
+ ranking_score_threshold: Option<f64>,
+) -> Result<MeilisearchSearchResult, String> {
+ let index_info = index_info(client, index).await?;
+ let body = meilisearch_search_body(
+ q,
+ offset,
+ limit,
+ filter,
+ sort,
+ index_info.primary_key.as_deref(),
+ hybrid,
+ show_ranking_score,
+ ranking_score_threshold,
+ )?;
+ let response = client
+ .post(&format!("/indexes/{}/search", encode_path_segment(&index_info.uid)))
+ .json(&body)
+ .send()
+ .await
+ .map_err(|error| format!("Meilisearch request failed: {error}"))?;
+ let value = response_json(response, "document search").await?;
+ let highlight = q.map(str::trim).is_some_and(|value| !value.is_empty());
+ parse_meilisearch_search_response(value, index_info.primary_key.as_deref(), highlight, show_ranking_score)
+}
+
+pub async fn get_index_settings(client: &MeilisearchClient, index: &str) -> Result<Value, String> {
+ let response = client
+ .get(&format!("/indexes/{}/settings", encode_path_segment(index)))
+ .send()
+ .await
+ .map_err(|error| format!("Meilisearch request failed: {error}"))?;
+ response_json(response, "index settings lookup").await
+}
+
+pub async fn update_index_settings(client: &MeilisearchClient, index: &str, settings: &Value) -> Result<(), String> {
+ let response = client
+ .request(Method::PATCH, &format!("/indexes/{}/settings", encode_path_segment(index)))
+ .json(settings)
+ .send()
+ .await
+ .map_err(|error| format!("Meilisearch request failed: {error}"))?;
+ let task = task_from_response(response, "index settings update").await?;
+ wait_for_task(client, task.task_uid).await
+}
+
+pub async fn get_index_stats(client: &MeilisearchClient, index: &str) -> Result<Value, String> {
+ let response = client
+ .get(&format!("/indexes/{}/stats", encode_path_segment(index)))
+ .send()
+ .await
+ .map_err(|error| format!("Meilisearch request failed: {error}"))?;
+ response_json(response, "index stats lookup").await
+}
+
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MeilisearchIndexOverview {
+ pub uid: String,
+ pub primary_key: Option<String>,
+ pub created_at: Option<String>,
+ pub updated_at: Option<String>,
+ pub number_of_documents: u64,
+ pub is_indexing: bool,
+ /// Instance-wide database size in bytes; `None` when the API key cannot read instance stats.
+ pub database_size: Option<u64>,
+}
+
+pub async fn get_index_overview(client: &MeilisearchClient, index: &str) -> Result<MeilisearchIndexOverview, String> {
+ let info = response_json(
+ client
+ .get(&format!("/indexes/{}", encode_path_segment(index)))
+ .send()
+ .await
+ .map_err(|error| format!("Meilisearch request failed: {error}"))?,
+ "index lookup",
+ )
+ .await?;
+ let stats = get_index_stats(client, index).await?;
+ // Instance stats require broader key permissions, so keep them best-effort.
+ let database_size = match client.get("/stats").send().await {
+ Ok(response) => response_json(response, "instance stats lookup")
+ .await
+ .ok()
+ .and_then(|value| value.get("databaseSize").and_then(Value::as_u64)),
+ Err(_) => None,
+ };
+ Ok(MeilisearchIndexOverview {
+ uid: info.get("uid").and_then(Value::as_str).unwrap_or(index).to_string(),
+ primary_key: info.get("primaryKey").and_then(Value::as_str).map(str::to_string),
+ created_at: info.get("createdAt").and_then(Value::as_str).map(str::to_string),
+ updated_at: info.get("updatedAt").and_then(Value::as_str).map(str::to_string),
+ number_of_documents: stats.get("numberOfDocuments").and_then(Value::as_u64).unwrap_or(0),
+ is_indexing: stats.get("isIndexing").and_then(Value::as_bool).unwrap_or(false),
+ database_size,
+ })
+}
+
+pub async fn delete_index(client: &MeilisearchClient, index: &str) -> Result<(), String> {
+ let response = client
+ .delete(&format!("/indexes/{}", encode_path_segment(index)))
+ .send()
+ .await
+ .map_err(|error| format!("Meilisearch request failed: {error}"))?;
+ let task = task_from_response(response, "index deletion").await?;
+ wait_for_task(client, task.task_uid).await?;
+ client.index_info_cache.lock().unwrap().remove(index);
+ Ok(())
+}
+
+pub async fn delete_all_documents(client: &MeilisearchClient, index: &str) -> Result<(), String> {
+ let response = client
+ .delete(&format!("/indexes/{}/documents", encode_path_segment(index)))
+ .send()
+ .await
+ .map_err(|error| format!("Meilisearch request failed: {error}"))?;
+ let task = task_from_response(response, "document deletion").await?;
+ wait_for_task(client, task.task_uid).await
+}
+
async fn read_bounded_rest_response(mut response: reqwest::Response) -> Result<(String, bool), String> {
let read_limit = REST_RESPONSE_MAX_BYTES.saturating_add(1);
let capacity = response.content_length().unwrap_or(0).min(read_limit as u64) as usize;
@@ -814,11 +1193,12 @@ fn raw_response_result(status: u16, body: String, start: Instant, truncated: boo
#[cfg(test)]
mod tests {
use super::{
- decode_bounded_rest_body, filter_expression, meilisearch_base_url, meilisearch_sort_from_request,
- parse_rest_request_line, MeilisearchClient,
+ decode_bounded_rest_body, decoded_identity, filter_expression, identity_path, meilisearch_base_url,
+ meilisearch_filter_from_request, meilisearch_search_body, meilisearch_sort_from_request,
+ parse_meilisearch_search_response, parse_rest_request_line, MeilisearchClient,
};
use reqwest::Method;
- use serde_json::json;
+ use serde_json::{json, Value};
use std::time::Duration;
#[test]
@@ -888,6 +1268,49 @@ mod tests {
);
}
+ #[test]
+ fn accepts_native_meilisearch_sort_syntax() {
+ assert_eq!(
+ meilisearch_sort_from_request(Some("raw.createdAt:desc"), Some("id")).unwrap(),
+ Some(vec!["raw.createdAt:desc".to_string()])
+ );
+ assert_eq!(
+ meilisearch_sort_from_request(Some("rating:desc, title"), Some("id")).unwrap(),
+ Some(vec!["rating:desc".to_string(), "title:asc".to_string()])
+ );
+ // The `_id` alias still maps to the real primary key in native syntax.
+ assert_eq!(
+ meilisearch_sort_from_request(Some("_id:desc"), Some("movie_id")).unwrap(),
+ Some(vec!["movie_id:desc".to_string()])
+ );
+ assert!(meilisearch_sort_from_request(Some("rating:sideways"), Some("id")).is_err());
+ assert!(meilisearch_sort_from_request(Some("bad field:asc"), Some("id")).is_err());
+ }
+
+ #[test]
+ fn passes_through_native_meilisearch_filter_syntax() {
+ assert_eq!(
+ meilisearch_filter_from_request(Some("status = \"published\" AND rating >= 8"), Some("id")).unwrap(),
+ Some(json!("status = \"published\" AND rating >= 8"))
+ );
+ // JSON filters keep going through the document-store translation.
+ assert!(meilisearch_filter_from_request(Some(r#"{"status":"published"}"#), Some("id"))
+ .unwrap()
+ .and_then(|value| value.as_str().map(str::to_string))
+ .unwrap()
+ .contains("status = \"published\""));
+ }
+
+ #[test]
+ fn passes_through_native_meilisearch_filter_arrays() {
+ // The official search API accepts filter as a string or an array; array
+ // input must reach the request body unchanged instead of entering the
+ // legacy JSON-object translation.
+ let filter =
+ meilisearch_filter_from_request(Some(r#"[["rating > 3"], "status = \"published\""]"#), Some("id")).unwrap();
+ assert_eq!(filter, Some(json!([["rating > 3"], "status = \"published\""])));
+ }
+
#[test]
fn maps_document_identity_alias_to_primary_key() {
assert_eq!(
@@ -922,4 +1345,323 @@ mod tests {
body.extend_from_slice("界".as_bytes());
assert_eq!(decode_bounded_rest_body(&body), "a".repeat(super::REST_RESPONSE_MAX_BYTES - 1));
}
+
+ #[test]
+ fn builds_search_body_with_highlight_and_translated_filter_sort() {
+ let body = meilisearch_search_body(
+ Some("space"),
+ 20,
+ 10,
+ Some(r#"{"status":"published"}"#),
+ Some(r#"{"rating":-1}"#),
+ Some("movie_id"),
+ None,
+ true,
+ Some(0.8),
+ )
+ .unwrap();
+
+ assert_eq!(body.get("q").and_then(Value::as_str), Some("space"));
+ assert_eq!(body.get("offset").and_then(Value::as_u64), Some(20));
+ assert_eq!(body.get("limit").and_then(Value::as_u64), Some(10));
+ assert_eq!(body.get("filter").and_then(Value::as_str), Some("(status = \"published\")"));
+ assert_eq!(
+ body.get("sort")
+ .and_then(Value::as_array)
+ .map(|values| { values.iter().filter_map(Value::as_str).collect::<Vec<_>>() }),
+ Some(vec!["rating:desc"])
+ );
+ assert_eq!(body.get("attributesToHighlight").and_then(Value::as_array).map(Vec::len), Some(1));
+ assert_eq!(body.get("highlightPreTag").and_then(Value::as_str), Some("<mark>"));
+ assert_eq!(body.get("highlightPostTag").and_then(Value::as_str), Some("</mark>"));
+ assert_eq!(body.get("showRankingScore").and_then(Value::as_bool), Some(true));
+ assert_eq!(body.get("rankingScoreThreshold").and_then(Value::as_f64), Some(0.8));
+ }
+
+ #[test]
+ fn search_body_omits_empty_query_filter_and_sort() {
+ let body = meilisearch_search_body(None, 0, 5, None, None, None, None, false, None).unwrap();
+
+ assert!(body.get("q").is_none());
+ assert!(body.get("filter").is_none());
+ assert!(body.get("sort").is_none());
+ assert!(body.get("hybrid").is_none());
+ assert!(body.get("showRankingScore").is_none());
+ // Without a query term there is nothing to highlight, so `_formatted`
+ // data is not requested.
+ assert!(body.get("attributesToHighlight").is_none());
+ assert!(body.get("highlightPreTag").is_none());
+ assert!(body.get("highlightPostTag").is_none());
+ // A zero threshold means "no filtering" and is omitted.
+ let body = meilisearch_search_body(None, 0, 5, None, None, None, None, false, Some(0.0)).unwrap();
+ assert!(body.get("rankingScoreThreshold").is_none());
+ }
+
+ #[test]
+ fn search_body_includes_hybrid_options_when_enabled() {
+ let body = meilisearch_search_body(
+ Some("space"),
+ 0,
+ 5,
+ None,
+ None,
+ None,
+ Some(&super::MeilisearchHybrid { embedder: "default".to_string(), semantic_ratio: 1.5 }),
+ false,
+ None,
+ )
+ .unwrap();
+
+ let hybrid = body.get("hybrid").cloned().unwrap();
+ assert_eq!(hybrid.get("embedder").and_then(Value::as_str), Some("default"));
+ // Out-of-range ratios are clamped into [0, 1].
+ assert_eq!(hybrid.get("semanticRatio").and_then(Value::as_f64), Some(1.0));
+
+ let err = meilisearch_search_body(
+ None,
+ 0,
+ 5,
+ None,
+ None,
+ None,
+ Some(&super::MeilisearchHybrid { embedder: " ".to_string(), semantic_ratio: 0.5 }),
+ false,
+ None,
+ )
+ .unwrap_err();
+ assert!(err.contains("embedder"));
+ }
+
+ #[test]
+ fn parses_search_response_and_captures_identity() {
+ let value = json!({
+ "hits": [
+ { "movie_id": 123, "title": "Alien", "_formatted": { "title": "<mark>Alien</mark>" } }
+ ],
+ "estimatedTotalHits": 42,
+ "processingTimeMs": 7
+ });
+ let result = parse_meilisearch_search_response(value, Some("movie_id"), true, false).unwrap();
+
+ assert_eq!(result.total_hits, 42);
+ assert_eq!(result.processing_time_ms, 7);
+ assert_eq!(result.hits.len(), 1);
+ assert_eq!(result.hits[0].id_json.as_deref(), Some("123"));
+ // JSON crosses the HTTP/Tauri boundary as text so JavaScript never
+ // rounds integer identities or document fields before decoding them.
+ let document: Value = serde_json::from_str(&result.hits[0].document_json).unwrap();
+ assert_eq!(document["movie_id"], json!(123));
+ let formatted: Value = serde_json::from_str(result.hits[0].formatted_json.as_deref().unwrap()).unwrap();
+ assert_eq!(formatted, json!({ "title": "<mark>Alien</mark>" }));
+ assert!(document.get("_formatted").is_none());
+ }
+
+ #[test]
+ fn search_hit_preserves_real_formatted_and_ranking_score_fields_when_not_requested() {
+ // Without highlight/ranking-score requests, same-named keys are user
+ // fields and must stay inside the document payload.
+ let value = json!({
+ "hits": [
+ { "movie_id": 7, "_formatted": { "note": "user data" }, "_rankingScore": 0.99 }
+ ],
+ "estimatedTotalHits": 1,
+ "processingTimeMs": 1
+ });
+ let result = parse_meilisearch_search_response(value.clone(), Some("movie_id"), false, false).unwrap();
+
+ assert_eq!(result.hits[0].formatted_json, None);
+ assert_eq!(result.hits[0].ranking_score_json, None);
+ let document: Value = serde_json::from_str(&result.hits[0].document_json).unwrap();
+ assert_eq!(document["_formatted"], json!({ "note": "user data" }));
+ assert_eq!(document["_rankingScore"], json!(0.99));
+
+ // With the flags on, Meilisearch-owned metadata is hoisted instead.
+ let hoisted = parse_meilisearch_search_response(value, Some("movie_id"), true, true).unwrap();
+ let formatted: Value = serde_json::from_str(hoisted.hits[0].formatted_json.as_deref().unwrap()).unwrap();
+ let ranking_score: Value =
+ serde_json::from_str(hoisted.hits[0].ranking_score_json.as_deref().unwrap()).unwrap();
+ let document: Value = serde_json::from_str(&hoisted.hits[0].document_json).unwrap();
+ assert_eq!(formatted, json!({ "note": "user data" }));
+ assert_eq!(ranking_score, json!(0.99));
+ assert!(document.get("_formatted").is_none());
+ assert!(document.get("_rankingScore").is_none());
+ }
+
+ #[test]
+ fn search_identity_never_shadows_a_real_underscore_id_field() {
+ // A document may legitimately store its own `_id` field; the dbx identity
+ // must live outside the document so the user field survives round-trips.
+ let value = json!({
+ "hits": [
+ { "movie_id": 7, "_id": "user-owned", "title": "Alien" }
+ ],
+ "estimatedTotalHits": 1,
+ "processingTimeMs": 1
+ });
+ let result = parse_meilisearch_search_response(value, Some("movie_id"), false, false).unwrap();
+
+ assert_eq!(result.hits[0].id_json.as_deref(), Some("7"));
+ let document: Value = serde_json::from_str(&result.hits[0].document_json).unwrap();
+ assert_eq!(document["_id"], json!("user-owned"));
+ assert_eq!(document["movie_id"], json!(7));
+ }
+
+ #[test]
+ fn parses_large_search_responses() {
+ let hits: Vec<Value> =
+ (0..5000).map(|index| json!({ "movie_id": index, "title": format!("title-{index}") })).collect();
+ let result = parse_meilisearch_search_response(
+ json!({ "hits": hits, "estimatedTotalHits": 5000 }),
+ Some("movie_id"),
+ false,
+ false,
+ )
+ .unwrap();
+
+ assert_eq!(result.hits.len(), 5000);
+ assert_eq!(result.hits[4999].id_json.as_deref(), Some("4999"));
+ let document: Value = serde_json::from_str(&result.hits[4999].document_json).unwrap();
+ assert_eq!(document["movie_id"], json!(4999));
+ }
+
+ #[test]
+ fn search_transport_keeps_large_integer_identity_and_document_exact() {
+ let value: Value =
+ serde_json::from_str(r#"{"hits":[{"movie_id":9007199254740993,"title":"Alien"}],"estimatedTotalHits":1}"#)
+ .unwrap();
+ let result = parse_meilisearch_search_response(value, Some("movie_id"), false, false).unwrap();
+
+ assert_eq!(result.hits[0].id_json.as_deref(), Some("9007199254740993"));
+ assert_eq!(result.hits[0].document_json, r#"{"movie_id":9007199254740993,"title":"Alien"}"#);
+ let wire = serde_json::to_value(&result).unwrap();
+ assert_eq!(wire["hits"][0]["idJson"], json!("9007199254740993"));
+ assert_eq!(wire["hits"][0]["documentJson"], json!(r#"{"movie_id":9007199254740993,"title":"Alien"}"#));
+ }
+
+ #[test]
+ fn fetch_documents_requests_every_stored_field() {
+ let body =
+ super::meilisearch_fetch_body(0, 1000, Some(r#"genre = "sci-fi""#), Some("movie_id:asc"), Some("movie_id"))
+ .unwrap();
+
+ assert_eq!(body.get("fields"), Some(&json!(["*"])));
+ assert_eq!(body.get("limit"), Some(&json!(1000)));
+ assert_eq!(body.get("offset"), Some(&json!(0)));
+ }
+
+ #[test]
+ fn search_response_prefers_estimated_total_and_falls_back_to_total() {
+ let estimated = parse_meilisearch_search_response(
+ json!({ "hits": [], "estimatedTotalHits": 5, "processingTimeMs": 1 }),
+ None,
+ false,
+ false,
+ )
+ .unwrap();
+ assert_eq!(estimated.total_hits, 5);
+
+ let fallback = parse_meilisearch_search_response(
+ json!({ "hits": [], "totalHits": 9, "processingTimeMs": 2 }),
+ None,
+ false,
+ false,
+ )
+ .unwrap();
+ assert_eq!(fallback.total_hits, 9);
+ }
+
+ #[test]
+ fn search_response_requires_a_hit_total() {
+ let error = parse_meilisearch_search_response(json!({ "hits": [], "processingTimeMs": 1 }), None, false, false)
+ .unwrap_err();
+
+ assert!(error.contains("hit total"));
+ }
+
+ /// Minimal HTTP/1.1 server that records request lines and serves canned
+ /// index-info / search responses.
+ async fn spawn_recording_server() -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ use tokio::net::TcpListener;
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
+ let server_requests = requests.clone();
+ tokio::spawn(async move {
+ loop {
+ let Ok((mut socket, _)) = listener.accept().await else { break };
+ let requests = server_requests.clone();
+ tokio::spawn(async move {
+ let mut buf = vec![0u8; 8192];
+ let read = socket.read(&mut buf).await.unwrap_or(0);
+ let head = String::from_utf8_lossy(&buf[..read]).to_string();
+ let request_line = head.lines().next().unwrap_or("").to_string();
+ requests.lock().unwrap().push(request_line.clone());
+ let body = if request_line.starts_with("GET ") && request_line.contains("/documents/") {
+ r#"{"movie_id":"SN-0001","title":"Canonical"}"#
+ } else if request_line.starts_with("GET ") {
+ r#"{"uid":"movies","primaryKey":"movie_id"}"#
+ } else {
+ r#"{"hits":[{"movie_id":1}],"estimatedTotalHits":1,"processingTimeMs":1}"#
+ };
+ let response = format!(
+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
+ body.len(),
+ body
+ );
+ let _ = socket.write_all(response.as_bytes()).await;
+ });
+ }
+ });
+ (format!("http://{addr}"), requests)
+ }
+
+ #[tokio::test]
+ async fn repeat_searches_share_one_index_lookup() {
+ let (base_url, requests) = spawn_recording_server().await;
+ let client = super::MeilisearchClient::new(&base_url, None, false, None, Duration::from_secs(5)).unwrap();
+
+ super::search_documents(&client, "movies", None, None, None, 20, 0, None, false, None).await.unwrap();
+ super::search_documents(&client, "movies", None, None, None, 20, 20, None, false, None).await.unwrap();
+
+ let requests = requests.lock().unwrap();
+ let index_lookups = requests.iter().filter(|line| line.starts_with("GET /indexes/movies ")).count();
+ let searches = requests.iter().filter(|line| line.starts_with("POST /indexes/movies/search")).count();
+ // The primary-key lookup is cached per index, so steady-state searching
+ // is a single `/search` request instead of two round-trips.
+ assert_eq!(index_lookups, 1, "requests: {requests:?}");
+ assert_eq!(searches, 2, "requests: {requests:?}");
+ }
+
+ #[test]
+ fn string_primary_keys_keep_their_string_identity() {
+ // serializeDocumentStoreId on the frontend prefixes string ids so the
+ // backend does not reinterpret a numeric-looking string as a number.
+ let serialized = r#"__dbx_meilisearch_string_id__"123""#;
+ assert_eq!(decoded_identity(serialized), json!("123"));
+ assert_eq!(identity_path(serialized), "123");
+ // A bare numeric id still decodes as a number.
+ assert_eq!(decoded_identity("123"), json!(123));
+ assert_eq!(identity_path("123"), "123");
+ }
+
+ #[tokio::test]
+ async fn get_document_fetches_the_canonical_record_by_identity() {
+ let (base_url, requests) = spawn_recording_server().await;
+ let client = super::MeilisearchClient::new(&base_url, None, false, None, Duration::from_secs(5)).unwrap();
+
+ // A string id arrives in the serialized form and must keep its string
+ // identity in the request path.
+ let document_json =
+ super::get_document(&client, "movies", r#"__dbx_meilisearch_string_id__"SN-0001""#).await.unwrap();
+
+ let document: Value = serde_json::from_str(&document_json).unwrap();
+ assert_eq!(document["title"], json!("Canonical"));
+ let requests = requests.lock().unwrap();
+ assert!(
+ requests.iter().any(|line| line.starts_with("GET /indexes/movies/documents/SN-0001?fields=*")),
+ "requests: {requests:?}"
+ );
+ }
}
diff --git a/crates/dbx-core/src/document_ops.rs b/crates/dbx-core/src/document_ops.rs
index 16029f64f1..c0e5c0791a 100644
--- a/crates/dbx-core/src/document_ops.rs
+++ b/crates/dbx-core/src/document_ops.rs
@@ -759,6 +759,187 @@ pub async fn save_meilisearch_document_batch_core(
}
}
+#[allow(clippy::too_many_arguments)]
+pub async fn meilisearch_search_documents_core(
+ state: &AppState,
+ connection_id: &str,
+ index: &str,
+ q: Option<&str>,
+ filter: Option<&str>,
+ sort: Option<&str>,
+ limit: u64,
+ offset: u64,
+ hybrid_embedder: Option<&str>,
+ hybrid_semantic_ratio: Option<f64>,
+ show_ranking_score: bool,
+ ranking_score_threshold: Option<f64>,
+) -> Result<crate::db::meilisearch_driver::MeilisearchSearchResult, String> {
+ ensure_document_pool(state, connection_id).await?;
+ let connections = state.connections.read().await;
+ match connections.get(connection_id).ok_or("Not found")? {
+ PoolKind::Meilisearch(client) => {
+ let client = client.clone();
+ drop(connections);
+ let hybrid = hybrid_embedder.map(|embedder| crate::db::meilisearch_driver::MeilisearchHybrid {
+ embedder: embedder.to_string(),
+ semantic_ratio: hybrid_semantic_ratio.unwrap_or(0.5),
+ });
+ crate::db::meilisearch_driver::search_documents(
+ &client,
+ index,
+ q,
+ filter,
+ sort,
+ limit,
+ offset,
+ hybrid.as_ref(),
+ show_ranking_score,
+ ranking_score_threshold,
+ )
+ .await
+ }
+ _ => Err("Not a Meilisearch connection".to_string()),
+ }
+}
+
+pub async fn meilisearch_fetch_document_page_core(
+ state: &AppState,
+ connection_id: &str,
+ index: &str,
+ filter: Option<&str>,
+ sort: Option<&str>,
+ limit: u64,
+ offset: u64,
+) -> Result<crate::db::meilisearch_driver::MeilisearchDocumentPage, String> {
+ ensure_document_pool(state, connection_id).await?;
+ let connections = state.connections.read().await;
+ match connections.get(connection_id).ok_or("Not found")? {
+ PoolKind::Meilisearch(client) => {
+ let client = client.clone();
+ drop(connections);
+ crate::db::meilisearch_driver::fetch_document_page(&client, index, offset, limit, filter, sort).await
+ }
+ _ => Err("Not a Meilisearch connection".to_string()),
+ }
+}
+
+pub async fn meilisearch_get_index_settings_core(
+ state: &AppState,
+ connection_id: &str,
+ index: &str,
+) -> Result<serde_json::Value, String> {
+ ensure_document_pool(state, connection_id).await?;
+ let connections = state.connections.read().await;
+ match connections.get(connection_id).ok_or("Not found")? {
+ PoolKind::Meilisearch(client) => {
+ let client = client.clone();
+ drop(connections);
+ crate::db::meilisearch_driver::get_index_settings(&client, index).await
+ }
+ _ => Err("Not a Meilisearch connection".to_string()),
+ }
+}
+
+pub async fn meilisearch_get_document_core(
+ state: &AppState,
+ connection_id: &str,
+ index: &str,
+ id: &str,
+) -> Result<String, String> {
+ ensure_document_pool(state, connection_id).await?;
+ let connections = state.connections.read().await;
+ match connections.get(connection_id).ok_or("Not found")? {
+ PoolKind::Meilisearch(client) => {
+ let client = client.clone();
+ drop(connections);
+ crate::db::meilisearch_driver::get_document(&client, index, id).await
+ }
+ _ => Err("Not a Meilisearch connection".to_string()),
+ }
+}
+
+pub async fn meilisearch_update_index_settings_core(
+ state: &AppState,
+ connection_id: &str,
+ index: &str,
+ settings: &serde_json::Value,
+) -> Result<(), String> {
+ ensure_document_pool(state, connection_id).await?;
+ let connections = state.connections.read().await;
+ match connections.get(connection_id).ok_or("Not found")? {
+ PoolKind::Meilisearch(client) => {
+ let client = client.clone();
+ drop(connections);
+ crate::db::meilisearch_driver::update_index_settings(&client, index, settings).await
+ }
+ _ => Err("Not a Meilisearch connection".to_string()),
+ }
+}
+
+pub async fn meilisearch_get_index_stats_core(
+ state: &AppState,
+ connection_id: &str,
+ index: &str,
+) -> Result<serde_json::Value, String> {
+ ensure_document_pool(state, connection_id).await?;
+ let connections = state.connections.read().await;
+ match connections.get(connection_id).ok_or("Not found")? {
+ PoolKind::Meilisearch(client) => {
+ let client = client.clone();
+ drop(connections);
+ crate::db::meilisearch_driver::get_index_stats(&client, index).await
+ }
+ _ => Err("Not a Meilisearch connection".to_string()),
+ }
+}
+
+pub async fn meilisearch_get_index_overview_core(
+ state: &AppState,
+ connection_id: &str,
+ index: &str,
+) -> Result<crate::db::meilisearch_driver::MeilisearchIndexOverview, String> {
+ ensure_document_pool(state, connection_id).await?;
+ let connections = state.connections.read().await;
+ match connections.get(connection_id).ok_or("Not found")? {
+ PoolKind::Meilisearch(client) => {
+ let client = client.clone();
+ drop(connections);
+ crate::db::meilisearch_driver::get_index_overview(&client, index).await
+ }
+ _ => Err("Not a Meilisearch connection".to_string()),
+ }
+}
+
+pub async fn meilisearch_delete_index_core(state: &AppState, connection_id: &str, index: &str) -> Result<(), String> {
+ ensure_document_pool(state, connection_id).await?;
+ let connections = state.connections.read().await;
+ match connections.get(connection_id).ok_or("Not found")? {
+ PoolKind::Meilisearch(client) => {
+ let client = client.clone();
+ drop(connections);
+ crate::db::meilisearch_driver::delete_index(&client, index).await
+ }
+ _ => Err("Not a Meilisearch connection".to_string()),
+ }
+}
+
+pub async fn meilisearch_delete_all_documents_core(
+ state: &AppState,
+ connection_id: &str,
+ index: &str,
+) -> Result<(), String> {
+ ensure_document_pool(state, connection_id).await?;
+ let connections = state.connections.read().await;
+ match connections.get(connection_id).ok_or("Not found")? {
+ PoolKind::Meilisearch(client) => {
+ let client = client.clone();
+ drop(connections);
+ crate::db::meilisearch_driver::delete_all_documents(&client, index).await
+ }
+ _ => Err("Not a Meilisearch connection".to_string()),
+ }
+}
+
#[cfg(test)]
mod tests {
use super::{
diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs
index e363e75953..f6d311bd60 100644
--- a/crates/dbx-web/src/main.rs
+++ b/crates/dbx-web/src/main.rs
@@ -799,6 +799,18 @@ async fn main() {
.route("/document-store/update-document", post(routes::document_store::update_document))
.route("/document-store/delete-document", post(routes::document_store::delete_document))
.route("/document-store/save-meilisearch-batch", post(routes::document_store::save_meilisearch_batch))
+ .route("/document-store/meilisearch/search", post(routes::document_store::meilisearch_search))
+ .route("/document-store/meilisearch/documents/fetch", post(routes::document_store::meilisearch_fetch_documents))
+ .route("/document-store/meilisearch/documents/get", post(routes::document_store::meilisearch_get_document))
+ .route("/document-store/meilisearch/settings/get", post(routes::document_store::meilisearch_get_settings))
+ .route("/document-store/meilisearch/settings/update", post(routes::document_store::meilisearch_update_settings))
+ .route("/document-store/meilisearch/stats", post(routes::document_store::meilisearch_get_stats))
+ .route("/document-store/meilisearch/overview", post(routes::document_store::meilisearch_get_overview))
+ .route("/document-store/meilisearch/index/delete", post(routes::document_store::meilisearch_delete_index))
+ .route(
+ "/document-store/meilisearch/documents/delete-all",
+ post(routes::document_store::meilisearch_delete_all_documents),
+ )
.route("/mongo/find-documents", post(routes::mongo::find_documents))
.route("/mongo/parse-shell-command", post(routes::mongo::parse_shell_command))
.route("/mongo/explain-find", post(routes::mongo::explain_find))
diff --git a/crates/dbx-web/src/routes/document_store.rs b/crates/dbx-web/src/routes/document_store.rs
index e4026e04bb..bc03629af9 100644
--- a/crates/dbx-web/src/routes/document_store.rs
+++ b/crates/dbx-web/src/routes/document_store.rs
@@ -139,6 +139,56 @@ pub struct MeilisearchBatchSaveRequest {
pub inserts: Vec<String>,
}
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MeilisearchSearchRequest {
+ pub connection_id: String,
+ pub index: String,
+ pub q: Option<String>,
+ pub filter: Option<String>,
+ pub sort: Option<String>,
+ pub limit: u64,
+ pub offset: u64,
+ pub hybrid_embedder: Option<String>,
+ pub hybrid_semantic_ratio: Option<f64>,
+ pub show_ranking_score: Option<bool>,
+ pub ranking_score_threshold: Option<f64>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MeilisearchDocumentPageRequest {
+ pub connection_id: String,
+ pub index: String,
+ pub filter: Option<String>,
+ pub sort: Option<String>,
+ pub limit: u64,
+ pub offset: u64,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MeilisearchIndexRequest {
+ pub connection_id: String,
+ pub index: String,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MeilisearchDocumentGetRequest {
+ pub connection_id: String,
+ pub index: String,
+ pub id: String,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MeilisearchSettingsUpdateRequest {
+ pub connection_id: String,
+ pub index: String,
+ pub settings: serde_json::Value,
+}
+
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GridFsBucketRequest {
@@ -360,6 +410,128 @@ pub async fn save_meilisearch_batch(
Ok(Json(result))
}
+pub async fn meilisearch_search(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<MeilisearchSearchRequest>,
+) -> Result<Json<dbx_core::db::meilisearch_driver::MeilisearchSearchResult>, AppError> {
+ let result = dbx_core::document_ops::meilisearch_search_documents_core(
+ &state.app,
+ &req.connection_id,
+ &req.index,
+ req.q.as_deref(),
+ req.filter.as_deref(),
+ req.sort.as_deref(),
+ req.limit,
+ req.offset,
+ req.hybrid_embedder.as_deref(),
+ req.hybrid_semantic_ratio,
+ req.show_ranking_score.unwrap_or(false),
+ req.ranking_score_threshold,
+ )
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn meilisearch_fetch_documents(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<MeilisearchDocumentPageRequest>,
+) -> Result<Json<dbx_core::db::meilisearch_driver::MeilisearchDocumentPage>, AppError> {
+ let result = dbx_core::document_ops::meilisearch_fetch_document_page_core(
+ &state.app,
+ &req.connection_id,
+ &req.index,
+ req.filter.as_deref(),
+ req.sort.as_deref(),
+ req.limit,
+ req.offset,
+ )
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn meilisearch_get_document(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<MeilisearchDocumentGetRequest>,
+) -> Result<Json<String>, AppError> {
+ let result =
+ dbx_core::document_ops::meilisearch_get_document_core(&state.app, &req.connection_id, &req.index, &req.id)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn meilisearch_get_settings(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<MeilisearchIndexRequest>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ let result =
+ dbx_core::document_ops::meilisearch_get_index_settings_core(&state.app, &req.connection_id, &req.index)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn meilisearch_update_settings(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<MeilisearchSettingsUpdateRequest>,
+) -> Result<Json<()>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Update settings").await?;
+ dbx_core::document_ops::meilisearch_update_index_settings_core(
+ &state.app,
+ &req.connection_id,
+ &req.index,
+ &req.settings,
+ )
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(()))
+}
+
+pub async fn meilisearch_get_stats(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<MeilisearchIndexRequest>,
+) -> Result<Json<serde_json::Value>, AppError> {
+ let result = dbx_core::document_ops::meilisearch_get_index_stats_core(&state.app, &req.connection_id, &req.index)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn meilisearch_get_overview(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<MeilisearchIndexRequest>,
+) -> Result<Json<dbx_core::db::meilisearch_driver::MeilisearchIndexOverview>, AppError> {
+ let result =
+ dbx_core::document_ops::meilisearch_get_index_overview_core(&state.app, &req.connection_id, &req.index)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(result))
+}
+
+pub async fn meilisearch_delete_index(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<MeilisearchIndexRequest>,
+) -> Result<Json<()>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Delete index").await?;
+ dbx_core::document_ops::meilisearch_delete_index_core(&state.app, &req.connection_id, &req.index)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(()))
+}
+
+pub async fn meilisearch_delete_all_documents(
+ State(state): State<Arc<WebState>>,
+ Json(req): Json<MeilisearchIndexRequest>,
+) -> Result<Json<()>, AppError> {
+ ensure_writable(&state.app, &req.connection_id, "Delete all documents").await?;
+ dbx_core::document_ops::meilisearch_delete_all_documents_core(&state.app, &req.connection_id, &req.index)
+ .await
+ .map_err(AppError::from)?;
+ Ok(Json(()))
+}
+
pub async fn list_gridfs_files(
State(state): State<Arc<WebState>>,
Json(req): Json<GridFsFileListRequest>,
diff --git a/src-tauri/src/commands/document_cmd.rs b/src-tauri/src/commands/document_cmd.rs
index 712c01b3ee..f556b5461e 100644
--- a/src-tauri/src/commands/document_cmd.rs
+++ b/src-tauri/src/commands/document_cmd.rs
@@ -231,6 +231,130 @@ pub async fn document_save_meilisearch_batch(
.await
}
+#[tauri::command]
+#[allow(clippy::too_many_arguments)]
+pub async fn meilisearch_search_documents(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ index: String,
+ q: Option<String>,
+ filter: Option<String>,
+ sort: Option<String>,
+ limit: u64,
+ offset: u64,
+ hybrid_embedder: Option<String>,
+ hybrid_semantic_ratio: Option<f64>,
+ show_ranking_score: Option<bool>,
+ ranking_score_threshold: Option<f64>,
+) -> Result<dbx_core::db::meilisearch_driver::MeilisearchSearchResult, String> {
+ dbx_core::document_ops::meilisearch_search_documents_core(
+ &state,
+ &connection_id,
+ &index,
+ q.as_deref(),
+ filter.as_deref(),
+ sort.as_deref(),
+ limit,
+ offset,
+ hybrid_embedder.as_deref(),
+ hybrid_semantic_ratio,
+ show_ranking_score.unwrap_or(false),
+ ranking_score_threshold,
+ )
+ .await
+}
+
+#[tauri::command]
+#[allow(clippy::too_many_arguments)]
+pub async fn meilisearch_fetch_documents(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ index: String,
+ filter: Option<String>,
+ sort: Option<String>,
+ limit: u64,
+ offset: u64,
+) -> Result<dbx_core::db::meilisearch_driver::MeilisearchDocumentPage, String> {
+ dbx_core::document_ops::meilisearch_fetch_document_page_core(
+ &state,
+ &connection_id,
+ &index,
+ filter.as_deref(),
+ sort.as_deref(),
+ limit,
+ offset,
+ )
+ .await
+}
+
+#[tauri::command]
+pub async fn meilisearch_get_document(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ index: String,
+ id: String,
+) -> Result<String, String> {
+ dbx_core::document_ops::meilisearch_get_document_core(&state, &connection_id, &index, &id).await
+}
+
+#[tauri::command]
+pub async fn meilisearch_get_index_settings(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ index: String,
+) -> Result<serde_json::Value, String> {
+ dbx_core::document_ops::meilisearch_get_index_settings_core(&state, &connection_id, &index).await
+}
+
+#[tauri::command]
+pub async fn meilisearch_update_index_settings(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ index: String,
+ settings: serde_json::Value,
+) -> Result<(), String> {
+ ensure_connection_writable(&state, &connection_id, "Update settings").await?;
+ dbx_core::document_ops::meilisearch_update_index_settings_core(&state, &connection_id, &index, &settings).await
+}
+
+#[tauri::command]
+pub async fn meilisearch_get_index_stats(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ index: String,
+) -> Result<serde_json::Value, String> {
+ dbx_core::document_ops::meilisearch_get_index_stats_core(&state, &connection_id, &index).await
+}
+
+#[tauri::command]
+pub async fn meilisearch_get_index_overview(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ index: String,
+) -> Result<dbx_core::db::meilisearch_driver::MeilisearchIndexOverview, String> {
+ dbx_core::document_ops::meilisearch_get_index_overview_core(&state, &connection_id, &index).await
+}
+
+#[tauri::command]
+pub async fn meilisearch_delete_index(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ index: String,
+) -> Result<(), String> {
+ ensure_connection_writable(&state, &connection_id, "Delete index").await?;
+ dbx_core::document_ops::meilisearch_delete_index_core(&state, &connection_id, &index).await
+}
+
+#[tauri::command]
+pub async fn meilisearch_delete_all_documents(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+ index: String,
+) -> Result<(), String> {
+ ensure_connection_writable(&state, &connection_id, "Delete all documents").await?;
+ dbx_core::document_ops::meilisearch_delete_all_documents_core(&state, &connection_id, &index).await
+}
+
#[tauri::command]
pub async fn document_list_gridfs_buckets(
state: State<'_, Arc<AppState>>,
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index c331051f1c..80ed4121f1 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -2037,6 +2037,15 @@ pub fn run() {
commands::mongo_cmd::mongo_update_documents,
commands::document_cmd::document_delete_document,
commands::document_cmd::document_save_meilisearch_batch,
+ commands::document_cmd::meilisearch_search_documents,
+ commands::document_cmd::meilisearch_fetch_documents,
+ commands::document_cmd::meilisearch_get_document,
+ commands::document_cmd::meilisearch_get_index_settings,
+ commands::document_cmd::meilisearch_update_index_settings,
+ commands::document_cmd::meilisearch_get_index_stats,
+ commands::document_cmd::meilisearch_get_index_overview,
+ commands::document_cmd::meilisearch_delete_index,
+ commands::document_cmd::meilisearch_delete_all_documents,
commands::hbase_cmd::hbase_get_table_schema,
commands::hbase_cmd::hbase_scan_rows,
commands::hbase_cmd::hbase_get_row,