Repository navigation
feat(graphile-search): vector search in the request language on tables with translations #2048
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
1f22120
ce447fe
bd1433d
d20e2d4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| -- Seed for vector search in the request's language. | ||
| -- articles carries @i18n articles_translations; each translation has its own vector. | ||
| -- | ||
| -- Requires postgres-plus:18 image with: vector | ||
|
|
||
| CREATE EXTENSION IF NOT EXISTS vector; | ||
|
|
||
| CREATE SCHEMA IF NOT EXISTS vector_i18n_test; | ||
|
|
||
| CREATE TABLE vector_i18n_test.articles ( | ||
| id serial PRIMARY KEY, | ||
| title text NOT NULL, | ||
| embedding vector(3) | ||
| ); | ||
|
|
||
| COMMENT ON TABLE vector_i18n_test.articles IS E'@i18n articles_translations'; | ||
|
|
||
| CREATE TABLE vector_i18n_test.articles_translations ( | ||
| id serial PRIMARY KEY, | ||
| articles_id integer NOT NULL REFERENCES vector_i18n_test.articles(id), | ||
| lang_code text NOT NULL, | ||
| title text, | ||
| embedding vector(3), | ||
| UNIQUE (articles_id, lang_code) | ||
| ); | ||
|
|
||
| -- Every article's own text points away from the query except article 1; | ||
| -- articles 2 and 3 only match the query through a translation. | ||
| INSERT INTO vector_i18n_test.articles (id, title, embedding) VALUES | ||
| (1, 'matches in the default language', '[1, 0, 0]'), | ||
| (2, 'matches only in French', '[0, 1, 0]'), | ||
| (3, 'matches only in Spanish', '[0, 0, 1]'), | ||
| (4, 'no match in any language', '[0, 1, 0]'); | ||
|
|
||
| INSERT INTO vector_i18n_test.articles_translations (articles_id, lang_code, title, embedding) VALUES | ||
| (2, 'fr', 'correspond en français', '[1, 0, 0]'), | ||
| (3, 'es', 'coincide en español', '[1, 0, 0]'), | ||
| (4, 'fr', 'ne correspond pas', '[0, 0, 1]'), | ||
| -- Article 1's French translation points away: a French request compares | ||
| -- through it, so article 1 is not a French match. | ||
| (1, 'fr', 'ne correspond pas en français', '[0, 1, 0]'); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| /** | ||
| * Vector search in the request's language. | ||
| * | ||
| * A table with translations (@i18n) is compared with the query through the | ||
| * translation in the first requested language the row has one for, and | ||
| * through the row's own vector otherwise. A default-language request never | ||
| * matches a row through another language's translation. | ||
| */ | ||
|
|
||
| import { ConnectionFilterPreset } from 'graphile-connection-filter'; | ||
| import type { GraphQLResponse } from 'graphile-test'; | ||
| import { getConnections, seed } from 'graphile-test'; | ||
| import { join } from 'path'; | ||
| import type { PgTestClient } from 'pgsql-test'; | ||
|
|
||
| import { createPgvectorAdapter } from '../adapters/pgvector'; | ||
| import { VectorCodecPlugin } from '../codecs/vector-codec'; | ||
| import { createUnifiedSearchPlugin } from '../plugin'; | ||
|
|
||
| type QueryFn = <TResult = unknown>( | ||
| query: string, | ||
| variables?: Record<string, unknown>, | ||
| commit?: boolean, | ||
| reqOptions?: Record<string, unknown> | ||
| ) => Promise<GraphQLResponse<TResult>>; | ||
|
|
||
| interface Result { | ||
| allArticles: { nodes: { rowId: number; embeddingVectorDistance: number | null }[] }; | ||
| } | ||
|
|
||
| describe('vector search follows the request language', () => { | ||
| let db: PgTestClient; | ||
| let teardown: () => Promise<void>; | ||
| let query: QueryFn; | ||
|
|
||
| beforeAll(async () => { | ||
| const connections = await getConnections( | ||
| { | ||
| schemas: ['vector_i18n_test'], | ||
| preset: { | ||
| extends: [ConnectionFilterPreset()], | ||
| plugins: [ | ||
| VectorCodecPlugin, | ||
| createUnifiedSearchPlugin({ adapters: [createPgvectorAdapter()], enableSearchScore: true }), | ||
| ], | ||
| }, | ||
| useRoot: true, | ||
| authRole: 'postgres', | ||
| }, | ||
| [seed.sqlfile([join(__dirname, './vector-i18n.sql')])] | ||
| ); | ||
| db = connections.db; | ||
| teardown = connections.teardown; | ||
| query = connections.query as QueryFn; | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| if (teardown) await teardown(); | ||
| }); | ||
|
|
||
| beforeEach(() => db.beforeEach()); | ||
| afterEach(() => db.afterEach()); | ||
|
|
||
| async function matches(langCodes?: string[]): Promise<number[]> { | ||
| const result = await query<Result>( | ||
| `query { | ||
| allArticles( | ||
| where: { vectorEmbedding: { vector: [1, 0, 0], metric: COSINE, distance: 0.1 } } | ||
| orderBy: PRIMARY_KEY_ASC | ||
| ) { nodes { rowId embeddingVectorDistance } } | ||
| }`, | ||
| undefined, | ||
| false, | ||
| langCodes ? { langCodes } : undefined | ||
| ); | ||
| expect(result.errors).toBeUndefined(); | ||
| return result.data!.allArticles.nodes.map((n) => n.rowId); | ||
| } | ||
|
|
||
| it('compares only the base rows without a request language', async () => { | ||
| expect(await matches()).toEqual([1]); | ||
| }); | ||
|
|
||
| it('never matches through a translation in a default-language request', async () => { | ||
| expect(await matches(['en'])).toEqual([1]); | ||
| }); | ||
|
|
||
| it('compares through the requested translation, falling back to the base row', async () => { | ||
| // 2 matches through French; 1 has a French translation that does not | ||
| // match; 3 has no French translation and its own text does not match. | ||
| expect(await matches(['fr'])).toEqual([2]); | ||
| // 3 matches through Spanish; 1 has no Spanish translation and falls back | ||
| // to its own (matching) text. | ||
| expect(await matches(['es'])).toEqual([1, 3]); | ||
| }); | ||
|
|
||
| it('falls back from a regional request to its primary language', async () => { | ||
| expect(await matches(['fr-CA'])).toEqual([2]); | ||
| }); | ||
|
|
||
| it('uses the first requested language a row has a translation in', async () => { | ||
| expect(await matches(['es', 'fr'])).toEqual([2, 3]); | ||
| }); | ||
|
|
||
| it('scores a row by the vector it was compared through', async () => { | ||
| const result = await query<Result>( | ||
| `query { | ||
| allArticles( | ||
| where: { vectorEmbedding: { vector: [1, 0, 0], metric: COSINE } } | ||
| orderBy: PRIMARY_KEY_ASC | ||
| ) { nodes { rowId embeddingVectorDistance } } | ||
| }`, | ||
| undefined, | ||
| false, | ||
| { langCodes: ['fr'] } | ||
| ); | ||
| expect(result.errors).toBeUndefined(); | ||
| const distance = Object.fromEntries( | ||
| result.data!.allArticles.nodes.map((n) => [n.rowId, n.embeddingVectorDistance]) | ||
| ); | ||
| expect(distance[2]).toBeCloseTo(0); | ||
| expect(distance[1]).toBeCloseTo(1); | ||
| expect(distance[3]).toBeCloseTo(1); | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| /** | ||
| * Translation vectors for a table with translations. | ||
| * | ||
| * A table the DataI18n module translated carries `@i18n <translations table>`. | ||
| * When that translations table has a vector column of the same name (the | ||
| * metaschema gives it one whenever the base table has one), vector search can | ||
| * compare a query with the translation in the request's language. | ||
| */ | ||
|
|
||
| export interface I18nVectorInfo { | ||
| schema: string; | ||
| tableName: string; | ||
| /** Translations column referencing the base row (`<base table>_id`). */ | ||
| parentFkField: string; | ||
| parentPkField: string; | ||
| langField: string; | ||
| embeddingField: string; | ||
| /** Translations column recording the model each translation vector came from. */ | ||
| modelColumn: string | null; | ||
| } | ||
|
|
||
| export function getI18nVectorInfo( | ||
| codec: any, | ||
| attributeName: string, | ||
| dimensions: number | undefined, | ||
| build: any | ||
| ): I18nVectorInfo | undefined { | ||
| const tableName = codec?.extensions?.tags?.i18n; | ||
| const pg = codec?.extensions?.pg; | ||
| if (typeof tableName !== 'string' || !tableName || !pg?.schemaName || !pg?.name) return undefined; | ||
|
|
||
| const codecs = Object.values(build?.input?.pgRegistry?.pgCodecs ?? {}) as any[]; | ||
| const translations = codecs.find( | ||
| (c) => c?.attributes && c.extensions?.pg?.schemaName === pg.schemaName && c.extensions?.pg?.name === tableName | ||
| ); | ||
| const attributes = translations?.attributes as Record<string, any> | undefined; | ||
| const vector = attributes?.[attributeName]; | ||
| if (vector?.codec?.name !== 'vector') return undefined; | ||
| // A translation vector of another width cannot be compared with the query. | ||
| const translationDimensions = vector.extensions?.vectorDimensions; | ||
| if (dimensions && translationDimensions && dimensions !== translationDimensions) return undefined; | ||
|
|
||
| const resources = Object.values(build?.input?.pgRegistry?.pgResources ?? {}) as any[]; | ||
| const primaryKey = resources | ||
| .find((r) => r?.codec === codec && !r.parameters) | ||
| ?.uniques?.find((u: any) => u.isPrimary)?.attributes; | ||
| if (!Array.isArray(primaryKey) || primaryKey.length !== 1) return undefined; | ||
| const parentPkField: string = primaryKey[0]; | ||
|
|
||
| const parentFkField = `${pg.name}_id`; | ||
| const langField = 'lang_code'; | ||
| if (!attributes[parentFkField] || !attributes[langField]) return undefined; | ||
|
|
||
| const modelColumn = | ||
| Object.entries(attributes).find(([, other]) => other.extensions?.tags?.embeddingModelOf === attributeName)?.[0] ?? | ||
| null; | ||
|
|
||
| return { | ||
| schema: pg.schemaName, | ||
| tableName, | ||
| parentFkField, | ||
| parentPkField, | ||
| langField, | ||
| embeddingField: attributeName, | ||
| modelColumn, | ||
| }; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,6 +10,7 @@ import type { SQL } from 'pg-sql2'; | |
|
|
||
| import type { FilterApplyResult,SearchableColumn, SearchAdapter } from '../types'; | ||
| import { type ChunksInfo,getChunksInfo } from './chunks'; | ||
| import { getI18nVectorInfo, type I18nVectorInfo } from './i18n'; | ||
|
|
||
| /** | ||
| * Build a distance expression for the given metric. | ||
|
|
@@ -101,12 +102,14 @@ export function createPgvectorAdapter( | |
| const modelColumn = Object.entries(codec.attributes as Record<string, any>).find( | ||
| ([, other]) => other.extensions?.tags?.embeddingModelOf === attributeName | ||
| )?.[0]; | ||
| const i18nInfo = getI18nVectorInfo(codec, attributeName, dimensions, _build); | ||
| columns.push({ | ||
| attributeName, | ||
| adapterData: | ||
| chunksInfo || dimensions || model || modelColumn | ||
| chunksInfo || dimensions || model || modelColumn || i18nInfo | ||
| ? { | ||
| ...(chunksInfo && { chunksInfo }), | ||
| ...(i18nInfo && { i18nInfo }), | ||
| ...(dimensions && { dimensions }), | ||
| ...(model && { model }), | ||
| ...(modelColumn && { modelColumn }), | ||
|
|
@@ -224,7 +227,12 @@ export function createPgvectorAdapter( | |
| const vectorExpr = sql`${sql.value(vectorString)}::vector`; | ||
|
|
||
| // Check if this column has chunks info and chunk querying is requested | ||
| const adapterData = column.adapterData as { chunksInfo?: ChunksInfo; modelColumn?: string } | undefined; | ||
| const adapterData = column.adapterData as { | ||
| chunksInfo?: ChunksInfo; | ||
| modelColumn?: string; | ||
| i18nInfo?: I18nVectorInfo; | ||
| langCodes?: string[]; | ||
| } | undefined; | ||
| const chunksInfo = adapterData?.chunksInfo; | ||
|
|
||
| // A row whose vector another model produced is not a worse match, it is | ||
|
|
@@ -240,6 +248,50 @@ export function createPgvectorAdapter( | |
| const scored = (distance: SQL): SQL => | ||
| sameModel ? sql`CASE WHEN ${sameModel} THEN ${distance} END` : distance; | ||
|
|
||
| // A table with translations (@i18n) is searched in the request's | ||
| // language: a row is compared through its translation in the first | ||
| // requested language it has one embedded for, and through its own | ||
| // vector otherwise. A default-language request finds no translation and | ||
| // compares the base rows only, so another language's text never matches. | ||
| const i18nInfo = adapterData?.i18nInfo; | ||
| const langCodes = adapterData?.langCodes; | ||
| let translationDistance: SQL | null = null; | ||
| if (i18nInfo && langCodes && langCodes.length > 0) { | ||
| const t = sql.identifier('__translation'); | ||
| const langs = sql`${sql.value(langCodes)}::text[]`; | ||
| const position = sql`array_position(${langs}, ${t}.${sql.identifier(i18nInfo.langField)}::text)`; | ||
| const translationVector = sql`${t}.${sql.identifier(i18nInfo.embeddingField)}`; | ||
| const translationModel = | ||
| i18nInfo.modelColumn && typeof model === 'string' && model | ||
| ? sql` AND ${t}.${sql.identifier(i18nInfo.modelColumn)} = ${sql.value(model)}` | ||
| : sql``; | ||
| translationDistance = sql`( | ||
| SELECT ${buildDistanceExpr(sql, translationVector, vectorExpr, resolvedMetric)} | ||
| FROM ${sql.identifier(i18nInfo.schema, i18nInfo.tableName)} AS ${t} | ||
| WHERE ${t}.${sql.identifier(i18nInfo.parentFkField)} = ${alias}.${sql.identifier(i18nInfo.parentPkField)} | ||
| AND ${position} IS NOT NULL | ||
| AND ${translationVector} IS NOT NULL${translationModel} | ||
| ORDER BY ${position} | ||
| LIMIT 1 | ||
| )`; | ||
| } | ||
| const inRequestLanguage = (baseDistance: SQL, baseScorable: SQL | null): FilterApplyResult => { | ||
| const scoreExpression = translationDistance | ||
| ? sql`COALESCE(${translationDistance}, ${baseDistance})` | ||
| : baseDistance; | ||
| const scorableClause = translationDistance | ||
| ? sql`(${translationDistance} IS NOT NULL OR ${baseScorable ?? sql`true`})` | ||
|
Comment on lines
+279
to
+283
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 bug · medium Translation distance suppresses chunk matches entirely On a table with both 📋 Prompt for AI AgentsIn graphile/graphile-search/src/adapters/pgvector.ts, the |
||
| : baseScorable; | ||
| return { | ||
| whereClause: | ||
| distance !== undefined && distance !== null | ||
| ? sql`${scoreExpression} <= ${sql.value(distance)}` | ||
| : null, | ||
| scoreExpression, | ||
| scorableClause, | ||
| }; | ||
| }; | ||
|
|
||
| if (chunksInfo && (includeChunks !== false)) { | ||
| // Chunk-aware query: find the closest chunk for each parent row | ||
| // Uses a lateral subquery to get the minimum distance across all chunks | ||
|
|
@@ -277,22 +329,20 @@ export function createPgvectorAdapter( | |
| // MIN(distance) is NULL exactly when no chunk has an embedding. | ||
| const scorableClause = sql`(${parentScorable} OR ${chunkDistanceSubquery} IS NOT NULL)`; | ||
|
|
||
| let whereClause: SQL | null = null; | ||
| if (distance !== undefined && distance !== null) { | ||
| whereClause = sql`${combinedDistanceExpr} <= ${sql.value(distance)}`; | ||
| } | ||
|
|
||
| return { | ||
| whereClause, | ||
| scoreExpression: combinedDistanceExpr, | ||
| scorableClause, | ||
| }; | ||
| return inRequestLanguage(combinedDistanceExpr, scorableClause); | ||
| } | ||
|
|
||
| // Standard (non-chunk) query | ||
| const columnExpr = sql`${alias}.${sql.identifier(column.attributeName)}`; | ||
| const distanceExpr = buildDistanceExpr(sql, columnExpr, vectorExpr, resolvedMetric); | ||
|
|
||
| if (translationDistance) { | ||
| return inRequestLanguage( | ||
| scored(distanceExpr), | ||
| both(sameModel, sql`${columnExpr} IS NOT NULL`) | ||
| ); | ||
| } | ||
|
|
||
| let whereClause: SQL | null = null; | ||
| if (distance !== undefined && distance !== null) { | ||
| whereClause = sql`${distanceExpr} <= ${sql.value(distance)}`; | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Reject translation vectors whose declared width is unknown.
The guard returns
undefinedonly when both declared widths are known and differ. An unconstrainedvectorcolumn has no declared width, so the check passes. A translation row whose vector width differs from the base column can then reach the pgvector distance operator. pgvector rejects the mismatch, so the search request fails instead of using the base-vector fallback. This needs a translation column with no declared width, which the repository's fixtures do not produce.Require both widths to be known and equal before translation scoring is enabled. Two
vector(3)columns still get translation discovery.Suggested fix
Committable suggestion