feat(search): add semantic search with embeddings and search mode toggle

This commit is contained in:
yiling
2026-05-28 20:14:11 +08:00
parent a39f793050
commit 2eb6ff6c0e
18 changed files with 384 additions and 44 deletions
+2 -2
View File
@@ -59,7 +59,7 @@ describe('AuthzService', () => {
projectId: project.id,
filter: {
sourceFolderId: 'root',
searchFilter: { conditions: [], operator: 'AND', recursively: true },
searchFilter: { conditions: [], operator: 'AND', recursively: true, searchMode: 'name' },
},
},
})
@@ -263,7 +263,7 @@ describe('AuthzService', () => {
projectId: project.id,
filter: {
sourceFolderId: 'root',
searchFilter: { conditions: [], operator: 'AND', recursively: true },
searchFilter: { conditions: [], operator: 'AND', recursively: true, searchMode: 'name' },
},
},
})
+4 -2
View File
@@ -48,6 +48,7 @@ describe('CollectionService', () => {
operator: 'AND',
conditions: [{ field: 'name', operator: 'contains', value: 'test' }],
recursively: true,
searchMode: 'name',
},
},
})
@@ -68,6 +69,7 @@ describe('CollectionService', () => {
operator: 'AND',
conditions: [{ field: 'rating', operator: 'eq', value: 5 }],
recursively: true,
searchMode: 'name',
},
},
})
@@ -90,7 +92,7 @@ describe('CollectionService', () => {
name: `Collection ${i}`,
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: { operator: 'AND', conditions: [], recursively: true },
searchFilter: { operator: 'AND', conditions: [], recursively: true, searchMode: 'name' },
},
})
}
@@ -128,7 +130,7 @@ describe('CollectionService', () => {
name: 'To be deleted',
filter: {
sourceFolderId: project.rootFolder!,
searchFilter: { operator: 'AND', conditions: [], recursively: true },
searchFilter: { operator: 'AND', conditions: [], recursively: true, searchMode: 'name' },
},
})
+5
View File
@@ -60,6 +60,7 @@ describe('N-gram Search Integration', () => {
const result = await searchService.search(root.id, {
operator: 'AND',
recursively: true,
searchMode: 'name',
conditions: [
{
field: 'name',
@@ -87,6 +88,7 @@ describe('N-gram Search Integration', () => {
const result = await searchService.search(root.id, {
operator: 'AND',
recursively: true,
searchMode: 'name',
conditions: [
{
field: 'name',
@@ -156,6 +158,7 @@ describe('N-gram Search Integration', () => {
const result = await searchService.search(rootId, {
operator: 'AND',
recursively: true,
searchMode: 'name',
conditions: [
{
field: 'name',
@@ -188,6 +191,7 @@ describe('N-gram Search Integration', () => {
await searchService.search(rootId, {
operator: 'AND',
recursively: true,
searchMode: 'name',
conditions: [{ field: 'name', operator: 'contains', value: 'rareterm' }],
})
@@ -209,6 +213,7 @@ describe('N-gram Search Integration', () => {
await searchService.search(rootId, {
operator: 'AND',
recursively: true,
searchMode: 'name',
conditions: [{ field: 'name', operator: 'contains', value: 'commonterm' }],
})
+11
View File
@@ -376,6 +376,7 @@ describe('SearchService', () => {
recursively: true,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
})
const names = result.data.map((a) => a.name).sort()
expect(names).toEqual(expected.sort())
@@ -390,6 +391,7 @@ describe('SearchService', () => {
recursively: true,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
})
expect(result.data).toHaveLength(1)
@@ -404,6 +406,7 @@ describe('SearchService', () => {
recursively: true,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
})
expect(result.data).toHaveLength(2)
@@ -420,6 +423,7 @@ describe('SearchService', () => {
recursively: true,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
})
expect(result.data).toHaveLength(1)
@@ -434,6 +438,7 @@ describe('SearchService', () => {
recursively: false,
assetType: 'file',
operator: 'AND',
searchMode: 'name',
})
// Should only find file1, as file2 is in subfolder
@@ -454,6 +459,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
})
expect(resultAsc.data[0].name).toBe('file1')
expect(resultAsc.data[1].name).toBe('file2')
@@ -464,6 +470,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
})
expect(resultDesc.data[0].name).toBe('file2')
expect(resultDesc.data[1].name).toBe('file1')
@@ -479,6 +486,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
})
expect(resultAsc.data[0].sizeByte).toBe(100)
expect(resultAsc.data[1].sizeByte).toBe(200)
@@ -489,6 +497,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
})
expect(resultDesc.data[0].sizeByte).toBe(200)
expect(resultDesc.data[1].sizeByte).toBe(100)
@@ -515,6 +524,7 @@ describe('SearchService', () => {
assetType: 'file',
operator: 'AND',
conditions: [],
searchMode: 'name',
})
expect(resultNormal.data.find((a) => a.id === symlink.id)).toBeUndefined()
@@ -525,6 +535,7 @@ describe('SearchService', () => {
operator: 'AND',
conditions: [],
showSymlink: true,
searchMode: 'name',
})
expect(resultWithSymlink.data.find((a) => a.id === symlink.id)).toBeDefined()
})
+72 -3
View File
@@ -1,10 +1,12 @@
import { prisma } from '@/db'
import { Prisma, AssetType } from '@/generated/prisma/client.ts'
import { Prisma, AssetType, WorkflowTaskType } from '@/generated/prisma/client.ts'
import { AssetService, assetService } from '@/services/asset/asset'
import { AssetInfo } from '@/dtos/asset'
import { SearchRequest } from '@/dtos/search'
import { paginateQuery, PaginatedData } from '@/services/pagination'
import { generateSearchNgrams } from '@/utils/ngram'
import { workflowService } from '@/workflow/workflow'
import { HTTPException } from 'hono/http-exception'
export class SearchService {
constructor(
@@ -57,8 +59,75 @@ export class SearchService {
Object.assign(where, typeCondition)
}
// AI Semantic search is skipped for now, but in the future we'll check if req.query exists
// and if the team has embeddings enabled to do a vector search
// ----------------------------------------------------------------------
// AI Semantic search
// ----------------------------------------------------------------------
let semanticIds: string[] = []
if (req.query && (req.searchMode === 'content' || req.searchMode === 'all')) {
// 1. Check if embedding agent exists and is enabled
const team = await this.prismaClient.asset.findUnique({
where: { id: folderId },
select: { project: { select: { teamId: true } } },
})
const teamId = team?.project?.teamId
if (!teamId) throw new Error('Team ID not found for folder')
const embeddingAgent = await this.prismaClient.agent.findFirst({
where: { teamId, type: 'embedding', enabled: true },
})
if (!embeddingAgent) {
throw new HTTPException(422, {
message: 'Embedding agent not configured or disabled for this team.',
})
}
// 2. Generate query embedding via workflow
const task = await this.prismaClient.workflowTask.create({
data: {
type: WorkflowTaskType.query_embedding_for_search,
teamId,
assetId: folderId, // Just using folderId as a placeholder
payload: {
projectId: '', // Not used for this task type
queryEmbeddingForSearch: { text: req.query },
} as PrismaJson.WorkflowTaskPayload,
status: 'pending',
},
})
const completedTask = await workflowService.executeWait(task)
const output = completedTask.output as Record<string, unknown> | null
const queryVector = output?.embedding as number[] | undefined
if (!queryVector) {
throw new Error('Failed to generate query embedding')
}
// 3. Fetch top 1000 unique asset IDs from asset_embeddings via pgvector
const semanticMatches = await this.prismaClient.$queryRaw<{ assetId: string }[]>`
SELECT asset_id as "assetId" FROM (
SELECT asset_id, MIN(embedding <=> ${JSON.stringify(queryVector)}::vector) as min_dist
FROM asset_embeddings
GROUP BY asset_id
) as sub
ORDER BY min_dist
LIMIT 1000
`
semanticIds = semanticMatches.map((m) => m.assetId)
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]
}
}
const orderBy: Prisma.AssetOrderByWithRelationInput = {}
if (req.sort) {
+9 -1
View File
@@ -185,7 +185,15 @@ export class TeamService {
where: { id: teamId },
})
if (!team) throw new Error('team not found')
return team.settings || {}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const settings = (team.settings || {}) as any
const embeddingAgent = await prisma.agent.findFirst({
where: { teamId, type: 'embedding', enabled: true },
})
settings.semanticSearchEnabled = !!embeddingAgent
return settings
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any