Edits history of script submission #24220 for ' Search on Postgres with pg_pinecone (pg_pinecone)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import { Client } from "pg";
    
    type Postgresql = {
      host: string;
      port: number;
      user: string;
      dbname: string;
      sslmode: string;
      password: string;
    };
    
    // Point the PostgreSQL resource at a database that has the vector and
    // pg_pinecone extensions. The database user needs to be allowed to create
    // them. This script replaces the table windmill_pg_pinecone_docs, builds a
    // native index, and returns the two closest rows. The query is the same SQL
    // as pgvector, and the rows stay in Postgres.
    export async function main(db: Postgresql) {
      const client = new Client({
        host: db.host,
        port: db.port,
        user: db.user,
        password: db.password,
        database: db.dbname,
        ssl: sslOption(db.sslmode),
      });
      await client.connect();
      try {
        await client.query("CREATE EXTENSION IF NOT EXISTS vector");
        await client.query("CREATE EXTENSION IF NOT EXISTS pg_pinecone");
        await client.query("DROP TABLE IF EXISTS windmill_pg_pinecone_docs");
        await client.query(`
          CREATE TABLE windmill_pg_pinecone_docs (
            id bigint PRIMARY KEY,
            body text,
            embedding vector(3)
          )
        `);
        await client.query(`
          INSERT INTO windmill_pg_pinecone_docs (id, body, embedding) VALUES
            (1, 'The Eiffel Tower was completed in 1889.', '[0.1, 0.1, 0.9]'),
            (2, 'Photosynthesis converts sunlight into glucose.', '[0.05, 0.9, 0.1]'),
            (4, 'Espresso is brewed by forcing hot water through ground coffee.', '[0.95, 0.05, 0.05]'),
            (7, 'A croissant is a flaky pastry made from buttered dough.', '[0.95, 0.05, 0.1]')
        `);
        await client.query(
          "SELECT pinecone.create_index('windmill_pg_pinecone_docs', 'embedding', engine => 'native')",
        );
        await client.query("SET enable_seqscan = off");
        const { rows } = await client.query(
          "SELECT id::int AS id, body FROM windmill_pg_pinecone_docs ORDER BY embedding <=> '[1, 0, 0]' LIMIT 2",
        );
        return rows;
      } finally {
        await client.end();
      }
    }
    
    function sslOption(sslmode: string | undefined) {
      const mode = (sslmode ?? "").toLowerCase();
      if (mode === "" || mode === "disable") return false;
      if (mode === "verify-ca" || mode === "verify-full") {
        return { rejectUnauthorized: true };
      }
      return { rejectUnauthorized: false };
    }

    Submitted by anthony761 14 days ago