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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(elasticsearch): apply document filters in browser
t8y27923f4915e4a
diff --git a/apps/desktop/src/components/mongo/MongoDocBrowser.vue b/apps/desktop/src/components/document/DocumentBrowser.vuesimilarity index 82%rename from apps/desktop/src/components/mongo/MongoDocBrowser.vuerename to apps/desktop/src/components/document/DocumentBrowser.vueindex 7b105cb1cc..162964e865 100644--- a/apps/desktop/src/components/mongo/MongoDocBrowser.vue+++ b/apps/desktop/src/components/document/DocumentBrowser.vue@@ -12,6 +12,7 @@ import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";import DataGrid from "@/components/grid/DataGrid.vue";import * as api from "@/lib/api";import { clampSearchSplitWidth } from "@/lib/dataGridSearchSplit";+import { buildDocumentFilterCondition, combineDocumentFilterConditions, currentDocumentFilterJson, defaultDocumentFilterRule, documentFilterModeNeedsValue, documentFilterModeOptions, documentStoreProviderFor, type DocumentFilterMode, type DocumentFilterRule } from "@/lib/documentStoreProvider";import { normalizeResultPageSize } from "@/lib/paginationPageSize";import { useSettingsStore } from "@/stores/settingsStore";import JsonEditNode from "./JsonEditNode.vue";@@ -60,22 +61,16 @@ const tableFindPaneWidth = ref<number | null>(null);const isResizingTableSearchSplit = ref(false);let tableSearchSplitStartX = 0;let tableSearchSplitStartWidth = 0;+const documentStoreProvider = computed(() => documentStoreProviderFor(props.databaseType));const tableFindPaneStyle = computed(() => {if (tableFindPaneWidth.value == null) return {};return { flex: `0 0 ${tableFindPaneWidth.value}px` };});-const documentStoreLabels = computed(() =>- props.databaseType === "elasticsearch"- ? {- documentsLabel: "Documents",- queryPreview: `${props.collection}/_search`,- }- : {- documentsLabel: t("mongo.documents", { count: total.value }),- queryPreview: mongoQueryPreview.value,- },-);+const documentStoreLabels = computed(() => ({+ documentsLabel: documentStoreProvider.value.documentsLabel({ total: total.value, t }),+ queryPreview: documentQueryPreview.value,+}));type PendingDelete = { kind: "document"; index: number } | { kind: "field"; index: number; name: string };type LocalFilterSummary = {@@ -84,28 +79,9 @@ type LocalFilterSummary = {values: string[];hiddenValueCount: number;};-type MongoFilterMode = "equals" | "not-equals" | "like" | "not-like" | "greater-than" | "less-than" | "is-null" | "is-not-null";-type MongoFilterRule = {- id: string;- fieldName: string;- mode: MongoFilterMode;- rawValue: string;- conjunction: "AND" | "OR";-};--const mongoFilterModeOptions: Array<{ value: MongoFilterMode; labelKey: string }> = [- { value: "equals", labelKey: "grid.filterBuilderEquals" },- { value: "not-equals", labelKey: "grid.filterBuilderNotEquals" },- { value: "like", labelKey: "grid.filterBuilderContains" },- { value: "not-like", labelKey: "grid.filterBuilderNotContains" },- { value: "greater-than", labelKey: "grid.filterBuilderGreaterThan" },- { value: "less-than", labelKey: "grid.filterBuilderLessThan" },- { value: "is-null", labelKey: "grid.filterBuilderIsNull" },- { value: "is-not-null", labelKey: "grid.filterBuilderIsNotNull" },-];-const mongoFilterBuilderOpen = ref(false);-const mongoFilterRules = ref<MongoFilterRule[]>([]);-const appliedMongoFilter = ref<Record<string, unknown> | null>(null);+const documentFilterBuilderOpen = ref(false);+const documentFilterRules = ref<DocumentFilterRule[]>([]);+const appliedDocumentFilter = ref<Record<string, unknown> | null>(null);const pendingDelete = ref<PendingDelete | null>(null);@@ -165,139 +141,77 @@ const gridResult = computed<QueryResult>(() => {return { columns, rows, affected_rows: 0, execution_time_ms: 0, truncated: false };});-const mongoFilterFieldOptions = computed(() => gridResult.value.columns);-const mongoStructuredFilterCount = computed(() => (appliedMongoFilter.value ? 1 : 0));+const documentFilterFieldOptions = computed(() => gridResult.value.columns);+const documentStructuredFilterCount = computed(() => (appliedDocumentFilter.value ? 1 : 0));-function defaultMongoFilterRule(): MongoFilterRule {- return {- id: uuid(),- fieldName: mongoFilterFieldOptions.value[0] ?? "",- mode: "equals",- rawValue: "",- conjunction: "AND",- };+function createDocumentFilterRule(): DocumentFilterRule {+ return defaultDocumentFilterRule(uuid(), documentFilterFieldOptions.value[0] ?? "");}-function ensureMongoFilterRule() {- if (mongoFilterRules.value.length === 0 && mongoFilterFieldOptions.value.length > 0) {- mongoFilterRules.value = [defaultMongoFilterRule()];+function ensureDocumentFilterRule() {+ if (documentFilterRules.value.length === 0 && documentFilterFieldOptions.value.length > 0) {+ documentFilterRules.value = [createDocumentFilterRule()];}}-function addMongoFilterRule() {- ensureMongoFilterRule();- mongoFilterRules.value = [...mongoFilterRules.value, defaultMongoFilterRule()];+function addDocumentFilterRule() {+ ensureDocumentFilterRule();+ documentFilterRules.value = [...documentFilterRules.value, createDocumentFilterRule()];}-function removeMongoFilterRule(ruleId: string) {- mongoFilterRules.value = mongoFilterRules.value.filter((rule) => rule.id !== ruleId);- if (mongoFilterRules.value.length === 0) appliedMongoFilter.value = null;+function removeDocumentFilterRule(ruleId: string) {+ documentFilterRules.value = documentFilterRules.value.filter((rule) => rule.id !== ruleId);+ if (documentFilterRules.value.length === 0) appliedDocumentFilter.value = null;}-function updateMongoFilterRule(ruleId: string, patch: Partial<MongoFilterRule>) {- mongoFilterRules.value = mongoFilterRules.value.map((rule) => {+function updateDocumentFilterRule(ruleId: string, patch: Partial<DocumentFilterRule>) {+ documentFilterRules.value = documentFilterRules.value.map((rule) => {if (rule.id !== ruleId) return rule;const next = { ...rule, ...patch };- if (!mongoFilterModeNeedsValue(next.mode)) next.rawValue = "";+ if (!documentFilterModeNeedsValue(next.mode)) next.rawValue = "";return next;});}-function resetMongoFilterBuilder() {- appliedMongoFilter.value = null;- mongoFilterRules.value = mongoFilterFieldOptions.value.length > 0 ? [defaultMongoFilterRule()] : [];+function resetDocumentFilterBuilder() {+ appliedDocumentFilter.value = null;+ documentFilterRules.value = documentFilterFieldOptions.value.length > 0 ? [createDocumentFilterRule()] : [];}-function mongoFilterModeNeedsValue(mode: MongoFilterMode): boolean {- return mode !== "is-null" && mode !== "is-not-null";+function currentDocumentFilter(): string | undefined {+ return currentDocumentFilterJson(filterInput.value, appliedDocumentFilter.value);}-function parseMongoFilterValue(raw: string): unknown {- const trimmed = raw.trim();- if (!trimmed) return "";- try {- return JSON.parse(trimmed);- } catch {- return trimmed;- }-}--function mongoConditionForRule(rule: MongoFilterRule): Record<string, unknown> | null {- if (!rule.fieldName) return null;- if (mongoFilterModeNeedsValue(rule.mode) && !rule.rawValue.trim()) return null;- const value = mongoFilterModeNeedsValue(rule.mode) ? parseMongoFilterValue(rule.rawValue) : null;- switch (rule.mode) {- case "equals":- return { [rule.fieldName]: value };- case "not-equals":- return { [rule.fieldName]: { $ne: value } };- case "like":- return { [rule.fieldName]: { $regex: String(value), $options: "i" } };- case "not-like":- return { [rule.fieldName]: { $not: { $regex: String(value), $options: "i" } } };- case "greater-than":- return { [rule.fieldName]: { $gt: value } };- case "less-than":- return { [rule.fieldName]: { $lt: value } };- case "is-null":- return { [rule.fieldName]: null };- case "is-not-null":- return { [rule.fieldName]: { $ne: null } };- }-}--function combineMongoConditions(conditions: Record<string, unknown>[], rules: MongoFilterRule[]): Record<string, unknown> | null {- if (conditions.length === 0) return null;- let result = conditions[0];- for (let i = 1; i < conditions.length; i++) {- const operator = rules[i]?.conjunction === "OR" ? "$or" : "$and";- result = { [operator]: [result, conditions[i]] };- }- return result;-}--function parseMongoFilterInput(): Record<string, unknown> {- const trimmed = filterInput.value.trim();- if (!trimmed) return {};- const parsed = JSON.parse(trimmed);- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {};-}--function currentMongoFilter(): string | undefined {- const manual = parseMongoFilterInput();- const structured = appliedMongoFilter.value;- const filter = structured ? (Object.keys(manual).length ? { $and: [manual, structured] } : structured) : manual;- return Object.keys(filter).length ? JSON.stringify(filter) : undefined;-}--const mongoQueryPreview = computed(() => {+const documentQueryPreview = computed(() => {let filter = "{}";try {- filter = currentMongoFilter() ?? "{}";+ filter = currentDocumentFilter() ?? "{}";} catch {filter = filterInput.value.trim() || "{}";}- const sort = sortInput.value.trim();- const parts = [`db.${props.collection}.find(${filter})`];- if (sort) parts.push(`.sort(${sort})`);- parts.push(`.skip(${page.value * pageSize.value}).limit(${pageSize.value})`);- return parts.join("");+ return documentStoreProvider.value.queryPreview({+ collection: props.collection,+ filterJson: filter,+ sortJson: sortInput.value.trim(),+ skip: page.value * pageSize.value,+ limit: pageSize.value,+ });});-async function applyMongoStructuredFilters() {- const items = mongoFilterRules.value.map((rule) => ({ rule, condition: mongoConditionForRule(rule) })).filter((item): item is { rule: MongoFilterRule; condition: Record<string, unknown> } => !!item.condition);- const structured = combineMongoConditions(+async function applyDocumentStructuredFilters() {+ const items = documentFilterRules.value.map((rule) => ({ rule, condition: buildDocumentFilterCondition(rule) })).filter((item): item is { rule: DocumentFilterRule; condition: Record<string, unknown> } => !!item.condition);+ const structured = combineDocumentFilterConditions(items.map((item) => item.condition),items.map((item) => item.rule),);- appliedMongoFilter.value = structured;- mongoFilterBuilderOpen.value = false;+ appliedDocumentFilter.value = structured;+ documentFilterBuilderOpen.value = false;applyFilter();}-function clearMongoFilters(clearLocalFilter?: (columnIndex?: number) => void) {- appliedMongoFilter.value = null;- resetMongoFilterBuilder();+function clearDocumentFilters(clearLocalFilter?: (columnIndex?: number) => void) {+ appliedDocumentFilter.value = null;+ resetDocumentFilterBuilder();clearLocalFilter?.();applyFilter();}@@ -346,9 +260,9 @@ async function load() {loading.value = true;error.value = "";try {- const filter = currentMongoFilter();+ const filter = currentDocumentFilter();const sort = sortInput.value.trim() || undefined;- const result = await api.mongoFindDocuments(props.connectionId, props.database, props.collection, page.value * pageSize.value, pageSize.value, filter, sort);+ const result = await api.documentFindDocuments(props.connectionId, props.database, props.collection, page.value * pageSize.value, pageSize.value, filter, sort);const nextDocuments = result.documents.map(asRecord);documents.value = nextDocuments;if (nextDocuments.length > 0) {@@ -382,11 +296,7 @@ function paginate(offset: number, limit: number) {}function onSort(column: string, _columnIndex: number, direction: "asc" | "desc" | null) {- if (direction) {- sortInput.value = JSON.stringify({ [column]: direction === "asc" ? 1 : -1 });- } else {- sortInput.value = "";- }+ sortInput.value = documentStoreProvider.value.sortInputForColumn(column, direction);page.value = 0;load();}@@ -791,24 +701,24 @@ function resetTableSearchSplitWidth() {<template #search-bar="{ localFilterCount, hasLocalColumnFilters, localFilterSummaries, clearLocalFilter }: { localFilterCount: number; hasLocalColumnFilters: boolean; localFilterSummaries: LocalFilterSummary[]; clearLocalFilter: (columnIndex?: number) => void }"><div ref="tableSearchSplitContainerRef" class="flex flex-1 min-w-0"><div class="flex flex-1 items-center gap-1 px-2 py-0.5 min-w-0" :style="tableFindPaneStyle">- <Popover v-model:open="mongoFilterBuilderOpen">+ <Popover v-model:open="documentFilterBuilderOpen"><PopoverTrigger as-child><buttontype="button"class="relative flex h-5 w-5 shrink-0 items-center justify-center rounded border text-[11px] font-medium transition-colors"- :class="hasLocalColumnFilters || appliedMongoFilter ? 'border-primary/40 bg-primary/10 text-primary hover:bg-primary/15' : 'border-border/70 text-muted-foreground hover:bg-accent hover:text-foreground'"- @click="ensureMongoFilterRule"+ :class="hasLocalColumnFilters || appliedDocumentFilter ? 'border-primary/40 bg-primary/10 text-primary hover:bg-primary/15' : 'border-border/70 text-muted-foreground hover:bg-accent hover:text-foreground'"+ @click="ensureDocumentFilterRule"><Filter class="h-3 w-3" />- <span v-if="localFilterCount + mongoStructuredFilterCount" class="absolute -right-1 -top-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-primary px-1 text-[9px] leading-none text-primary-foreground">- {{ localFilterCount + mongoStructuredFilterCount }}+ <span v-if="localFilterCount + documentStructuredFilterCount" class="absolute -right-1 -top-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-primary px-1 text-[9px] leading-none text-primary-foreground">+ {{ localFilterCount + documentStructuredFilterCount }}</span></button></PopoverTrigger><PopoverContent align="start" class="w-[360px] max-w-[calc(100vw-24px)] gap-3 p-3"><div class="flex items-center justify-between gap-3"><div class="text-xs font-medium text-foreground">{{ t("grid.filter") }}</div>- <Button variant="ghost" size="sm" class="h-7 px-2 text-xs" @click="addMongoFilterRule">+ <Button variant="ghost" size="sm" class="h-7 px-2 text-xs" @click="addDocumentFilterRule"><Plus class="mr-1 h-3.5 w-3.5" />{{ t("grid.filterBuilderAddRule") }}</Button>@@ -845,15 +755,15 @@ function resetTableSearchSplitWidth() {</div></div>- <div v-if="mongoFilterRules.length" class="space-y-2">- <template v-for="(rule, index) in mongoFilterRules" :key="rule.id">+ <div v-if="documentFilterRules.length" class="space-y-2">+ <template v-for="(rule, index) in documentFilterRules" :key="rule.id"><div v-if="index > 0" class="flex justify-center"><Buttonvariant="ghost"size="sm"class="h-6 px-2 text-[11px] font-medium text-muted-foreground hover:text-foreground"@click="- updateMongoFilterRule(rule.id, {+ updateDocumentFilterRule(rule.id, {conjunction: rule.conjunction === 'AND' ? 'OR' : 'AND',})"@@ -862,41 +772,41 @@ function resetTableSearchSplitWidth() {</Button></div><div class="grid grid-cols-[minmax(0,1fr)_minmax(0,0.95fr)_minmax(0,1fr)_auto] items-center gap-1.5">- <Select :model-value="rule.fieldName" @update:model-value="(value: any) => updateMongoFilterRule(rule.id, { fieldName: String(value) })">+ <Select :model-value="rule.fieldName" @update:model-value="(value: any) => updateDocumentFilterRule(rule.id, { fieldName: String(value) })"><SelectTrigger class="h-8 w-full min-w-0 overflow-hidden text-xs [&_[data-slot=select-value]]:min-w-0 [&_[data-slot=select-value]]:truncate"><SelectValue :placeholder="t('grid.filterBuilderColumn')" /></SelectTrigger><SelectContent position="popper">- <SelectItem v-for="fieldName in mongoFilterFieldOptions" :key="fieldName" :value="fieldName">+ <SelectItem v-for="fieldName in documentFilterFieldOptions" :key="fieldName" :value="fieldName">{{ fieldName }}</SelectItem></SelectContent></Select>- <Select :model-value="rule.mode" @update:model-value="(value: any) => updateMongoFilterRule(rule.id, { mode: value as MongoFilterMode })">+ <Select :model-value="rule.mode" @update:model-value="(value: any) => updateDocumentFilterRule(rule.id, { mode: value as DocumentFilterMode })"><SelectTrigger class="h-8 w-full min-w-0 overflow-hidden text-xs [&_[data-slot=select-value]]:min-w-0 [&_[data-slot=select-value]]:truncate"><SelectValue /></SelectTrigger><SelectContent position="popper">- <SelectItem v-for="option in mongoFilterModeOptions" :key="option.value" :value="option.value">+ <SelectItem v-for="option in documentFilterModeOptions" :key="option.value" :value="option.value">{{ t(option.labelKey) }}</SelectItem></SelectContent></Select><Input- v-if="mongoFilterModeNeedsValue(rule.mode)"+ v-if="documentFilterModeNeedsValue(rule.mode)":model-value="rule.rawValue"class="h-8 min-w-0 text-xs":placeholder="t('grid.filterBuilderValue')"- @update:model-value="(value) => updateMongoFilterRule(rule.id, { rawValue: String(value ?? '') })"- @keydown.enter.prevent="applyMongoStructuredFilters"+ @update:model-value="(value) => updateDocumentFilterRule(rule.id, { rawValue: String(value ?? '') })"+ @keydown.enter.prevent="applyDocumentStructuredFilters"/><div v-else class="flex h-8 min-w-0 items-center overflow-hidden rounded-md border border-dashed px-2 text-xs text-muted-foreground"><span class="truncate">{{ t("grid.filterBuilderNoValue") }}</span></div>- <Button variant="ghost" size="icon" class="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive" :disabled="mongoFilterRules.length === 1" @click="removeMongoFilterRule(rule.id)">+ <Button variant="ghost" size="icon" class="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive" :disabled="documentFilterRules.length === 1" @click="removeDocumentFilterRule(rule.id)"><Trash2 class="h-3.5 w-3.5" /></Button></div>@@ -907,21 +817,21 @@ function resetTableSearchSplitWidth() {</div><div class="flex items-center justify-between gap-2 pt-1">- <Button variant="ghost" size="sm" class="h-8 px-2 text-xs" @click="clearMongoFilters(clearLocalFilter)">+ <Button variant="ghost" size="sm" class="h-8 px-2 text-xs" @click="clearDocumentFilters(clearLocalFilter)">{{ t("grid.clearFilter") }}</Button><div class="flex items-center gap-2">- <Button variant="ghost" size="sm" class="h-8 px-2 text-xs" @click="resetMongoFilterBuilder">+ <Button variant="ghost" size="sm" class="h-8 px-2 text-xs" @click="resetDocumentFilterBuilder">{{ t("grid.resetFilterBuilder") }}</Button>- <Button size="sm" class="h-8 px-3 text-xs" @click="applyMongoStructuredFilters">+ <Button size="sm" class="h-8 px-3 text-xs" @click="applyDocumentStructuredFilters">{{ t("grid.applyFilter") }}</Button></div></div></PopoverContent></Popover>- <span class="text-blue-600 dark:text-blue-400 text-xs font-medium select-none shrink-0">find</span>+ <span class="text-blue-600 dark:text-blue-400 text-xs font-medium select-none shrink-0">{{ documentStoreProvider.filterInputLabel }}</span><input v-model="filterInput" autocapitalize="off" autocorrect="off" spellcheck="false" class="flex-1 h-5 min-w-0 text-xs bg-transparent outline-none placeholder:text-muted-foreground/60 font-mono" placeholder="{}" @keydown.enter="applyFilter" /><buttonv-if="filterInput.trim()"@@ -937,14 +847,14 @@ function resetTableSearchSplitWidth() {<buttontype="button"class="group relative flex w-2 shrink-0 cursor-col-resize items-center justify-center border-l border-r border-border/80 bg-muted/15 hover:bg-primary/10 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary"- aria-label="Resize find and sort"+ aria-label="Resize document filter and sort"@mousedown="startTableSearchSplitResize"@dblclick.stop="resetTableSearchSplitWidth"><span class="h-5 w-px bg-border group-hover:bg-primary/60" /></button><div class="flex flex-1 items-center gap-1 px-2 py-0.5 min-w-0">- <span class="text-orange-600 dark:text-orange-400 text-xs font-medium select-none shrink-0">sort</span>+ <span class="text-orange-600 dark:text-orange-400 text-xs font-medium select-none shrink-0">{{ documentStoreProvider.sortInputLabel }}</span><input v-model="sortInput" autocapitalize="off" autocorrect="off" spellcheck="false" class="flex-1 h-5 min-w-0 text-xs bg-transparent outline-none placeholder:text-muted-foreground/60 font-mono" placeholder="{}" @keydown.enter="applyFilter" /><buttonv-if="sortInput.trim()"diff --git a/apps/desktop/src/components/mongo/JsonEditNode.vue b/apps/desktop/src/components/document/JsonEditNode.vuesimilarity index 100%rename from apps/desktop/src/components/mongo/JsonEditNode.vuerename to apps/desktop/src/components/document/JsonEditNode.vuediff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vueindex 47d4e08afb..5e24c0e8cc 100644--- a/apps/desktop/src/components/layout/ContentArea.vue+++ b/apps/desktop/src/components/layout/ContentArea.vue@@ -33,7 +33,7 @@ function preloadDataGridComponent() {const DataGrid = defineAsyncComponent(loadDataGridComponent);const RedisKeyBrowser = defineAsyncComponent(() => import("@/components/redis/RedisKeyBrowser.vue"));const EtcdKeyBrowser = defineAsyncComponent(() => import("@/components/etcd/EtcdKeyBrowser.vue"));-const MongoDocBrowser = defineAsyncComponent(() => import("@/components/mongo/MongoDocBrowser.vue"));+const DocumentBrowser = defineAsyncComponent(() => import("@/components/document/DocumentBrowser.vue"));const ObjectBrowser = defineAsyncComponent(() => import("@/components/objects/ObjectBrowser.vue"));const TableStructureEditor = defineAsyncComponent(() => import("@/components/structure/TableStructureEditor.vue"));const DatabaseUserAdmin = defineAsyncComponent(() => import("@/components/admin/DatabaseUserAdmin.vue"));@@ -823,7 +823,7 @@ defineExpose({ focusSearch, refreshData, handleModRTarget });<!-- Document mode: MongoDB collections and Elasticsearch indices --><template v-else-if="activeTab.mode === 'mongo'"><div class="flex-1 min-h-0">- <MongoDocBrowser :key="activeTab.id" :connection-id="activeTab.connectionId" :database="activeTab.database" :collection="activeTab.sql" :database-type="activeEffectiveDatabaseType" />+ <DocumentBrowser :key="activeTab.id" :connection-id="activeTab.connectionId" :database="activeTab.database" :collection="activeTab.sql" :database-type="activeEffectiveDatabaseType" /></div></template>diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex a43d7cb00f..7448bd985c 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -257,6 +257,7 @@ export const etcdDelete = forward("etcdDelete");// MongoDBexport const mongoListDatabases = forward("mongoListDatabases");export const mongoListCollections = forward("mongoListCollections");+export const documentFindDocuments = forward("documentFindDocuments");export const mongoFindDocuments = forward("mongoFindDocuments");export const mongoAggregateDocuments = forward("mongoAggregateDocuments");export const mongoInsertDocument = forward("mongoInsertDocument");diff --git a/apps/desktop/src/lib/documentStoreProvider.ts b/apps/desktop/src/lib/documentStoreProvider.tsnew file mode 100644index 0000000000..777072b96f--- /dev/null+++ b/apps/desktop/src/lib/documentStoreProvider.ts@@ -0,0 +1,258 @@+import type { ComposerTranslation } from "vue-i18n";+import type { DatabaseType } from "@/types/database";++export type DocumentStoreKind = "mongodb" | "elasticsearch";+export type DocumentFilterMode = "equals" | "not-equals" | "like" | "not-like" | "greater-than" | "less-than" | "is-null" | "is-not-null";++export type DocumentFilterRule = {+ id: string;+ fieldName: string;+ mode: DocumentFilterMode;+ rawValue: string;+ conjunction: "AND" | "OR";+};++export type DocumentStoreQueryPreviewOptions = {+ collection: string;+ filterJson?: string;+ sortJson?: string;+ skip: number;+ limit: number;+};++export type DocumentStoreProvider = {+ kind: DocumentStoreKind;+ filterInputLabel: string;+ sortInputLabel: string;+ documentsLabel(options: { total: number; t: ComposerTranslation }): string;+ queryPreview(options: DocumentStoreQueryPreviewOptions): string;+ sortInputForColumn(column: string, direction: "asc" | "desc" | null): string;+};++export const documentFilterModeOptions: Array<{ value: DocumentFilterMode; labelKey: string }> = [+ { value: "equals", labelKey: "grid.filterBuilderEquals" },+ { value: "not-equals", labelKey: "grid.filterBuilderNotEquals" },+ { value: "like", labelKey: "grid.filterBuilderContains" },+ { value: "not-like", labelKey: "grid.filterBuilderNotContains" },+ { value: "greater-than", labelKey: "grid.filterBuilderGreaterThan" },+ { value: "less-than", labelKey: "grid.filterBuilderLessThan" },+ { value: "is-null", labelKey: "grid.filterBuilderIsNull" },+ { value: "is-not-null", labelKey: "grid.filterBuilderIsNotNull" },+];++const mongoDocumentProvider: DocumentStoreProvider = {+ kind: "mongodb",+ filterInputLabel: "find",+ sortInputLabel: "sort",+ documentsLabel: ({ total, t }) => t("mongo.documents", { count: total }),+ queryPreview: ({ collection, filterJson, sortJson, skip, limit }) => {+ const parts = [`db.${collection}.find(${filterJson || "{}"})`];+ if (sortJson?.trim()) parts.push(`.sort(${sortJson.trim()})`);+ parts.push(`.skip(${skip}).limit(${limit})`);+ return parts.join("");+ },+ sortInputForColumn: (column, direction) => (direction ? JSON.stringify({ [column]: direction === "asc" ? 1 : -1 }) : ""),+};++const elasticsearchDocumentProvider: DocumentStoreProvider = {+ kind: "elasticsearch",+ filterInputLabel: "filter",+ sortInputLabel: "sort",+ documentsLabel: () => "Documents",+ queryPreview: ({ collection, filterJson, sortJson, skip, limit }) => {+ const body = safeElasticsearchSearchBodyFromDocumentQuery({ filterJson, sortJson, skip, limit });+ return `POST /${collection}/_search\n${JSON.stringify(body, null, 2)}`;+ },+ sortInputForColumn: mongoDocumentProvider.sortInputForColumn,+};++export function documentStoreProviderFor(databaseType?: DatabaseType): DocumentStoreProvider {+ return databaseType === "elasticsearch" ? elasticsearchDocumentProvider : mongoDocumentProvider;+}++export function defaultDocumentFilterRule(id: string, fieldName = ""): DocumentFilterRule {+ return {+ id,+ fieldName,+ mode: "equals",+ rawValue: "",+ conjunction: "AND",+ };+}++export function documentFilterModeNeedsValue(mode: DocumentFilterMode): boolean {+ return mode !== "is-null" && mode !== "is-not-null";+}++export function buildDocumentFilterCondition(rule: DocumentFilterRule): Record<string, unknown> | null {+ if (!rule.fieldName) return null;+ if (documentFilterModeNeedsValue(rule.mode) && !rule.rawValue.trim()) return null;+ const value = documentFilterModeNeedsValue(rule.mode) ? parseDocumentFilterValue(rule.rawValue) : null;+ switch (rule.mode) {+ case "equals":+ return { [rule.fieldName]: value };+ case "not-equals":+ return { [rule.fieldName]: { $ne: value } };+ case "like":+ return { [rule.fieldName]: { $regex: String(value), $options: "i" } };+ case "not-like":+ return { [rule.fieldName]: { $not: { $regex: String(value), $options: "i" } } };+ case "greater-than":+ return { [rule.fieldName]: { $gt: value } };+ case "less-than":+ return { [rule.fieldName]: { $lt: value } };+ case "is-null":+ return { [rule.fieldName]: null };+ case "is-not-null":+ return { [rule.fieldName]: { $ne: null } };+ }+}++export function combineDocumentFilterConditions(conditions: Record<string, unknown>[], rules: Pick<DocumentFilterRule, "conjunction">[]): Record<string, unknown> | null {+ if (conditions.length === 0) return null;+ let result = conditions[0];+ for (let i = 1; i < conditions.length; i++) {+ const operator = rules[i]?.conjunction === "OR" ? "$or" : "$and";+ result = { [operator]: [result, conditions[i]] };+ }+ return result;+}++export function parseDocumentFilterInput(input: string): Record<string, unknown> {+ const trimmed = input.trim();+ if (!trimmed) return {};+ const parsed = JSON.parse(trimmed);+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {};+}++export function currentDocumentFilterJson(input: string, structured: Record<string, unknown> | null): string | undefined {+ const manual = parseDocumentFilterInput(input);+ const filter = structured ? (Object.keys(manual).length ? { $and: [manual, structured] } : structured) : manual;+ return Object.keys(filter).length ? JSON.stringify(filter) : undefined;+}++function parseDocumentFilterValue(raw: string): unknown {+ const trimmed = raw.trim();+ if (!trimmed) return "";+ try {+ return JSON.parse(trimmed);+ } catch {+ return trimmed;+ }+}++export function elasticsearchSearchBodyFromDocumentQuery(options: Pick<DocumentStoreQueryPreviewOptions, "filterJson" | "sortJson" | "skip" | "limit">): Record<string, unknown> {+ const body: Record<string, unknown> = {+ from: options.skip,+ size: options.limit,+ };+ const query = elasticsearchQueryFromDocumentFilter(options.filterJson);+ if (query) body.query = query;+ body.sort = elasticsearchSortFromDocumentSort(options.sortJson);+ return body;+}++function safeElasticsearchSearchBodyFromDocumentQuery(options: Pick<DocumentStoreQueryPreviewOptions, "filterJson" | "sortJson" | "skip" | "limit">): Record<string, unknown> {+ try {+ return elasticsearchSearchBodyFromDocumentQuery(options);+ } catch {+ return {+ from: options.skip,+ size: options.limit,+ sort: ["_doc"],+ };+ }+}++function elasticsearchQueryFromDocumentFilter(filterJson?: string): Record<string, unknown> | null {+ const trimmed = filterJson?.trim();+ if (!trimmed || trimmed === "{}") return null;+ const parsed = JSON.parse(trimmed);+ if (!isPlainRecord(parsed) || Object.keys(parsed).length === 0) return null;+ return translateDocumentFilterToElasticsearchQuery(parsed);+}++function translateDocumentFilterToElasticsearchQuery(filter: Record<string, unknown>): Record<string, unknown> {+ const filters: Record<string, unknown>[] = [];+ for (const [key, value] of Object.entries(filter)) {+ if (key === "$and") {+ filters.push(...translateLogicalArrayToElasticsearch("$and", value));+ } else if (key === "$or") {+ const should = translateLogicalArrayToElasticsearch("$or", value);+ if (should.length > 0) filters.push({ bool: { should, minimum_should_match: 1 } });+ } else {+ filters.push(translateFieldFilterToElasticsearchQuery(key, value));+ }+ }+ if (filters.length === 1) return filters[0];+ return { bool: { filter: filters } };+}++function translateLogicalArrayToElasticsearch(operator: "$and" | "$or", value: unknown): Record<string, unknown>[] {+ if (!Array.isArray(value)) throw new Error(`${operator} must be an array`);+ return value.filter(isPlainRecord).map(translateDocumentFilterToElasticsearchQuery);+}++function translateFieldFilterToElasticsearchQuery(field: string, value: unknown): Record<string, unknown> {+ if (!isPlainRecord(value) || !Object.keys(value).some((key) => key.startsWith("$"))) {+ return termOrNullQuery(field, value);+ }++ const filter: Record<string, unknown>[] = [];+ const mustNot: Record<string, unknown>[] = [];+ const range: Record<string, unknown> = {};+ for (const [operator, operatorValue] of Object.entries(value)) {+ if (operator === "$options") continue;+ if (operator === "$ne") {+ if (operatorValue === null) filter.push({ exists: { field } });+ else mustNot.push({ term: { [field]: operatorValue } });+ } else if (operator === "$gt" || operator === "$gte" || operator === "$lt" || operator === "$lte") {+ range[operator.slice(1)] = operatorValue;+ } else if (operator === "$regex") {+ filter.push(wildcardQuery(field, operatorValue, value.$options));+ } else if (operator === "$not") {+ if (isPlainRecord(operatorValue) && "$regex" in operatorValue) {+ mustNot.push(wildcardQuery(field, operatorValue.$regex, operatorValue.$options ?? value.$options));+ }+ }+ }+ if (Object.keys(range).length > 0) filter.push({ range: { [field]: range } });+ if (filter.length === 1 && mustNot.length === 0) return filter[0];+ if (filter.length === 0 && mustNot.length > 0) return { bool: { must_not: mustNot } };+ const bool: Record<string, unknown> = {};+ if (filter.length > 0) bool.filter = filter;+ if (mustNot.length > 0) bool.must_not = mustNot;+ return { bool };+}++function termOrNullQuery(field: string, value: unknown): Record<string, unknown> {+ if (value === null) return { bool: { must_not: [{ exists: { field } }] } };+ return { term: { [field]: value } };+}++function wildcardQuery(field: string, value: unknown, options: unknown): Record<string, unknown> {+ const pattern = String(value ?? "");+ const wildcard = pattern.startsWith("*") || pattern.endsWith("*") ? pattern : `*${pattern}*`;+ return {+ wildcard: {+ [field]: {+ value: wildcard,+ case_insensitive: typeof options === "string" && options.toLowerCase().includes("i"),+ },+ },+ };+}++function elasticsearchSortFromDocumentSort(sortJson?: string): unknown[] {+ const trimmed = sortJson?.trim();+ if (!trimmed || trimmed === "{}") return ["_doc"];+ const parsed = JSON.parse(trimmed);+ if (!isPlainRecord(parsed)) return ["_doc"];+ return Object.entries(parsed).map(([field, direction]) => ({+ [field]: { order: direction === -1 || (typeof direction === "string" && direction.toLowerCase() === "desc") ? "desc" : "asc" },+ }));+}++function isPlainRecord(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}diff --git a/apps/desktop/src/lib/http.ts b/apps/desktop/src/lib/http.tsindex 7f25491d5c..d13fdc76bb 100644--- a/apps/desktop/src/lib/http.ts+++ b/apps/desktop/src/lib/http.ts@@ -1259,6 +1259,10 @@ export async function mongoFindDocuments(connectionId: string, database: string,return post("/api/mongo/find-documents", { connectionId, database, collection, skip, limit, filter, sort });}+export async function documentFindDocuments(connectionId: string, database: string, collection: string, skip: number, limit: number, filter?: string, sort?: string): Promise<MongoDocumentResult> {+ return post("/api/document-store/find-documents", { connectionId, database, collection, skip, limit, filter, sort });+}+export async function mongoAggregateDocuments(connectionId: string, database: string, collection: string, pipelineJson: string, maxRows?: number): Promise<MongoDocumentResult> {return post("/api/mongo/aggregate-documents", { connectionId, database, collection, pipelineJson, maxRows });}diff --git a/apps/desktop/src/lib/tauri.ts b/apps/desktop/src/lib/tauri.tsindex e9cc2dd5cb..0ea8ceb32b 100644--- a/apps/desktop/src/lib/tauri.ts+++ b/apps/desktop/src/lib/tauri.ts@@ -1158,6 +1158,10 @@ export async function mongoFindDocuments(connectionId: string, database: string,return invoke("mongo_find_documents", { connectionId, database, collection, skip, limit, filter, sort });}+export async function documentFindDocuments(connectionId: string, database: string, collection: string, skip: number, limit: number, filter?: string, sort?: string): Promise<MongoDocumentResult> {+ return invoke("document_find_documents", { connectionId, database, collection, skip, limit, filter, sort });+}+export async function mongoAggregateDocuments(connectionId: string, database: string, collection: string, pipelineJson: string, maxRows?: number): Promise<MongoDocumentResult> {return invoke("mongo_aggregate_documents", { connectionId, database, collection, pipelineJson, maxRows });}diff --git a/crates/dbx-core/src/db/elasticsearch_driver.rs b/crates/dbx-core/src/db/elasticsearch_driver.rsindex 493a401f91..e7f20a639f 100644--- a/crates/dbx-core/src/db/elasticsearch_driver.rs+++ b/crates/dbx-core/src/db/elasticsearch_driver.rs@@ -322,12 +322,10 @@ pub async fn find_documents(index: &str,skip: u64,limit: i64,+ filter: Option<&str>,+ sort: Option<&str>,) -> Result<MongoDocumentResult, String> {- let body = serde_json::json!({- "from": skip,- "size": limit,- "sort": ["_doc"],- });+ let body = build_find_documents_body(skip, limit, filter, sort)?;let path = format!("/{}/_search", index);let resp = client.post(&path).json(&body).send().await.map_err(|e| format!("Elasticsearch request failed: {e}"))?;@@ -356,6 +354,223 @@ pub async fn find_documents(Ok(MongoDocumentResult { documents, total: result.hits.total.value })}+fn build_find_documents_body(+ skip: u64,+ limit: i64,+ filter: Option<&str>,+ sort: Option<&str>,+) -> Result<serde_json::Value, String> {+ let mut body = serde_json::Map::new();+ body.insert("from".to_string(), serde_json::json!(skip));+ body.insert("size".to_string(), serde_json::json!(limit));++ if let Some(query) = elasticsearch_query_from_document_filter(filter)? {+ body.insert("query".to_string(), query);+ }++ body.insert("sort".to_string(), elasticsearch_sort_from_document_sort(sort)?);+ Ok(serde_json::Value::Object(body))+}++fn elasticsearch_query_from_document_filter(filter: Option<&str>) -> Result<Option<serde_json::Value>, String> {+ let Some(filter) = filter.map(str::trim).filter(|value| !value.is_empty()) else {+ return Ok(None);+ };+ let value: serde_json::Value = serde_json::from_str(filter).map_err(|e| format!("Invalid filter JSON: {e}"))?;+ let query = translate_document_filter_value(&value)?;+ Ok(match query {+ Some(query) => Some(query),+ None => None,+ })+}++fn translate_document_filter_value(value: &serde_json::Value) -> Result<Option<serde_json::Value>, String> {+ let Some(object) = value.as_object() else {+ return Err("Elasticsearch filter must be a JSON object".to_string());+ };+ if object.is_empty() {+ return Ok(None);+ }++ let mut must = Vec::new();+ for (key, value) in object {+ match key.as_str() {+ "$and" => must.extend(translate_logical_filter_array("$and", value)?),+ "$or" => {+ let should = translate_logical_filter_array("$or", value)?;+ if !should.is_empty() {+ must.push(serde_json::json!({ "bool": { "should": should, "minimum_should_match": 1 } }));+ }+ }+ key if key.starts_with('$') => {+ return Err(format!("Unsupported Elasticsearch filter operator: {key}"));+ }+ field => must.push(translate_field_filter(field, value)?),+ }+ }++ Ok(single_or_bool_filter(must))+}++fn translate_logical_filter_array(operator: &str, value: &serde_json::Value) -> Result<Vec<serde_json::Value>, String> {+ let items = value.as_array().ok_or_else(|| format!("{operator} must be an array"))?;+ let mut queries = Vec::new();+ for item in items {+ if let Some(query) = translate_document_filter_value(item)? {+ queries.push(query);+ }+ }+ Ok(queries)+}++fn translate_field_filter(field: &str, value: &serde_json::Value) -> Result<serde_json::Value, String> {+ let Some(object) = value.as_object() else {+ return Ok(term_or_null_query(field, value));+ };+ if object.keys().any(|key| key.starts_with('$')) {+ return translate_field_operator_filter(field, object);+ }+ Ok(term_or_null_query(field, value))+}++fn translate_field_operator_filter(+ field: &str,+ object: &serde_json::Map<String, serde_json::Value>,+) -> Result<serde_json::Value, String> {+ let mut must = Vec::new();+ let mut must_not = Vec::new();+ let mut range = serde_json::Map::new();++ for (operator, value) in object {+ match operator.as_str() {+ "$options" => {}+ "$ne" => {+ if value.is_null() {+ must.push(serde_json::json!({ "exists": { "field": field } }));+ } else {+ must_not.push(serde_json::json!({ "term": { field: value.clone() } }));+ }+ }+ "$gt" => {+ range.insert("gt".to_string(), value.clone());+ }+ "$gte" => {+ range.insert("gte".to_string(), value.clone());+ }+ "$lt" => {+ range.insert("lt".to_string(), value.clone());+ }+ "$lte" => {+ range.insert("lte".to_string(), value.clone());+ }+ "$regex" => {+ must.push(regex_like_query(field, value, object.get("$options"))?);+ }+ "$not" => {+ let Some(inner) = value.as_object() else {+ return Err("$not must be a JSON object".to_string());+ };+ if let Some(regex) = inner.get("$regex") {+ must_not.push(regex_like_query(+ field,+ regex,+ inner.get("$options").or_else(|| object.get("$options")),+ )?);+ } else {+ return Err("Unsupported Elasticsearch $not filter".to_string());+ }+ }+ other => return Err(format!("Unsupported Elasticsearch field filter operator: {other}")),+ }+ }++ if !range.is_empty() {+ must.push(serde_json::json!({ "range": { field: serde_json::Value::Object(range) } }));+ }++ match (must.len(), must_not.is_empty()) {+ (1, true) => Ok(must.remove(0)),+ (0, false) => Ok(serde_json::json!({ "bool": { "must_not": must_not } })),+ _ => {+ let mut bool_query = serde_json::Map::new();+ if !must.is_empty() {+ bool_query.insert("must".to_string(), serde_json::Value::Array(must));+ }+ if !must_not.is_empty() {+ bool_query.insert("must_not".to_string(), serde_json::Value::Array(must_not));+ }+ Ok(serde_json::json!({ "bool": bool_query }))+ }+ }+}++fn term_or_null_query(field: &str, value: &serde_json::Value) -> serde_json::Value {+ if value.is_null() {+ serde_json::json!({ "bool": { "must_not": [{ "exists": { "field": field } }] } })+ } else {+ serde_json::json!({ "term": { field: value.clone() } })+ }+}++fn regex_like_query(+ field: &str,+ value: &serde_json::Value,+ options: Option<&serde_json::Value>,+) -> Result<serde_json::Value, String> {+ let pattern = value.as_str().ok_or_else(|| "$regex must be a string for Elasticsearch filters".to_string())?;+ let case_insensitive = options+ .and_then(serde_json::Value::as_str)+ .is_some_and(|value| value.chars().any(|ch| ch.eq_ignore_ascii_case(&'i')));+ Ok(serde_json::json!({+ "wildcard": {+ field: {+ "value": wildcard_contains_pattern(pattern),+ "case_insensitive": case_insensitive+ }+ }+ }))+}++fn wildcard_contains_pattern(pattern: &str) -> String {+ if pattern.starts_with('*') || pattern.ends_with('*') {+ pattern.to_string()+ } else {+ format!("*{}*", pattern)+ }+}++fn single_or_bool_filter(mut queries: Vec<serde_json::Value>) -> Option<serde_json::Value> {+ match queries.len() {+ 0 => None,+ 1 => queries.pop(),+ _ => Some(serde_json::json!({ "bool": { "filter": queries } })),+ }+}++fn elasticsearch_sort_from_document_sort(sort: Option<&str>) -> Result<serde_json::Value, String> {+ let Some(sort) = sort.map(str::trim).filter(|value| !value.is_empty()) else {+ return Ok(serde_json::json!(["_doc"]));+ };+ let value: serde_json::Value = serde_json::from_str(sort).map_err(|e| format!("Invalid sort JSON: {e}"))?;+ let object = value.as_object().ok_or_else(|| "Elasticsearch sort must be a JSON object".to_string())?;+ if object.is_empty() {+ return Ok(serde_json::json!(["_doc"]));+ }++ let items = object+ .iter()+ .map(|(field, direction)| {+ let order = match direction {+ serde_json::Value::Number(number) if number.as_i64().unwrap_or(1) < 0 => "desc",+ serde_json::Value::String(value) if value.eq_ignore_ascii_case("desc") => "desc",+ _ => "asc",+ };+ serde_json::json!({ field: { "order": order } })+ })+ .collect::<Vec<_>>();+ Ok(serde_json::Value::Array(items))+}+pub async fn insert_document(client: &EsClient, index: &str, doc_json: &str) -> Result<String, String> {let doc: serde_json::Value = serde_json::from_str(doc_json).map_err(|e| format!("Invalid JSON: {e}"))?;@@ -1139,8 +1354,10 @@ fn parse_aggregations(aggs: &serde_json::Map<String, serde_json::Value>) -> (Vec#[cfg(test)]mod tests {use super::{- elasticsearch_accept_invalid_certs, elasticsearch_base_url_fallbacks, redact_elasticsearch_url, EsClient,+ build_find_documents_body, elasticsearch_accept_invalid_certs, elasticsearch_base_url_fallbacks,+ redact_elasticsearch_url, EsClient,};+ use serde_json::json;use std::time::Duration;#[test]@@ -1189,4 +1406,88 @@ mod tests {"https://user:password@localhost:9200");}++ #[test]+ fn builds_elasticsearch_find_body_with_filter_and_sort() {+ let body = build_find_documents_body(20, 10, Some(r#"{"city":"长治"}"#), Some(r#"{"created_at":-1}"#)).unwrap();++ assert_eq!(+ body,+ json!({+ "from": 20,+ "size": 10,+ "query": { "term": { "city": "长治" } },+ "sort": [{ "created_at": { "order": "desc" } }]+ })+ );+ }++ #[test]+ fn builds_elasticsearch_find_body_with_structured_filter_operators() {+ let body = build_find_documents_body(+ 0,+ 100,+ Some(+ r#"{+ "$and": [+ {"city": {"$ne": "上海"}},+ {"age": {"$gt": 18, "$lte": 60}},+ {"name": {"$not": {"$regex": "test", "$options": "i"}}}+ ]+ }"#,+ ),+ None,+ )+ .unwrap();++ assert_eq!(+ body,+ json!({+ "from": 0,+ "size": 100,+ "query": {+ "bool": {+ "filter": [+ { "bool": { "must_not": [{ "term": { "city": "上海" } }] } },+ { "range": { "age": { "gt": 18, "lte": 60 } } },+ {+ "bool": {+ "must_not": [+ {+ "wildcard": {+ "name": {+ "value": "*test*",+ "case_insensitive": true+ }+ }+ }+ ]+ }+ }+ ]+ }+ },+ "sort": ["_doc"]+ })+ );+ }++ #[test]+ fn builds_elasticsearch_find_body_with_or_filter() {+ let body =+ build_find_documents_body(0, 50, Some(r#"{"$or":[{"city":"长治"},{"city":"上海"}]}"#), None).unwrap();++ assert_eq!(+ body["query"],+ json!({+ "bool": {+ "should": [+ { "term": { "city": "长治" } },+ { "term": { "city": "上海" } }+ ],+ "minimum_should_match": 1+ }+ })+ );+ }}diff --git a/crates/dbx-core/src/mongo_ops.rs b/crates/dbx-core/src/mongo_ops.rsindex f932dba63f..95a0cb4977 100644--- a/crates/dbx-core/src/mongo_ops.rs+++ b/crates/dbx-core/src/mongo_ops.rs@@ -72,7 +72,7 @@ pub async fn mongo_list_collections_core(}#[allow(clippy::too_many_arguments)]-pub async fn mongo_find_documents_core(+pub async fn document_find_documents_core(state: &AppState,connection_id: &str,database: &str,@@ -90,7 +90,7 @@ pub async fn mongo_find_documents_core(PoolKind::Elasticsearch(client) => {let client = client.clone();drop(connections);- elasticsearch_driver::find_documents(&client, collection, skip, limit).await+ elasticsearch_driver::find_documents(&client, collection, skip, limit, filter, sort).await}PoolKind::Agent(client) => {let mut client = client.lock().await;@@ -109,6 +109,19 @@ pub async fn mongo_find_documents_core(}}+pub async fn mongo_find_documents_core(+ state: &AppState,+ connection_id: &str,+ database: &str,+ collection: &str,+ skip: u64,+ limit: i64,+ filter: Option<&str>,+ sort: Option<&str>,+) -> Result<MongoDocumentResult, String> {+ document_find_documents_core(state, connection_id, database, collection, skip, limit, filter, sort).await+}+pub async fn mongo_aggregate_documents_core(state: &AppState,connection_id: &str,diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rsindex 8281c869e1..2cf90d7a75 100644--- a/crates/dbx-web/src/main.rs+++ b/crates/dbx-web/src/main.rs@@ -257,6 +257,7 @@ async fn main() {// MongoDB.route("/mongo/list-databases", post(routes::mongo::list_databases)).route("/mongo/list-collections", post(routes::mongo::list_collections))+ .route("/document-store/find-documents", post(routes::mongo::document_find_documents)).route("/mongo/find-documents", post(routes::mongo::find_documents)).route("/mongo/aggregate-documents", post(routes::mongo::aggregate_documents)).route("/mongo/insert-document", post(routes::mongo::insert_document))diff --git a/crates/dbx-web/src/routes/mongo.rs b/crates/dbx-web/src/routes/mongo.rsindex 03abb1799d..b09d26315a 100644--- a/crates/dbx-web/src/routes/mongo.rs+++ b/crates/dbx-web/src/routes/mongo.rs@@ -153,6 +153,25 @@ pub async fn find_documents(Ok(Json(serde_json::to_value(result).map_err(|e| AppError(e.to_string()))?))}+pub async fn document_find_documents(+ State(state): State<Arc<WebState>>,+ Json(req): Json<MongoFindRequest>,+) -> Result<Json<serde_json::Value>, AppError> {+ let result = dbx_core::mongo_ops::document_find_documents_core(+ &state.app,+ &req.connection_id,+ &req.database,+ &req.collection,+ req.skip.unwrap_or(0),+ req.limit.unwrap_or(50),+ req.filter.as_deref(),+ req.sort.as_deref(),+ )+ .await+ .map_err(AppError)?;+ Ok(Json(serde_json::to_value(result).map_err(|e| AppError(e.to_string()))?))+}+pub async fn aggregate_documents(State(state): State<Arc<WebState>>,Json(req): Json<MongoAggregateRequest>,diff --git a/packages/app-tests/documentStoreProvider.test.ts b/packages/app-tests/documentStoreProvider.test.tsnew file mode 100644index 0000000000..4e93e8d745--- /dev/null+++ b/packages/app-tests/documentStoreProvider.test.ts@@ -0,0 +1,70 @@+import { strict as assert } from "node:assert";+import { test } from "vitest";+import { buildDocumentFilterCondition, combineDocumentFilterConditions, currentDocumentFilterJson, documentStoreProviderFor, elasticsearchSearchBodyFromDocumentQuery, type DocumentFilterRule } from "../../apps/desktop/src/lib/documentStoreProvider.ts";++function rule(patch: Partial<DocumentFilterRule>): DocumentFilterRule {+ return {+ id: "rule-1",+ fieldName: "city",+ mode: "equals",+ rawValue: "长治",+ conjunction: "AND",+ ...patch,+ };+}++test("selects MongoDB and Elasticsearch document store providers", () => {+ assert.equal(documentStoreProviderFor("mongodb").kind, "mongodb");+ assert.equal(documentStoreProviderFor("elasticsearch").kind, "elasticsearch");+});++test("providers build store-specific query previews", () => {+ const t = ((key: string, params?: Record<string, unknown>) => `${key}:${params?.count ?? ""}`) as never;+ const mongo = documentStoreProviderFor("mongodb");+ const elasticsearch = documentStoreProviderFor("elasticsearch");++ assert.equal(mongo.documentsLabel({ total: 7, t }), "mongo.documents:7");+ assert.equal(mongo.queryPreview({ collection: "orders", filterJson: '{"city":"长治"}', sortJson: '{"createdAt":-1}', skip: 20, limit: 10 }), 'db.orders.find({"city":"长治"}).sort({"createdAt":-1}).skip(20).limit(10)');+ assert.equal(elasticsearch.documentsLabel({ total: 7, t }), "Documents");+ assert.equal(elasticsearch.filterInputLabel, "filter");+ assert.equal(+ elasticsearch.queryPreview({ collection: "orders", filterJson: '{"city":"长治"}', sortJson: '{"createdAt":-1}', skip: 20, limit: 10 }),+ ["POST /orders/_search", "{", ' "from": 20,', ' "size": 10,', ' "query": {', ' "term": {', ' "city": "长治"', " }", " },", ' "sort": [', " {", ' "createdAt": {', ' "order": "desc"', " }", " }", " ]", "}"].join("\n"),+ );+});++test("builds reusable document filter conditions", () => {+ assert.deepEqual(buildDocumentFilterCondition(rule({})), { city: "长治" });+ assert.deepEqual(buildDocumentFilterCondition(rule({ mode: "not-like", rawValue: "test" })), {+ city: { $not: { $regex: "test", $options: "i" } },+ });+ assert.deepEqual(buildDocumentFilterCondition(rule({ mode: "is-not-null", rawValue: "" })), { city: { $ne: null } });+});++test("combines manual and structured document filters", () => {+ const structured = combineDocumentFilterConditions([{ city: "长治" }, { status: "active" }], [rule({}), rule({ fieldName: "status", rawValue: "active", conjunction: "OR" })]);++ assert.deepEqual(structured, { $or: [{ city: "长治" }, { status: "active" }] });+ assert.equal(currentDocumentFilterJson('{"tenant":"a"}', structured), JSON.stringify({ $and: [{ tenant: "a" }, structured] }));+});++test("translates document filters to Elasticsearch search body previews", () => {+ assert.deepEqual(+ elasticsearchSearchBodyFromDocumentQuery({+ filterJson: JSON.stringify({ $and: [{ city: { $ne: "上海" } }, { age: { $gt: 18, $lte: 60 } }] }),+ sortJson: '{"createdAt":-1}',+ skip: 0,+ limit: 50,+ }),+ {+ from: 0,+ size: 50,+ query: {+ bool: {+ filter: [{ bool: { must_not: [{ term: { city: "上海" } }] } }, { range: { age: { gt: 18, lte: 60 } } }],+ },+ },+ sort: [{ createdAt: { order: "desc" } }],+ },+ );+});diff --git a/src-tauri/src/commands/mongo_cmd.rs b/src-tauri/src/commands/mongo_cmd.rsindex d443344384..0fc4eeae2f 100644--- a/src-tauri/src/commands/mongo_cmd.rs+++ b/src-tauri/src/commands/mongo_cmd.rs@@ -46,6 +46,31 @@ pub async fn mongo_find_documents(.await}+#[tauri::command]+#[allow(clippy::too_many_arguments)]+pub async fn document_find_documents(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ database: String,+ collection: String,+ skip: u64,+ limit: i64,+ filter: Option<String>,+ sort: Option<String>,+) -> Result<MongoDocumentResult, String> {+ dbx_core::mongo_ops::document_find_documents_core(+ &state,+ &connection_id,+ &database,+ &collection,+ skip,+ limit,+ filter.as_deref(),+ sort.as_deref(),+ )+ .await+}+#[tauri::command]pub async fn mongo_aggregate_documents(state: State<'_, Arc<AppState>>,diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 05a3f93403..06594792ea 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -476,6 +476,7 @@ pub fn run() {commands::saved_sql::sync_saved_sql_directory,commands::mongo_cmd::mongo_list_databases,commands::mongo_cmd::mongo_list_collections,+ commands::mongo_cmd::document_find_documents,commands::mongo_cmd::mongo_find_documents,commands::mongo_cmd::mongo_aggregate_documents,commands::mongo_cmd::mongo_insert_document,