feat(db): add HNSW index on asset_embeddings and natural sort collation on assets.name

- Add HNSW index on asset_embeddings.embedding using vector_cosine_ops (m=16,
  ef_construction=64) with hnsw.iterative_scan=relaxed_order for efficient
  filtered ANN queries
- Create ICU numeric collation and alter assets.name column to use it for
  natural sort (file2 < file10 instead of lexicographic ordering)
- Add B-tree index on assets.name with numeric collation for sort performance
- Add schema @@index annotations to match migration index names
- Add 7 tests verifying natural sort behaviour in both AssetService.listChildren
  and SearchService.search (Prisma ORM and raw-SQL paths)
This commit is contained in:
yiling
2026-05-29 15:18:31 +08:00
parent 840cf87728
commit 048028007e
6 changed files with 234 additions and 0 deletions
@@ -0,0 +1,11 @@
-- Enable iterative index scans for HNSW so filtered queries don't fall back to seq scan
SET hnsw.iterative_scan = relaxed_order;
-- CreateIndex: HNSW index on asset_embeddings.embedding
-- Uses cosine distance ops (suited for normalized OpenAI-style embeddings)
-- m=16: controls graph connectivity (higher = better recall, more memory)
-- ef_construction=64: build-time search width (higher = better quality, slower build)
CREATE INDEX "AssetEmbedding_embedding_idx"
ON "asset_embeddings"
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
@@ -0,0 +1,16 @@
-- Create ICU numeric collation for natural sort (numbers sort by value, not lexicographically)
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_collation WHERE collname = 'numeric') THEN
CREATE COLLATION numeric (provider = icu, locale = 'en@colNumeric=yes');
END IF;
END;
$$;
-- Alter assets.name to use the numeric collation
-- This makes all ORDER BY name queries (ORM and raw SQL) use natural sort automatically
ALTER TABLE "assets" ALTER COLUMN "name" TYPE TEXT COLLATE numeric;
-- CreateIndex: B-tree index on name using the numeric collation
-- Supports efficient ORDER BY name ASC/DESC without seq scans
CREATE INDEX "assets_name_idx" ON "assets" ("name" COLLATE numeric);
+3
View File
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+2
View File
@@ -406,6 +406,7 @@ model Asset {
@@index([sortIndex])
@@index([isDeleted])
@@index([deletedAt])
@@index([name], name: "assets_name_idx")
@@index([nameNgram], type: Gin)
@@unique([parentId, targetId], name: "parentIdTargetId")
}
@@ -494,6 +495,7 @@ model AssetEmbedding {
assetId String @map("asset_id")
asset Asset @relation("AssetToEmbedding", fields: [assetId], references: [id], onDelete: Cascade)
@@index([embedding], name: "AssetEmbedding_embedding_idx")
@@map("asset_embeddings")
}
+105
View File
@@ -1482,3 +1482,108 @@ describe('AssetService', () => {
})
})
})
describe('AssetService — natural sort by name', () => {
setupTestDbHooks()
let assetService: AssetService
beforeEach(() => {
assetService = new AssetService()
})
const setupNaturalSortAssets = async (names: string[]) => {
const user = await prisma.user.create({
data: {
name: 'natural-sort-user',
email: `natural-sort-${Date.now()}@example.com`,
type: 'human',
},
})
const team = await prisma.team.create({ data: { name: 'natural-sort-team' } })
const project = await prisma.project.create({
data: { name: 'natural-sort-proj', teamId: team.id },
})
const root = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
// Create files in a shuffled order so we are not relying on insertion order
for (const name of names) {
await prisma.asset.create({
data: {
name,
type: AssetType.file,
projectId: project.id,
parentId: root.id,
creatorId: user.id,
status: 'uploaded',
sizeByte: 0,
},
})
}
return { root }
}
it('sorts files with numeric suffixes in natural order (asc)', async () => {
// Insert in non-natural lexicographic order to prove the collation does the work
const { root } = await setupNaturalSortAssets(['file10', 'file2', 'file20', 'file1'])
const result = await assetService.listChildren({
assetId: root.id,
assetType: AssetType.file,
sort: 'name',
order: 'asc',
first: 20,
})
expect(result.data.map((a) => a.name)).toEqual(['file1', 'file2', 'file10', 'file20'])
})
it('sorts files with numeric suffixes in natural order (desc)', async () => {
const { root } = await setupNaturalSortAssets(['file10', 'file2', 'file20', 'file1'])
const result = await assetService.listChildren({
assetId: root.id,
assetType: AssetType.file,
sort: 'name',
order: 'desc',
first: 20,
})
expect(result.data.map((a) => a.name)).toEqual(['file20', 'file10', 'file2', 'file1'])
})
it('sorts mixed alpha-numeric names correctly', async () => {
const { root } = await setupNaturalSortAssets(['asset 100', 'asset 9', 'asset 10', 'asset 2'])
const result = await assetService.listChildren({
assetId: root.id,
assetType: AssetType.file,
sort: 'name',
order: 'asc',
first: 20,
})
expect(result.data.map((a) => a.name)).toEqual(['asset 2', 'asset 9', 'asset 10', 'asset 100'])
})
it('does not regress lexicographic ordering for purely alphabetical names', async () => {
const { root } = await setupNaturalSortAssets(['banana', 'apple', 'cherry', 'apricot'])
const result = await assetService.listChildren({
assetId: root.id,
assetType: AssetType.file,
sort: 'name',
order: 'asc',
first: 20,
})
expect(result.data.map((a) => a.name)).toEqual(['apple', 'apricot', 'banana', 'cherry'])
})
})
+97
View File
@@ -735,3 +735,100 @@ describe('SearchService', () => {
})
})
})
describe('SearchService — natural sort by name', () => {
setupTestDbHooks()
let searchService: SearchService
beforeEach(() => {
searchService = new SearchService()
})
const setupSearchNaturalSortAssets = async (names: string[]) => {
const user = await prisma.user.create({
data: {
name: 'search-natural-sort-user',
email: `search-natural-sort-${Date.now()}@example.com`,
type: 'human',
},
})
const team = await prisma.team.create({ data: { name: 'search-natural-sort-team' } })
const project = await prisma.project.create({
data: { name: 'search-natural-sort-proj', teamId: team.id },
})
const root = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
for (const name of names) {
await prisma.asset.create({
data: {
name,
type: AssetType.file,
projectId: project.id,
parentId: root.id,
creatorId: user.id,
status: 'uploaded',
sizeByte: 0,
},
})
}
return { root }
}
it('returns results in natural name order (asc) via raw-SQL sort path', async () => {
const { root } = await setupSearchNaturalSortAssets(['clip10', 'clip2', 'clip20', 'clip1'])
const result = await searchService.search(root.id, {
recursively: false,
assetType: 'file',
operator: 'AND',
conditions: [],
isSemantic: false,
sort: { field: 'name', order: 'asc' },
})
expect(result.data.map((a) => a.name)).toEqual(['clip1', 'clip2', 'clip10', 'clip20'])
})
it('returns results in natural name order (desc) via raw-SQL sort path', async () => {
const { root } = await setupSearchNaturalSortAssets(['clip10', 'clip2', 'clip20', 'clip1'])
const result = await searchService.search(root.id, {
recursively: false,
assetType: 'file',
operator: 'AND',
conditions: [],
isSemantic: false,
sort: { field: 'name', order: 'desc' },
})
expect(result.data.map((a) => a.name)).toEqual(['clip20', 'clip10', 'clip2', 'clip1'])
})
it('sorts mixed alpha-numeric names naturally via search', async () => {
const { root } = await setupSearchNaturalSortAssets([
'scene 100',
'scene 9',
'scene 10',
'scene 2',
])
const result = await searchService.search(root.id, {
recursively: false,
assetType: 'file',
operator: 'AND',
conditions: [],
isSemantic: false,
sort: { field: 'name', order: 'asc' },
})
expect(result.data.map((a) => a.name)).toEqual(['scene 2', 'scene 9', 'scene 10', 'scene 100'])
})
})