Edits history of script submission #22490 for ' Upsert Vectors (pinecone)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import { PineconeClient } from "@pinecone-database/[email protected]";
    import { UpsertOperationRequest } from "@pinecone-database/[email protected]/dist/pinecone-generated-ts-fetch/index.js";
    
    type Pinecone = {
      apiKey: string;
      environment: string;
    };
    export async function main(
      auth: Pinecone,
      index_name: string,
      vectors: { id: string; values: number[]; metadata?: Record<string, any> }[],
      namespace?: string,
      raw?: boolean,
    ) {
      const client = new PineconeClient();
      await client.init(auth);
      const index = client.Index(index_name);
    
      const upsertRequest: UpsertOperationRequest = removeObjectEmptyFields({
        vectors,
        namespace,
      });
      return await index[raw ? "upsertRaw" : "upsert"]({ upsertRequest });
    }
    
    function removeObjectEmptyFields(
      object?: Record<string, any>,
      removeEmptyArraysAndObjects = true,
      createNewObject = true,
    ) {
      if (!object || typeof object !== "object") return {}
      const obj = createNewObject ? { ...object } : object
      const emptyValues = [undefined, null, ""]
      for (const key in obj) {
        const value = obj[key]
        if (emptyValues.includes(value)) {
          delete obj[key]
        } else if (typeof value === "object") {
          if (Object.keys(value).length) {
            obj[key] = removeObjectEmptyFields(value, removeEmptyArraysAndObjects, false)
          }
          if (!Object.keys(value).length && removeEmptyArraysAndObjects) {
            delete obj[key]
          }
        }
      }
      return obj
    }
    

    Submitted by hugo989 6 days ago