-
Notifications
You must be signed in to change notification settings - Fork 90
docs(examples): add metadata filter operator snippets #438
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
Open
moroshani
wants to merge
5
commits into
usemoss:main
Choose a base branch
from
moroshani:docs/metadata-filter-operator-examples
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
2060ba9
docs(examples): add metadata filter operator snippets
moroshani de35eea
fix(examples): make metadata filter cleanup robust
moroshani e378388
Merge remote-tracking branch 'upstream/main' into docs/metadata-filte…
moroshani edd5105
Merge remote-tracking branch 'upstream/main' into docs/metadata-filte…
moroshani 5a0219c
Address metadata example cleanup review
moroshani File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import { runMetadataFilterExample } from "./shared"; | ||
|
|
||
| runMetadataFilterExample({ | ||
| operator: "$and", | ||
| description: "Use $and to require multiple metadata filters to match together.", | ||
| query: "running shoes available in New York", | ||
| filter: { | ||
| $and: [ | ||
| { field: "category", condition: { $eq: "shoes" } }, | ||
| { field: "city", condition: { $eq: "new-york" } }, | ||
| ], | ||
| }, | ||
| }).catch((error) => { | ||
| console.error(error); | ||
| process.exitCode = 1; | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import { runMetadataFilterExample } from "./shared"; | ||
|
|
||
| runMetadataFilterExample({ | ||
| operator: "$eq", | ||
| description: "Use $eq to match documents whose metadata field has one exact value.", | ||
| query: "running shoes for city training", | ||
| filter: { | ||
| field: "category", | ||
| condition: { $eq: "shoes" }, | ||
| }, | ||
| }).catch((error) => { | ||
| console.error(error); | ||
| process.exitCode = 1; | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import { runMetadataFilterExample } from "./shared"; | ||
|
|
||
| runMetadataFilterExample({ | ||
| operator: "$in", | ||
| description: "Use $in to match documents whose metadata value is in an allowed list.", | ||
| query: "portable gear for commuters", | ||
| filter: { | ||
| field: "city", | ||
| condition: { $in: ["new-york", "seattle"] }, | ||
| }, | ||
| }).catch((error) => { | ||
| console.error(error); | ||
| process.exitCode = 1; | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import { runMetadataFilterExample } from "./shared"; | ||
|
|
||
| runMetadataFilterExample({ | ||
| operator: "$near", | ||
| description: "Use $near to match location metadata within a radius in meters.", | ||
| query: "city products near Times Square", | ||
| filter: { | ||
| field: "location", | ||
| condition: { $near: "40.7580,-73.9855,5000" }, | ||
| }, | ||
| }).catch((error) => { | ||
| console.error(error); | ||
| process.exitCode = 1; | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| import { MossClient, type DocumentInfo } from "@moss-dev/moss"; | ||
| import { randomUUID } from "node:crypto"; | ||
| import { config } from "dotenv"; | ||
|
|
||
| config(); | ||
|
|
||
| type MetadataFilter = Record<string, unknown>; | ||
|
|
||
| interface MetadataFilterExample { | ||
| operator: string; | ||
| description: string; | ||
| query: string; | ||
| filter: MetadataFilter; | ||
| } | ||
|
|
||
| const documents: DocumentInfo[] = [ | ||
| { | ||
| id: "shoe-nyc-001", | ||
| text: "Breathable road running shoes for daily city training.", | ||
| metadata: { | ||
| category: "shoes", | ||
| brand: "swiftfit", | ||
| city: "new-york", | ||
| location: "40.7580,-73.9855", | ||
| }, | ||
| }, | ||
| { | ||
| id: "shoe-denver-002", | ||
| text: "Trail running shoes built for rocky mountain paths.", | ||
| metadata: { | ||
| category: "shoes", | ||
| brand: "peakstride", | ||
| city: "denver", | ||
| location: "39.7392,-104.9903", | ||
| }, | ||
| }, | ||
| { | ||
| id: "bag-nyc-003", | ||
| text: "Lightweight commuter backpack with a laptop sleeve.", | ||
| metadata: { | ||
| category: "bags", | ||
| brand: "urbanpack", | ||
| city: "new-york", | ||
| location: "40.7505,-73.9934", | ||
| }, | ||
| }, | ||
| { | ||
| id: "bag-seattle-004", | ||
| text: "Compact travel duffel with a separate shoe compartment.", | ||
| metadata: { | ||
| category: "bags", | ||
| brand: "swiftfit", | ||
| city: "seattle", | ||
| location: "47.6205,-122.3493", | ||
| }, | ||
| }, | ||
| ]; | ||
|
|
||
| function requireEnv(name: string): string { | ||
| const value = process.env[name]?.trim(); | ||
|
|
||
| if (!value) { | ||
| throw new Error( | ||
| `Missing ${name}. Add it to .env before running this example.`, | ||
| ); | ||
| } | ||
|
|
||
| return value; | ||
| } | ||
|
|
||
| export async function runMetadataFilterExample( | ||
| example: MetadataFilterExample, | ||
| ): Promise<void> { | ||
| const projectId = requireEnv("MOSS_PROJECT_ID"); | ||
| const projectKey = requireEnv("MOSS_PROJECT_KEY"); | ||
| const indexName = `metadata-filter-${example.operator.slice(1)}-${randomUUID()}`; | ||
| const client = new MossClient(projectId, projectKey); | ||
| let cleanupNeeded = false; | ||
| let operationError: unknown; | ||
| let operationFailed = false; | ||
|
|
||
| try { | ||
| console.log(`Moss metadata filter example: ${example.operator}`); | ||
| console.log(example.description); | ||
|
|
||
| console.log(`\nCreating temporary index: ${indexName}`); | ||
| cleanupNeeded = true; | ||
| await client.createIndex(indexName, documents, { modelId: "moss-minilm" }); | ||
|
|
||
| console.log("Loading index locally for filtered query..."); | ||
| await client.loadIndex(indexName); | ||
|
|
||
| console.log(`\nQuery: ${example.query}`); | ||
| console.log(`Filter: ${JSON.stringify(example.filter)}`); | ||
|
|
||
| const results = await client.query(indexName, example.query, { | ||
| topK: 5, | ||
| alpha: 0.5, | ||
| filter: example.filter, | ||
| }); | ||
|
|
||
| const timing = | ||
| results.timeTakenInMs === undefined | ||
| ? "" | ||
| : ` in ${results.timeTakenInMs}ms`; | ||
| console.log(`\nFound ${results.docs.length} result(s)${timing}:`); | ||
| results.docs.forEach((doc, index) => { | ||
| const preview = | ||
| doc.text.length > 80 ? `${doc.text.slice(0, 80)}...` : doc.text; | ||
| console.log( | ||
| `${index + 1}. [${doc.id}] score=${doc.score.toFixed(3)} ${preview}`, | ||
| ); | ||
| console.log(` metadata=${JSON.stringify(doc.metadata ?? {})}`); | ||
| }); | ||
| } catch (error) { | ||
| operationError = error; | ||
| operationFailed = true; | ||
| } | ||
|
|
||
| if (cleanupNeeded) { | ||
| console.log(`\nDeleting temporary index: ${indexName}`); | ||
| try { | ||
| const deleted = await client.deleteIndex(indexName); | ||
| if (!deleted) { | ||
| throw new Error(`Moss did not delete temporary index: ${indexName}`); | ||
| } | ||
| } catch (cleanupError) { | ||
| if (operationFailed) { | ||
| console.warn( | ||
| `Failed to delete temporary index: ${indexName}`, | ||
| cleanupError, | ||
| ); | ||
| } else { | ||
| throw cleanupError; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if (operationFailed) { | ||
| throw operationError; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.