0

Upsert Vectors

by
Published Apr 18, 2023
Script pinecone Verified

The script

Submitted by hugo989 Bun
Verified 6 days ago
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

Other submissions
  • Submitted by adam186 Deno
    Created 398 days ago
    1
    import { removeObjectEmptyFields } from "https://deno.land/x/[email protected]/mod.ts";
    2
    import { PineconeClient } from "npm:@pinecone-database/pinecone";
    3
    import { UpsertOperationRequest } from "npm:@pinecone-database/pinecone/0.0.12/dist/pinecone-generated-ts-fetch/index.js";
    4
    
    
    5
    type Pinecone = {
    6
      apiKey: string;
    7
      environment: string;
    8
    };
    9
    export async function main(
    10
      auth: Pinecone,
    11
      index_name: string,
    12
      vectors: { id: string; values: number[]; metadata?: Record<string, any> }[],
    13
      namespace?: string,
    14
      raw?: boolean,
    15
    ) {
    16
      const client = new PineconeClient();
    17
      await client.init(auth);
    18
      const index = client.Index(index_name);
    19
    
    
    20
      const upsertRequest: UpsertOperationRequest = removeObjectEmptyFields({
    21
        vectors,
    22
        namespace,
    23
      });
    24
      return await index[raw ? "upsertRaw" : "upsert"]({ upsertRequest });
    25
    }
    26