feat(search): implement multi-chunk semantic search with segment timestamps

This commit is contained in:
yiling
2026-05-29 11:00:23 +08:00
parent 1855ca1405
commit 4f9c4db9ce
10 changed files with 690 additions and 117 deletions
+2
View File
@@ -66,6 +66,8 @@ export const assetInfoSchema = z.object({
creator: userInfoSchema.nullable().optional(),
fieldValues: z.array(fieldValueInfoSchema).optional(),
sortIndex: z.string().optional().nullable(),
startTime: z.number().optional().nullable(),
endTime: z.number().optional().nullable(),
media: z
.object({
+1 -4
View File
@@ -44,9 +44,6 @@ export type SearchOperator = z.infer<typeof searchOperatorSchema>
export const searchAssetTypeSchema = z.enum(['file', 'folder'])
export type SearchAssetType = z.infer<typeof searchAssetTypeSchema>
export const searchModeSchema = z.enum(['name', 'content', 'all']).optional().default('name')
export type SearchMode = z.infer<typeof searchModeSchema>
export const searchFilterSchema = z.object({
operator: searchOperatorSchema.optional().default('AND'),
conditions: z.array(searchConditionSchema).optional().default([]),
@@ -56,7 +53,7 @@ export const searchFilterSchema = z.object({
showSymlink: z.boolean().optional(),
recursively: z.boolean().optional().default(true),
query: z.string().optional(),
searchMode: searchModeSchema.default('name'),
isSemantic: z.boolean().optional().default(false),
})
export type SearchFilter = z.infer<typeof searchFilterSchema>
+2 -2
View File
@@ -59,7 +59,7 @@ describe('AuthzService', () => {
projectId: project.id,
filter: {
sourceFolderId: 'root',
searchFilter: { conditions: [], operator: 'AND', recursively: true, searchMode: 'name' },
searchFilter: { conditions: [], operator: 'AND', recursively: true, isSemantic: false },
},
},
})
@@ -263,7 +263,7 @@ describe('AuthzService', () => {
projectId: project.id,
filter: {
sourceFolderId: 'root',
searchFilter: { conditions: [], operator: 'AND', recursively: true, searchMode: 'name' },
searchFilter: { conditions: [], operator: 'AND', recursively: true, isSemantic: false },
},
},
})
+4 -4
View File
@@ -48,7 +48,7 @@ describe('CollectionService', () => {
operator: 'AND',
conditions: [{ field: 'name', operator: 'contains', value: 'test' }],
recursively: true,
searchMode: 'name',
isSemantic: false,
},
},
})
@@ -69,7 +69,7 @@ describe('CollectionService', () => {
operator: 'AND',
conditions: [{ field: 'rating', operator: 'eq', value: 5 }],
recursively: true,
searchMode: 'name',
isSemantic: false,
},
},
})
@@ -92,7 +92,7 @@ describe('CollectionService', () => {
name: `Collection ${i}`,
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: { operator: 'AND', conditions: [], recursively: true, searchMode: 'name' },
searchFilter: { operator: 'AND', conditions: [], recursively: true, isSemantic: false },
},
})
}
@@ -130,7 +130,7 @@ describe('CollectionService', () => {
name: 'To be deleted',
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: { operator: 'AND', conditions: [], recursively: true, searchMode: 'name' },
searchFilter: { operator: 'AND', conditions: [], recursively: true, isSemantic: false },
},
})
+5 -5
View File
@@ -60,7 +60,7 @@ describe('N-gram Search Integration', () => {
const result = await searchService.search(root.id, {
operator: 'AND',
recursively: true,
searchMode: 'name',
isSemantic: false,
conditions: [
{
field: 'name',
@@ -88,7 +88,7 @@ describe('N-gram Search Integration', () => {
const result = await searchService.search(root.id, {
operator: 'AND',
recursively: true,
searchMode: 'name',
isSemantic: false,
conditions: [
{
field: 'name',
@@ -158,7 +158,7 @@ describe('N-gram Search Integration', () => {
const result = await searchService.search(rootId, {
operator: 'AND',
recursively: true,
searchMode: 'name',
isSemantic: false,
conditions: [
{
field: 'name',
@@ -191,7 +191,7 @@ describe('N-gram Search Integration', () => {
await searchService.search(rootId, {
operator: 'AND',
recursively: true,
searchMode: 'name',
isSemantic: false,
conditions: [{ field: 'name', operator: 'contains', value: 'rareterm' }],
})
@@ -213,7 +213,7 @@ describe('N-gram Search Integration', () => {
await searchService.search(rootId, {
operator: 'AND',
recursively: true,
searchMode: 'name',
isSemantic: false,
conditions: [{ field: 'name', operator: 'contains', value: 'commonterm' }],
})
+207 -12
View File
@@ -1,9 +1,10 @@
import { describe, expect, it, beforeEach } from 'vitest'
import { describe, expect, it, beforeEach, vi } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { SearchService } from './search'
import { SearchConditionOperator } from '@/dtos/search'
import { metadataService } from '@/services/metadata/metadata'
import { workflowService } from '@/workflow/workflow'
import { AssetType } from '@/generated/prisma/client.ts'
@@ -376,7 +377,7 @@ describe('SearchService', () => {
recursively: true,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
isSemantic: false,
})
const names = result.data.map((a) => a.name).sort()
expect(names).toEqual(expected.sort())
@@ -391,7 +392,7 @@ describe('SearchService', () => {
recursively: true,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
isSemantic: false,
})
expect(result.data).toHaveLength(1)
@@ -406,7 +407,7 @@ describe('SearchService', () => {
recursively: true,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
isSemantic: false,
})
expect(result.data).toHaveLength(2)
@@ -423,7 +424,7 @@ describe('SearchService', () => {
recursively: true,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
isSemantic: false,
})
expect(result.data).toHaveLength(1)
@@ -438,7 +439,7 @@ describe('SearchService', () => {
recursively: false,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
isSemantic: false,
})
// Should only find file1, as file2 is in subfolder
@@ -459,7 +460,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
isSemantic: false,
})
expect(resultAsc.data[0].name).toBe('file1')
expect(resultAsc.data[1].name).toBe('file2')
@@ -470,7 +471,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
isSemantic: false,
})
expect(resultDesc.data[0].name).toBe('file2')
expect(resultDesc.data[1].name).toBe('file1')
@@ -486,7 +487,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
isSemantic: false,
})
expect(resultAsc.data[0].sizeByte).toBe(100)
expect(resultAsc.data[1].sizeByte).toBe(200)
@@ -497,7 +498,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
isSemantic: false,
})
expect(resultDesc.data[0].sizeByte).toBe(200)
expect(resultDesc.data[1].sizeByte).toBe(100)
@@ -524,7 +525,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
isSemantic: false,
})
expect(resultNormal.data.find((a) => a.id === symlink.id)).toBeUndefined()
@@ -535,8 +536,202 @@ describe('SearchService', () => {
operator: 'AND',
conditions: [],
showSymlink: true,
searchMode: 'name',
isSemantic: false,
})
expect(resultWithSymlink.data.find((a) => a.id === symlink.id)).toBeDefined()
})
describe('Semantic Search with multiple chunks and distance ordering', () => {
it('returns multiple matching segments from the same asset and orders by distance', async () => {
const user = await prisma.user.create({
data: { name: 'semantic-user', email: 'semantic-user@example.com', type: 'human' },
})
const team = await prisma.team.create({
data: { name: 'semantic-team' },
})
const project = await prisma.project.create({
data: { name: 'semantic-project', teamId: team.id },
})
// We need an embedding agent that is enabled for semantic search to be allowed
const botUser = await prisma.user.create({
data: { name: 'Embedding Bot', email: 'emb@example.com', type: 'agent' },
})
const provider = await prisma.provider.create({
data: {
name: 'google',
teamId: team.id,
config: { api: 'google', apiKey: 'key' } as unknown as PrismaJson.ProviderConfig,
},
})
const model = await prisma.model.create({
data: {
modelId: 'gemini',
name: 'Gemini',
providerId: provider.id,
config: {
reasoning: false,
input: ['text'],
contextWindow: 1000,
maxTokens: 1000,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
} as unknown as PrismaJson.ModelConfig,
},
})
await prisma.agent.create({
data: {
id: botUser.id,
teamId: team.id,
type: 'embedding',
enabled: true,
providerId: provider.id,
modelId: model.id,
config: { provider: 'google', model: 'gemini' },
},
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
const videoAssetA = await prisma.asset.create({
data: {
name: 'videoA.mp4',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
creatorId: user.id,
status: 'uploaded',
},
})
const videoAssetB = await prisma.asset.create({
data: {
name: 'videoB.mp4',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
creatorId: user.id,
status: 'uploaded',
},
})
// Insert embedding chunks:
// We will insert 2 chunks for videoAssetA and 1 chunk for videoAssetB.
// Vector size is 1536. We use unit vectors to ensure distinct cosine distances:
// Chunk A1: startTime = 0.0, endTime = 10.0, embedding = [1, 0, 0...] (cosine similarity = 1.0, distance = 0.0)
// Chunk B1: startTime = 5.0, endTime = 15.0, embedding = [1, 1, 0...] (cosine similarity = 0.707, distance = 0.293)
// Chunk A2: startTime = 10.0, endTime = 20.0, embedding = [0, 1, 0...] (cosine similarity = 0.0, distance = 1.0)
const arrA1 = Array(1536).fill(0)
arrA1[0] = 1.0
const vectorA1 = JSON.stringify(arrA1)
const arrB1 = Array(1536).fill(0)
arrB1[0] = 1.0
arrB1[1] = 1.0
const vectorB1 = JSON.stringify(arrB1)
const arrA2 = Array(1536).fill(0)
arrA2[1] = 1.0
const vectorA2 = JSON.stringify(arrA2)
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, created_at, updated_at)
VALUES (
'chunk-a1',
${videoAssetA.id},
${vectorA1}::vector,
0.0,
10.0,
NOW(),
NOW()
)
`
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, created_at, updated_at)
VALUES (
'chunk-a2',
${videoAssetA.id},
${vectorA2}::vector,
10.0,
20.0,
NOW(),
NOW()
)
`
await prisma.$executeRaw`
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, created_at, updated_at)
VALUES (
'chunk-b1',
${videoAssetB.id},
${vectorB1}::vector,
5.0,
15.0,
NOW(),
NOW()
)
`
// Mock the embedding generation workflow task.
// Our query vector points along the first dimension [1, 0, 0...]
const queryVector = Array(1536).fill(0)
queryVector[0] = 1.0
const mockExecuteWait = vi
.spyOn(workflowService, 'executeWait')
.mockImplementation(async (task) => {
return {
...task,
status: 'completed',
output: {
embedding: queryVector,
},
} as unknown as typeof task
})
// Search using semantic mode
const result = await searchService.search(rootFolder.id, {
recursively: true,
assetType: 'file',
operator: 'AND',
conditions: [],
query: 'find some cute cat video segments',
isSemantic: true,
})
// We expect 3 distinct results because videoAssetA matches twice and videoAssetB matches once:
// Sorting should be based on vector distance:
// Distance from query (0.2) to:
// - Chunk A1 (0.1): |0.2 - 0.1| = 0.1 -> closest (1st)
// - Chunk B1 (0.5): |0.2 - 0.5| = 0.3 -> medium (2nd)
// - Chunk A2 (0.9): |0.2 - 0.9| = 0.7 -> farthest (3rd)
expect(result.data).toHaveLength(3)
// 1st: Chunk A1
expect(result.data[0].id).toBe(videoAssetA.id)
expect(result.data[0].startTime).toBe(0)
expect(result.data[0].endTime).toBe(10)
// 2nd: Chunk B1
expect(result.data[1].id).toBe(videoAssetB.id)
expect(result.data[1].startTime).toBe(5)
expect(result.data[1].endTime).toBe(15)
// 3rd: Chunk A2
expect(result.data[2].id).toBe(videoAssetA.id)
expect(result.data[2].startTime).toBe(10)
expect(result.data[2].endTime).toBe(20)
mockExecuteWait.mockRestore()
})
})
})
+276 -27
View File
@@ -3,10 +3,17 @@ import { Prisma, AssetType, WorkflowTaskType } from '@/generated/prisma/client.t
import { AssetService, assetService } from '@/services/asset/asset'
import { AssetInfo } from '@/dtos/asset'
import { SearchRequest } from '@/dtos/search'
import { paginateQuery, PaginatedData } from '@/services/pagination'
import {
paginateQuery,
PaginatedData,
decodeCursor,
encodeCursor,
PageInfo,
} from '@/services/pagination'
import { generateSearchNgrams } from '@/utils/ngram'
import { workflowService } from '@/workflow/workflow'
import { HTTPException } from 'hono/http-exception'
import { SqlQueryBuilder } from './sql-query-builder'
export class SearchService {
constructor(
@@ -62,8 +69,7 @@ export class SearchService {
// ----------------------------------------------------------------------
// AI Semantic search
// ----------------------------------------------------------------------
let semanticIds: string[] = []
if (req.query && (req.searchMode === 'content' || req.searchMode === 'all')) {
if (req.query && req.isSemantic) {
// 1. Check if embedding agent exists and is enabled
const team = await this.prismaClient.asset.findUnique({
where: { id: folderId },
@@ -87,9 +93,9 @@ export class SearchService {
data: {
type: WorkflowTaskType.query_embedding_for_search,
teamId,
assetId: folderId, // Just using folderId as a placeholder
assetId: folderId,
payload: {
projectId: '', // Not used for this task type
projectId: '',
queryEmbeddingForSearch: { text: req.query },
} as PrismaJson.WorkflowTaskPayload,
status: 'pending',
@@ -104,31 +110,159 @@ export class SearchService {
throw new Error('Failed to generate query embedding')
}
// 3. Fetch top 1000 unique asset IDs from asset_embeddings via pgvector
// 3. Construct raw SQL using SqlQueryBuilder
const vectorJson = JSON.stringify(queryVector)
const semanticMatches = await this.prismaClient.$queryRaw<{ assetId: string }[]>`
SELECT DISTINCT ON (asset_id) asset_id as "assetId" FROM (
SELECT asset_id, embedding <=> ${vectorJson}::vector as dist
FROM asset_embeddings
ORDER BY embedding <=> ${vectorJson}::vector
LIMIT 2000
) as sub
ORDER BY asset_id, dist
LIMIT 1000
`
semanticIds = semanticMatches.map((m) => m.assetId)
const builder = new SqlQueryBuilder()
.select(
Prisma.sql`a.id as "assetId", ae.start_time as "startTime", ae.end_time as "endTime", (ae.embedding <=> ${vectorJson}::vector) as "distance"`,
)
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (req.searchMode === 'content') {
where.id = { in: semanticIds }
} else if (req.searchMode === 'all') {
const keywordCondition: Prisma.AssetWhereInput = {
name: { contains: req.query, mode: 'insensitive' },
}
const semanticCondition: Prisma.AssetWhereInput = {
id: { in: semanticIds },
}
where.OR = [keywordCondition, semanticCondition]
if (targetFolderIds.length > 0) {
builder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
builder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
builder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
const condSqls: Prisma.Sql[] = []
for (const cond of req.conditions) {
if (cond.field === 'name' && cond.operator === 'contains') continue
const sqlCond = this.buildSqlCondition(cond.field, cond.operator, cond.value)
if (sqlCond) {
condSqls.push(sqlCond)
}
}
if (condSqls.length > 0) {
const separator = req.operator === 'OR' ? ' OR ' : ' AND '
builder.addWhere(Prisma.sql`(${Prisma.join(condSqls, separator)})`)
}
}
const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains')
if (nameCond) {
const valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
builder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else {
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
}
builder.orderBy(Prisma.sql`distance ASC`)
// 4. Paginate in SQL using limit/offset
let limit = req.first || 20
if (limit <= 0 || limit > 200) {
limit = 20
}
let offset = 0
if (req.after) {
offset = decodeCursor(req.after)
}
builder.limit(limit + 1).offset(offset)
// 5. Execute raw SQL query
const query = builder.build()
const semanticMatches = await this.prismaClient.$queryRaw<
{
assetId: string
startTime: number | null
endTime: number | null
distance: number
}[]
>(query)
const hasNextPage = semanticMatches.length > limit
const finalMatches = hasNextPage ? semanticMatches.slice(0, limit) : semanticMatches
// 6. Map back to full rich metadata and return time-based duplicate segments
const uniqueIds = Array.from(new Set(finalMatches.map((m) => m.assetId)))
const fetchedInfos = await this.assetSvc.listAssetsByIds(uniqueIds)
const assetInfosMap = new Map<string, AssetInfo>()
for (const info of fetchedInfos) {
assetInfosMap.set(info.id, info)
}
const data: AssetInfo[] = []
for (const match of finalMatches) {
const baseInfo = assetInfosMap.get(match.assetId)
if (baseInfo) {
data.push({
...baseInfo,
startTime: match.startTime,
endTime: match.endTime,
})
}
}
const pageInfo: PageInfo = {}
if (req.includeCount) {
const countBuilder = new SqlQueryBuilder()
.select(Prisma.sql`COUNT(*)`)
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
if (targetFolderIds.length > 0) {
countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
}
if (req.showSymlink) {
countBuilder.addWhere(Prisma.sql`
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
`)
} else {
countBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
}
if (req.conditions && req.conditions.length > 0) {
const condSqls: Prisma.Sql[] = []
for (const cond of req.conditions) {
if (cond.field === 'name' && cond.operator === 'contains') continue
const sqlCond = this.buildSqlCondition(cond.field, cond.operator, cond.value)
if (sqlCond) {
condSqls.push(sqlCond)
}
}
if (condSqls.length > 0) {
const separator = req.operator === 'OR' ? ' OR ' : ' AND '
countBuilder.addWhere(Prisma.sql`(${Prisma.join(condSqls, separator)})`)
}
}
if (nameCond) {
const valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
countBuilder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
} else {
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
}
}
const countRes = await this.prismaClient.$queryRaw<{ count: bigint }[]>(
countBuilder.build(),
)
pageInfo.total = Number(countRes[0]?.count || 0)
}
if (hasNextPage) {
pageInfo.cursor = encodeCursor(offset + limit)
}
return { data, pageInfo }
}
const orderBy: Prisma.AssetOrderByWithRelationInput = {}
@@ -640,6 +774,121 @@ export class SearchService {
const parsed = new Date(value as string)
return isNaN(parsed.getTime()) ? null : parsed
}
private buildSqlCondition(
field: string,
operator: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any,
): Prisma.Sql | null {
const colName =
field === 'sizeByte' || field === 'size_byte'
? 'size_byte'
: field === 'createdAt' || field === 'created_at'
? 'created_at'
: field === 'updatedAt' || field === 'updated_at'
? 'updated_at'
: field
const dbCol = Prisma.raw(`a."${colName}"`)
if (field === 'name') {
const valStr = String(value)
switch (operator) {
case 'eq':
return Prisma.sql`${dbCol} = ${valStr}`
case 'neq':
return Prisma.sql`${dbCol} != ${valStr}`
case 'contains':
return Prisma.sql`${dbCol} ILIKE ${'%' + valStr + '%'}`
case 'notContains':
return Prisma.sql`${dbCol} NOT ILIKE ${'%' + valStr + '%'}`
case 'isEmpty':
return Prisma.sql`${dbCol} = ''`
case 'isNotEmpty':
return Prisma.sql`${dbCol} != ''`
default:
throw new Error(`Unsupported operator for name field: ${operator}`)
}
}
if (field === 'sizeByte' || field === 'size_byte') {
const valNum = Number(value)
switch (operator) {
case 'eq':
return Prisma.sql`${dbCol} = ${valNum}`
case 'neq':
return Prisma.sql`${dbCol} != ${valNum}`
case 'gt':
return Prisma.sql`${dbCol} > ${valNum}`
case 'gte':
return Prisma.sql`${dbCol} >= ${valNum}`
case 'lt':
return Prisma.sql`${dbCol} < ${valNum}`
case 'lte':
return Prisma.sql`${dbCol} <= ${valNum}`
default:
throw new Error(`Unsupported operator for sizeByte field: ${operator}`)
}
}
if (
field === 'createdAt' ||
field === 'updatedAt' ||
field === 'created_at' ||
field === 'updated_at'
) {
const valDate = this.toDate(value)
switch (operator) {
case 'eq':
return Prisma.sql`${dbCol} = ${valDate}`
case 'neq':
return Prisma.sql`${dbCol} != ${valDate}`
case 'gt':
return Prisma.sql`${dbCol} > ${this.toDateBound(value, 'end')}`
case 'gte':
return Prisma.sql`${dbCol} >= ${this.toDateBound(value, 'start')}`
case 'lt':
return Prisma.sql`${dbCol} < ${this.toDateBound(value, 'start')}`
case 'lte':
return Prisma.sql`${dbCol} <= ${this.toDateBound(value, 'end')}`
case 'isWithin': {
const range = this.parseDateRange(value)
return Prisma.sql`${dbCol} >= ${range.start} AND ${dbCol} <= ${range.end}`
}
default:
throw new Error(`Unsupported operator for date field: ${operator}`)
}
}
// Custom EAV metadata field query on asset_metadata_values
if (operator === 'isEmpty') {
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field})`
}
if (operator === 'isNotEmpty') {
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field})`
}
// Standard EAV value matching based on type of value
if (typeof value === 'string') {
const valStr = String(value)
if (this.isDate(valStr)) {
const valDate = this.toDate(valStr)
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND date_value = ${valDate})`
}
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND string_value = ${valStr})`
}
if (typeof value === 'number') {
const valNum = Number(value)
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND number_value = ${valNum})`
}
if (typeof value === 'boolean') {
const valBool = Boolean(value)
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND boolean_value = ${valBool})`
}
return null
}
}
export const searchService = new SearchService()
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { SqlQueryBuilder } from './sql-query-builder'
import { Prisma } from '@/generated/prisma/client.ts'
describe('SqlQueryBuilder', () => {
it('correctly constructs a basic SQL query', () => {
const builder = new SqlQueryBuilder()
.select(Prisma.sql`a.id, a.name`)
.from(Prisma.sql`assets a`)
.addWhere(Prisma.sql`a.is_deleted = false`)
const query = builder.build()
expect(query.text).toContain('SELECT a.id, a.name FROM assets a WHERE a.is_deleted = false')
})
it('correctly constructs query with where clauses, order, limit, and offset', () => {
const vectorJson = '[0.1, 0.2, 0.3]'
const builder = new SqlQueryBuilder()
.select(Prisma.sql`a.id, ae.start_time as "startTime"`)
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
.addWhere(Prisma.sql`a.is_deleted = false`)
.addWhere(Prisma.sql`a.project_id = ${'project-123'}`)
.orderBy(Prisma.sql`ae.embedding <=> ${vectorJson}::vector ASC`)
.limit(10)
.offset(20)
const query = builder.build()
expect(query.text).toContain(
'SELECT a.id, ae.start_time as "startTime" FROM assets a JOIN asset_embeddings ae ON a.id = ae.asset_id WHERE a.is_deleted = false AND a.project_id = $1 ORDER BY ae.embedding <=> $2::vector ASC LIMIT $3 OFFSET $4',
)
expect(query.values).toEqual(['project-123', vectorJson, 10, 20])
})
it('throws an error if FROM clause is missing', () => {
const builder = new SqlQueryBuilder().select(Prisma.sql`id`)
expect(() => builder.build()).toThrow('FROM clause is required')
})
})
+73
View File
@@ -0,0 +1,73 @@
import { Prisma } from '@/generated/prisma/client.ts'
export class SqlQueryBuilder {
private selectSql: Prisma.Sql = Prisma.sql`*`
private fromSql: Prisma.Sql | null = null
private wheres: Prisma.Sql[] = []
private orderSql: Prisma.Sql | null = null
private limitCount: number | null = null
private offsetCount: number | null = null
select(fields: Prisma.Sql): this {
this.selectSql = fields
return this
}
from(relation: Prisma.Sql): this {
this.fromSql = relation
return this
}
addWhere(condition: Prisma.Sql): this {
this.wheres.push(condition)
return this
}
orderBy(order: Prisma.Sql): this {
this.orderSql = order
return this
}
limit(n: number): this {
this.limitCount = n
return this
}
offset(n: number): this {
this.offsetCount = n
return this
}
build(): Prisma.Sql {
if (!this.fromSql) {
throw new Error('FROM clause is required in SqlQueryBuilder')
}
const queryParts: Prisma.Sql[] = [
Prisma.sql`SELECT`,
this.selectSql,
Prisma.sql`FROM`,
this.fromSql,
]
if (this.wheres.length > 0) {
queryParts.push(Prisma.sql`WHERE`)
queryParts.push(Prisma.join(this.wheres, ' AND '))
}
if (this.orderSql) {
queryParts.push(Prisma.sql`ORDER BY`)
queryParts.push(this.orderSql)
}
if (this.limitCount !== null) {
queryParts.push(Prisma.sql`LIMIT ${this.limitCount}`)
}
if (this.offsetCount !== null) {
queryParts.push(Prisma.sql`OFFSET ${this.offsetCount}`)
}
return Prisma.join(queryParts, ' ')
}
}
@@ -5,6 +5,8 @@ import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button'
import { Dialog, DialogContent } from '@/ui/components/ui/dialog'
import { Input } from '@/ui/components/ui/input'
import { Switch } from '@/ui/components/ui/switch'
import { Label } from '@/ui/components/ui/label'
import { formatSize } from '@/ui/lib/format'
import { cn } from '@/ui/lib/utils'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
@@ -60,7 +62,8 @@ export function SearchFilterDialog({
const [isFiltersExpanded, setIsFiltersExpanded] = useState(true)
const [searchInput, setSearchInput] = useState(initialKeyword)
const [debouncedSearchInput, setDebouncedSearchInput] = useState(initialKeyword)
const [searchMode, setSearchMode] = useState<'name' | 'content' | 'all'>('name')
const [isSemantic, setIsSemantic] = useState<boolean>(false)
const [semanticSearchTriggerQuery, setSemanticSearchTriggerQuery] = useState('')
const { data: teamSettings } = useQuery({
queryKey: ['team-settings', teamId],
@@ -76,13 +79,20 @@ export function SearchFilterDialog({
const semanticSearchEnabled = teamSettings?.semanticSearchEnabled ?? false
// Sync back if changed from outside
// Sync back if changed from outside, clear on close
useEffect(() => {
if (open) {
setSearchInput(initialKeyword)
setDebouncedSearchInput(initialKeyword)
setConditions(initialOtherConditions)
setSearchMode('name')
setIsSemantic(false)
setSemanticSearchTriggerQuery('')
} else {
setSearchInput('')
setDebouncedSearchInput('')
setConditions([])
setIsSemantic(false)
setSemanticSearchTriggerQuery('')
}
}, [open, initialKeyword, initialOtherConditions])
@@ -96,26 +106,26 @@ export function SearchFilterDialog({
const combinedConditions = useMemo(() => {
const result: SearchCondition[] = [...conditions]
if (debouncedSearchInput.trim() && searchMode === 'name') {
const activeText = isSemantic ? semanticSearchTriggerQuery : debouncedSearchInput
if (activeText.trim() && !isSemantic) {
result.push({
field: 'name',
operator: 'contains',
value: debouncedSearchInput.trim(),
value: activeText.trim(),
})
}
return result
}, [debouncedSearchInput, conditions, searchMode])
}, [isSemantic, debouncedSearchInput, semanticSearchTriggerQuery, conditions])
const hasActiveCriteria = useMemo(() => {
return (
debouncedSearchInput.trim() !== '' ||
conditions.some((c) => String(c.value || '').trim() !== '')
)
}, [debouncedSearchInput, conditions])
const activeText = isSemantic ? semanticSearchTriggerQuery : debouncedSearchInput
return activeText.trim() !== '' || conditions.some((c) => String(c.value || '').trim() !== '')
}, [isSemantic, debouncedSearchInput, semanticSearchTriggerQuery, conditions])
const { mutate: saveAsCollection, isPending: isSaving } = useMutation({
mutationFn: async () => {
let name = debouncedSearchInput.trim()
const activeText = isSemantic ? semanticSearchTriggerQuery : debouncedSearchInput
let name = activeText.trim()
if (!name && conditions.length > 0) {
const first = conditions[0]
const field = fields.find((f) => f.id === first.field)
@@ -133,8 +143,8 @@ export function SearchFilterDialog({
searchFilter: {
conditions: combinedConditions,
recursively: true,
query: debouncedSearchInput.trim(),
searchMode: searchMode,
query: activeText.trim(),
isSemantic: isSemantic,
},
},
},
@@ -166,18 +176,19 @@ export function SearchFilterDialog({
teamId,
assetId,
combinedConditions,
searchMode,
debouncedSearchInput,
isSemantic,
isSemantic ? semanticSearchTriggerQuery : debouncedSearchInput,
],
queryFn: async () => {
const activeText = isSemantic ? semanticSearchTriggerQuery : debouncedSearchInput
const res = await client.api.folders[':folderId'].search.$post({
param: { folderId: assetId },
json: {
assetType: undefined,
conditions: combinedConditions,
recursively: true,
query: debouncedSearchInput.trim(),
searchMode: searchMode,
query: activeText.trim(),
isSemantic: isSemantic,
first: 20,
},
})
@@ -200,7 +211,14 @@ export function SearchFilterDialog({
const handleClearFilters = () => {
setConditions([])
setSearchInput('')
setSearchMode('name')
setSemanticSearchTriggerQuery('')
setIsSemantic(false)
}
const formatTimestamp = (seconds: number) => {
const m = Math.floor(seconds / 60)
const s = Math.floor(seconds % 60)
return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
}
const handleResultClick = (item: AssetInfo) => {
@@ -228,7 +246,11 @@ export function SearchFilterDialog({
<form
onSubmit={(e) => {
e.preventDefault()
handleApply()
if (isSemantic) {
setSemanticSearchTriggerQuery(searchInput.trim())
} else {
handleApply()
}
}}
className="flex flex-col gap-3 mt-2"
>
@@ -237,14 +259,21 @@ export function SearchFilterDialog({
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
placeholder={
searchMode === 'name' ? 'Search records by name...' : 'Search by content...'
isSemantic
? "Describe what you're looking for and click Search..."
: 'Search records by name...'
}
className="w-full pl-4 pr-24 py-3 bg-background border-border rounded-xl text-sm h-12 focus-visible:ring-2 focus-visible:ring-primary/20 shadow-sm"
/>
{searchInput && (
<button
type="button"
onClick={() => setSearchInput('')}
onClick={() => {
setSearchInput('')
if (isSemantic) {
setSemanticSearchTriggerQuery('')
}
}}
className="absolute right-20 top-1/2 -translate-y-1/2 p-1 rounded-md text-muted-foreground hover:text-foreground transition-colors"
>
<X className="w-4 h-4" />
@@ -258,50 +287,23 @@ export function SearchFilterDialog({
</button>
</div>
<div className="flex items-center gap-2">
<div className="flex bg-background border border-border p-1 rounded-lg">
<button
type="button"
onClick={() => setSearchMode('name')}
className={cn(
'px-3 py-1.5 text-xs font-medium rounded-md transition-colors',
searchMode === 'name'
? 'bg-primary text-primary-foreground shadow-sm'
: 'hover:bg-accent text-muted-foreground',
)}
>
Name
</button>
<button
type="button"
onClick={() => setSearchMode('content')}
<div className="flex items-center gap-3 py-1">
<div className="flex items-center gap-2 bg-background border border-border px-3 py-1.5 rounded-lg shadow-sm">
<Switch
id="semantic-search-switch"
checked={isSemantic}
onCheckedChange={setIsSemantic}
disabled={!semanticSearchEnabled}
/>
<Label
htmlFor="semantic-search-switch"
className={cn(
'px-3 py-1.5 text-xs font-medium rounded-md transition-colors',
searchMode === 'content'
? 'bg-primary text-primary-foreground shadow-sm'
: 'hover:bg-accent text-muted-foreground',
'text-xs font-semibold select-none cursor-pointer',
!semanticSearchEnabled && 'opacity-50 cursor-not-allowed',
)}
title={!semanticSearchEnabled ? 'Embedding agent is not enabled' : ''}
>
Content
</button>
<button
type="button"
onClick={() => setSearchMode('all')}
disabled={!semanticSearchEnabled}
className={cn(
'px-3 py-1.5 text-xs font-medium rounded-md transition-colors',
searchMode === 'all'
? 'bg-primary text-primary-foreground shadow-sm'
: 'hover:bg-accent text-muted-foreground',
!semanticSearchEnabled && 'opacity-50 cursor-not-allowed',
)}
title={!semanticSearchEnabled ? 'Embedding agent is not enabled' : ''}
>
All
</button>
Semantic Search
</Label>
</div>
{!semanticSearchEnabled && (
<span className="text-[10px] text-muted-foreground italic">
@@ -367,7 +369,7 @@ export function SearchFilterDialog({
{isLoading && (
<span className="inline-flex items-center gap-1.5 text-xs text-primary">
<Loader2 className="h-3 w-3 animate-spin" />
{searchMode !== 'name'
{isSemantic
? 'Semantic search using media intelligence might be slow...'
: 'Querying database...'}
</span>
@@ -450,6 +452,15 @@ export function SearchFilterDialog({
? 'Folder'
: `Size: ${formatSize(record.sizeByte || 0)}`}
</span>
{record.startTime !== undefined &&
record.startTime !== null &&
record.endTime !== undefined &&
record.endTime !== null && (
<span className="text-[10px] font-semibold text-primary bg-primary/10 border border-primary/20 px-1.5 py-0.5 rounded mt-1 inline-block">
Match found at {formatTimestamp(record.startTime)} -{' '}
{formatTimestamp(record.endTime)}
</span>
)}
</div>
<span className="text-xs text-muted-foreground font-mono shrink-0">
{new Date(record.createdAt).toLocaleDateString(undefined, {
@@ -481,7 +492,7 @@ export function SearchFilterDialog({
<Button
variant="outline"
size="xs"
className="h-8 text-[10px] font-semibold uppercase tracking-wider"
className="h-8 text-[10px] font-semibold uppercase tracking-wider mr-1"
disabled={!hasActiveCriteria || isSaving}
onClick={() => saveAsCollection()}
>
@@ -494,6 +505,14 @@ export function SearchFilterDialog({
'Save as collection'
)}
</Button>
<Button
size="xs"
className="h-8 text-[10px] font-semibold uppercase tracking-wider"
onClick={handleApply}
>
{isSemantic ? 'Apply' : 'Apply and Close'}
</Button>
</div>
</div>
</DialogContent>