Elffuss BraidHub

kikocis/lancedb public

main · 2.2 KiBRawPermalink
1// Copyright 2023 Lance Developers.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15'use strict'
16
17
18async function example() {
19
20 const lancedb = require('vectordb')
21
22 // Import transformers and the all-MiniLM-L6-v2 model (https://huggingface.co/Xenova/all-MiniLM-L6-v2)
23 const { pipeline } = await import('@xenova/transformers')
24 const pipe = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
25
26
27 // Create embedding function from pipeline which returns a list of vectors from batch
28 // sourceColumn is the name of the column in the data to be embedded
29 //
30 // Output of pipe is a Tensor { data: Float32Array(384) }, so filter for the vector
31 const embed_fun = {}
32 embed_fun.sourceColumn = 'text'
33 embed_fun.embed = async function (batch) {
34 let result = []
35 for (let text of batch) {
36 const res = await pipe(text, { pooling: 'mean', normalize: true })
37 result.push(Array.from(res['data']))
38 }
39 return (result)
40 }
41
42 // Link a folder and create a table with data
43 const db = await lancedb.connect('data/sample-lancedb')
44
45 const data = [
46 { id: 1, text: 'Cherry', type: 'fruit' },
47 { id: 2, text: 'Carrot', type: 'vegetable' },
48 { id: 3, text: 'Potato', type: 'vegetable' },
49 { id: 4, text: 'Apple', type: 'fruit' },
50 { id: 5, text: 'Banana', type: 'fruit' }
51 ]
52
53 const table = await db.createTable('food_table', data, embed_fun)
54
55
56 // Query the table
57 const results = await table
58 .search("a sweet fruit to eat")
59 .metricType("cosine")
60 .limit(2)
61 .execute()
62 console.log(results.map(r => r.text))
63
64}
65
66example().then(_ => { console.log("Done!") })