Repository navigation
Expand file tree
/
Copy pathkeyword-terms.test.ts
More file actions
120 lines (108 loc) · 7.78 KB
/
Copy pathkeyword-terms.test.ts
File metadata and controls
120 lines (108 loc) · 7.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
// The keyword leg's terms, without a database: the same rule as the libSQL
// store's, pinned with the same cases, and how each kind of term is matched,
// down to the operator in the statement a search sends.
import { describe, expect, it } from 'vitest';
import type { KnowledgeSource } from '@objectstack/spec/ai';
import { PgvectorKnowledgeAdapter, type PgPoolLike } from '../index.js';
import { KEYWORD_SEPARATORS, containsOperator, isWordTerm, keywordTerms } from '../sql.js';
import { FakeEmbedder } from './live-pg.testkit.js';
describe('knowledge-pgvector keywordTerms', () => {
it('splits a query into terms at white space and punctuation, keeping a code whole', () => {
// Latin-script and spaced terms: the terms they always had.
expect(keywordTerms('What is the X-200 pump? v1.2, a/b; #tag (part 7731)')).toEqual([
'What', 'is', 'the', 'X-200', 'pump', 'v1.2', 'a/b', 'tag', 'part', '7731',
]);
expect(keywordTerms('出差 住宿')).toEqual(['出差', '住宿']);
expect(keywordTerms('pump PUMP Pump')).toEqual(['pump']);
expect(keywordTerms(Array.from({ length: 40 }, (_, i) => `w${i}`).join(' '))).toHaveLength(16);
});
it('cuts a run of Han, kana or Hangul into pieces of three characters and of two, keeping figures and codes whole', () => {
// An unspaced question: its figure, then the pieces of three, then those of two, up to the cap.
expect(keywordTerms('出差住宿费2000元以下需要审批吗')).toEqual([
'2000', '出差住', '差住宿', '住宿费', '元以下', '以下需', '下需要', '需要审', '要审批', '审批吗',
'出差', '差住', '住宿', '宿费', '元以', '以下',
]);
expect(keywordTerms('X-200型号的保修期')).toEqual([
'X-200', '型号的', '号的保', '的保修', '保修期', '型号', '号的', '的保', '保修', '修期',
]);
// A run of two is one piece, kept with the pieces of three; a run of one is dropped; a repeat counts once.
expect(keywordTerms('出差的住宿标准,「三十天」。出差')).toEqual([
'出差的', '差的住', '的住宿', '住宿标', '宿标准', '三十天', '出差', '差的', '的住', '住宿', '宿标', '标准', '三十', '十天',
]);
expect(keywordTerms('费 2000元')).toEqual(['2000']);
// Katakana with its prolonged sound mark, which belongs to no script, and Hangul.
expect(keywordTerms('コーヒー代')).toEqual(['コーヒ', 'ーヒー', 'ヒー代', 'コー', 'ーヒ', 'ヒー', 'ー代']);
expect(keywordTerms('휴가는')).toEqual(['휴가는', '휴가', '가는']);
});
it('keeps 々, 〆 and 〇 inside a run, and still splits at 、 and 。', () => {
// The three marks sit in the CJK symbols block, beside its punctuation.
expect(keywordTerms('人々')).toEqual(['人々']);
expect(keywordTerms('二〇二四年')).toEqual(['二〇二', '〇二四', '二四年', '二〇', '〇二', '二四', '四年']);
expect(keywordTerms('〆切日')).toEqual(['〆切日', '〆切', '切日']);
expect(keywordTerms('出差、住宿。审批')).toEqual(['出差', '住宿', '审批']);
});
it('splits at the punctuation of the CJK symbols block and at none of its letters or numbers', () => {
// Derived from the runtime's own Unicode tables, not from a list: a member of
// U+3000–303F separates terms exactly when it is neither a letter nor a number.
const block = Array.from({ length: 0x40 }, (_, i) => String.fromCodePoint(0x3000 + i));
const letterOrNumber = (c: string): boolean => /[\p{L}\p{N}]/u.test(c);
const separates = (c: string): boolean => `a${c}b`.split(KEYWORD_SEPARATORS).length === 2;
expect(block.filter(separates)).toEqual(block.filter((c) => !letterOrNumber(c)));
const letters = block.filter(letterOrNumber);
expect(letters).toEqual(expect.arrayContaining(['々', '〆', '〇', '〡', '〩', '〱', '〵', '〸', '〺', '〻', '〼']));
// Each of them, three in a row, is a term or yields pieces: none is dropped as punctuation.
for (const c of letters) expect(keywordTerms(c.repeat(3)).join('')).toContain(c);
// The vertical iteration mark and the Hangzhou numerals are Han: they stay inside a run.
expect(keywordTerms('人〻')).toEqual(['人〻']);
expect(keywordTerms('第〢〣号')).toEqual(['第〢〣', '〢〣号', '第〢', '〢〣', '〣号']);
// 、, 。 and the corner brackets still separate.
expect(keywordTerms('出差、住宿。「审批」')).toEqual(['出差', '住宿', '审批']);
});
it('splits with the same class as the libSQL store', () => {
// The libSQL store's test pins the same literal against its own class: keep the two pins, and so the two classes, identical.
expect(KEYWORD_SEPARATORS).toEqual(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u3004\u3008-\u3020\u302a-\u3030\u3036\u3037\u303d-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u);
});
it('matches a piece as a substring and a figure or a code of three characters or more on the tsvector', () => {
expect(keywordTerms('住宿费2000元以下').map((t) => [t, isWordTerm(t)])).toEqual([
['2000', true], ['住宿费', false], ['元以下', false], ['住宿', false], ['宿费', false], ['元以', false], ['以下', false],
]);
// A piece holding only 〆, which belongs to no script, is still a substring term, never a tsvector word.
expect(isWordTerm('〆〆〆')).toBe(false);
});
it('matches a substring term without a cased letter by LIKE, and one holding a cased letter by ILIKE', () => {
for (const term of ['元以下', '出差', 'コー', '휴가', '42']) expect(containsOperator(term)).toBe('LIKE');
for (const term of ['ab', 'X-200', 'É']) expect(containsOperator(term)).toBe('ILIKE');
});
});
describe('knowledge-pgvector keyword leg statement', () => {
const source = { name: 'kw', label: 'kw', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource;
/** A store with one stable active generation, which records each ranking statement and its values. */
function recordingPool(): { pool: PgPoolLike; ranked: Array<{ text: string; values: unknown[] }> } {
const ranked: Array<{ text: string; values: unknown[] }> = [];
const answer = async <R>(text: string, values: unknown[] = []): Promise<{ rows: R[] }> => {
if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.0' }] as R[] };
if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] as R[] };
if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) {
return { rows: [{ generation: 1, fingerprint: 'fp', recipe_hash: 'rh', dim: 384, state: 'active' }] as R[] };
}
if (text.includes('AS distance')) ranked.push({ text, values });
return { rows: [] as R[] };
};
return { pool: { query: answer, connect: async () => ({ query: answer, release: () => undefined }) }, ranked };
}
it('sends a caseless Chinese piece as content LIKE and a cased Latin term as content ILIKE', async () => {
const { pool, ranked } = recordingPool();
const adapter = new PgvectorKnowledgeAdapter({ id: 'kw', pool, embedder: new FakeEmbedder() });
await adapter.search('出差 ab', { source, topK: 5, index: { fingerprint: 'fp' } });
expect(ranked).toHaveLength(1);
const { text, values } = ranked[0];
// The operator in front of the placeholder a pattern is bound to, read from the statement itself.
const operatorOf = (pattern: string): string | undefined => {
const at = values.indexOf(pattern) + 1;
return at === 0 ? undefined : new RegExp(`content (I?LIKE) \\$${at}::text`).exec(text)?.[1];
};
expect(operatorOf('%出差%')).toBe('LIKE');
expect(operatorOf('%ab%')).toBe('ILIKE');
});
});