1 | import { PineconeClient } from "@pinecone-database/[email protected]"; |
2 | import { UpsertOperationRequest } from "@pinecone-database/[email protected]/dist/pinecone-generated-ts-fetch/index.js"; |
3 |
|
4 | type Pinecone = { |
5 | apiKey: string; |
6 | environment: string; |
7 | }; |
8 | export async function main( |
9 | auth: Pinecone, |
10 | index_name: string, |
11 | vectors: { id: string; values: number[]; metadata?: Record<string, any> }[], |
12 | namespace?: string, |
13 | raw?: boolean, |
14 | ) { |
15 | const client = new PineconeClient(); |
16 | await client.init(auth); |
17 | const index = client.Index(index_name); |
18 |
|
19 | const upsertRequest: UpsertOperationRequest = removeObjectEmptyFields({ |
20 | vectors, |
21 | namespace, |
22 | }); |
23 | return await index[raw ? "upsertRaw" : "upsert"]({ upsertRequest }); |
24 | } |
25 |
|
26 | function removeObjectEmptyFields( |
27 | object?: Record<string, any>, |
28 | removeEmptyArraysAndObjects = true, |
29 | createNewObject = true, |
30 | ) { |
31 | if (!object || typeof object !== "object") return {} |
32 | const obj = createNewObject ? { ...object } : object |
33 | const emptyValues = [undefined, null, ""] |
34 | for (const key in obj) { |
35 | const value = obj[key] |
36 | if (emptyValues.includes(value)) { |
37 | delete obj[key] |
38 | } else if (typeof value === "object") { |
39 | if (Object.keys(value).length) { |
40 | obj[key] = removeObjectEmptyFields(value, removeEmptyArraysAndObjects, false) |
41 | } |
42 | if (!Object.keys(value).length && removeEmptyArraysAndObjects) { |
43 | delete obj[key] |
44 | } |
45 | } |
46 | } |
47 | return obj |
48 | } |
49 |
|