Skip to content

Commit 23f20e9

Browse files
author
福晋
committed
chore: add load options
1 parent 5cd4e3c commit 23f20e9

8 files changed

Lines changed: 94 additions & 12 deletions

File tree

‎README.md‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ const results = await ctx.query('How to configure a line chart', { library: 'g2'
114114
115115
In read-only mode, `Context` opens existing `${library}.zvec` files with `ZVecOpen`. It does not create missing stores, and `load()` will throw because it would mutate the zvec file.
116116
117-
### `ctx.load(library, pattern)`
117+
### `ctx.load(library, pattern, options?)`
118118
119119
Load files into a specified library with automatic batch vectorization. Documents are embedded in batches and inserted into the vector store. A content-hash change detection mechanism re-embeds files whose content has changed since the last load.
120120
@@ -124,12 +124,26 @@ Document IDs are derived from file paths relative to `basePath` for cross-machin
124124
|-----------|------|-------------|
125125
| `library` | `string` | Library name for organizing documents |
126126
| `pattern` | `string \| string[]` | Glob pattern(s) matching files to load |
127+
| `options.buildIndexContent` | `(document, context) => string \| Promise<string>` | Build derived text used for embedding and the `indexContent` FTS field while preserving the original returned content |
127128
128129
```typescript
129130
await ctx.load('g2', './docs/**/*.md');
130131
await ctx.load('g2', ['./docs/**/*.md', './docs/**/*.json']);
132+
133+
await ctx.load('g2', './docs/**/*.md', {
134+
buildIndexContent: (doc) => [
135+
doc.meta?.title,
136+
doc.meta?.description,
137+
...(Array.isArray(doc.meta?.tags) ? doc.meta.tags : []),
138+
doc.content.slice(0, 500),
139+
].filter(Boolean).join('\n'),
140+
});
131141
```
132142
143+
When `buildIndexContent` is provided, its result is used for embedding and can
144+
be queried by configuring `ftsFields: ['indexContent']`. The original
145+
`document.content` is stored unchanged and returned by `query()`.
146+
133147
Load phases emit progress via the `onProgress` callback:
134148
135149
```typescript

‎package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
{
22
"name": "@antv/context",
3-
"version": "0.1.1",
3+
"version": "0.1.2",
44
"description": "A local context retrieval library that enables semantic search over your documentation. It loads documents (Markdown, JSON, Text), vectorizes them using [Transformers.js](https://huggingface.co/transformers.js), and stores vectors locally in `.zvec` files for fast semantic querying. ",
55
"main": "dist/index.js",
66
"types": "dist/index.d.ts",
77
"scripts": {
8-
"build": "tsc",
8+
"build": "rm -rf dist && tsc",
99
"test": "HF_ENDPOINT=https://hf-mirror.com vitest run --coverage",
1010
"lint": "eslint src/ --ext .ts",
1111
"lint:fix": "eslint src/ --ext .ts --fix",

‎src/context.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
QueryOptions,
77
QueryResult,
88
LoadedDoc,
9+
LoadOptions,
910
} from './types';
1011
import { Embedder } from './embedder';
1112

@@ -54,7 +55,7 @@ export class Context {
5455
return new Context(options, embedder, { dimensions: embedder.dimensions });
5556
}
5657

57-
async load(library: string, pattern: string | string[]): Promise<void> {
58+
async load(library: string, pattern: string | string[], options: LoadOptions = {}): Promise<void> {
5859
const patterns = Array.isArray(pattern) ? pattern : [pattern];
5960
const files = await glob(patterns, { absolute: true });
6061

@@ -69,10 +70,14 @@ export class Context {
6970

7071
const doc = await loader.load(filePath);
7172
const relativePath = path.relative(this.options.basePath!, filePath);
73+
const indexContent = options.buildIndexContent
74+
? await options.buildIndexContent(doc, { library, filePath, relativePath })
75+
: doc.content;
7276
return {
7377
...doc,
78+
indexContent,
7479
id: pathToId(relativePath),
75-
contentHash: computeContentHash(doc.content),
80+
contentHash: computeContentHash(`${doc.content}\n\0${indexContent}`),
7681
path: relativePath,
7782
};
7883
}),
@@ -91,7 +96,7 @@ export class Context {
9196

9297
if (docsToEmbed.length === 0) return;
9398

94-
const contents = docsToEmbed.map((doc) => doc.content);
99+
const contents = docsToEmbed.map((doc) => doc.indexContent);
95100
const vectors = await this.embedder.embedBatch(contents);
96101

97102
if (this.options.onProgress) {
@@ -103,6 +108,7 @@ export class Context {
103108
vector: vectors[index],
104109
fields: {
105110
content: doc.content,
111+
indexContent: doc.indexContent,
106112
meta: doc.meta ? JSON.stringify(doc.meta) : '',
107113
path: doc.path,
108114
contentHash: doc.contentHash,

‎src/storage/schema.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,18 @@ const INDEX_TYPES = {
1919
HNSW: ZVecIndexType.HNSW,
2020
};
2121

22-
export function buildZvecSchema(dims: number, tokenizerName: string = 'jieba'): ZVecCollectionSchema {
22+
export function buildZvecSchema(
23+
dims: number,
24+
tokenizerName: string = 'jieba',
25+
ftsFields: string[] = ['content'],
26+
): ZVecCollectionSchema {
27+
const fts = (name: string): Pick<ZvecFieldSchema, 'indexType' | 'indexOptions'> =>
28+
ftsFields.includes(name)
29+
? { indexType: 'FTS', indexOptions: { tokenizerName } }
30+
: {};
2331
const fields: ZvecFieldSchema[] = [
24-
{ name: 'content', dataType: 'STRING', indexType: 'FTS', indexOptions: { tokenizerName } },
32+
{ name: 'content', dataType: 'STRING', ...fts('content') },
33+
{ name: 'indexContent', dataType: 'STRING', ...fts('indexContent') },
2534
{ name: 'meta', dataType: 'STRING' },
2635
{ name: 'path', dataType: 'STRING' },
2736
{ name: 'contentHash', dataType: 'STRING' },
@@ -48,4 +57,4 @@ export function buildZvecSchema(dims: number, tokenizerName: string = 'jieba'):
4857
: {}),
4958
})) as never,
5059
}) as ZVecCollectionSchema;
51-
}
60+
}

‎src/storage/store.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,11 @@ export class Store {
4646
if (fs.existsSync(filePath)) {
4747
collection = ZVecOpen(filePath, { readOnly: this.options.readOnly });
4848
} else {
49-
const schema = buildZvecSchema(this.embedder.dimensions, tokenizerName);
49+
const schema = buildZvecSchema(
50+
this.embedder.dimensions,
51+
tokenizerName,
52+
this.options.ftsFields,
53+
);
5054
collection = ZVecCreateAndOpen(filePath, schema, { readOnly: this.options.readOnly });
5155
}
5256

‎src/types.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ export interface Document {
1414
* Document with computed fields for loading.
1515
*/
1616
export interface LoadedDoc extends Document {
17+
/** Derived text used for embedding and optional FTS indexing. */
18+
indexContent: string;
1719
/** Document ID */
1820
id: string;
1921
/** Hash of document content */
@@ -22,6 +24,17 @@ export interface LoadedDoc extends Document {
2224
path: string;
2325
}
2426

27+
export interface LoadOptions {
28+
/**
29+
* Build focused text for embedding and FTS while preserving the original
30+
* document content returned by query(). Defaults to document.content.
31+
*/
32+
buildIndexContent?: (
33+
document: Document,
34+
context: { library: string; filePath: string; relativePath: string },
35+
) => string | Promise<string>;
36+
}
37+
2538
/** Configuration for query expansion. */
2639
export interface QueryExpansionOptions {
2740
/**

‎test/context.test.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,34 @@ describe('Context', () => {
9090
expect(results[0].meta).toHaveProperty('title');
9191
});
9292

93+
it('should index derived content while returning original content', async () => {
94+
const indexDir = TEST_DIR + '-index-content';
95+
const indexContext = await Context.create({
96+
vectorsDir: indexDir,
97+
ftsFields: ['indexContent'],
98+
});
99+
100+
await indexContext.load(
101+
'index-content',
102+
path.join(FIXTURES_DIR, 'getting-started.md'),
103+
{
104+
buildIndexContent: (doc) => `unique-index-marker ${String(doc.meta?.title ?? '')}`,
105+
},
106+
);
107+
108+
const results = await indexContext.query('unique-index-marker', {
109+
library: 'index-content',
110+
topK: 1,
111+
rerank: false,
112+
});
113+
expect(results).toHaveLength(1);
114+
expect(results[0].content).toContain('npm');
115+
expect(results[0].content).not.toContain('unique-index-marker');
116+
117+
await indexContext.close();
118+
fs.rmSync(indexDir, { recursive: true, force: true });
119+
});
120+
93121
it('should skip already loaded documents (deduplication)', async () => {
94122
await ctx.load('md', path.join(FIXTURES_DIR, 'getting-started.md'));
95123

@@ -398,4 +426,4 @@ describe('Context two-phase separation', () => {
398426

399427
await ctx3.close();
400428
});
401-
});
429+
});

‎test/storage/schema.test.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@ describe('buildZvecSchema', () => {
2626
expect(schemaStr).toContain('tokenizer_name:jieba');
2727
});
2828

29+
it('should include indexContent with an FTS index', () => {
30+
const schema = buildZvecSchema(128, 'jieba', ['indexContent']);
31+
const schemaStr = String(schema);
32+
33+
expect(schemaStr).toContain("name: 'indexContent'");
34+
expect(schemaStr).toContain('FtsIndexParams');
35+
});
36+
2937
it('should accept custom tokenizer (standard)', () => {
3038
const schema = buildZvecSchema(128, 'standard');
3139
const schemaStr = String(schema);
@@ -48,4 +56,4 @@ describe('buildZvecSchema', () => {
4856

4957
expect(schemaStr).toContain('data_type: VECTOR_FP32');
5058
});
51-
});
59+
});

0 commit comments

Comments
 (0)