1 | import { PineconeClient } from "@pinecone-database/[email protected]"; |
2 | import { QueryOperationRequest } from "@pinecone-database/[email protected]/dist/pinecone-generated-ts-fetch/index.js"; |
3 |
|
4 | |
5 | * |
6 | * @param topK The number of results to return for each query. |
7 | * |
8 | * @param vector _(Conditionally Optional)_ The query vector. This should be the same length as the dimension |
9 | * of the index being queried. |
10 | * **Each query request can contain only one of the parameters "id" or "vector".** |
11 | * |
12 | * @param id _(Conditionally Optional)_ The unique ID of the vector to be used as a query vector. |
13 | * **Each query request can contain only one of the parameters "vector" or "id".** |
14 | * |
15 | * @param namespace _(Optional)_ The namespace to query. |
16 | * |
17 | * @param includeValues _(Optional)_ Indicates whether vector values are included in the response. |
18 | * Defaults to `false`. |
19 | * |
20 | * @param includeMetadata _(Optional)_ Indicates whether metadata is included in the response as well as the ids. |
21 | * Defaults to `false`. |
22 | * |
23 | * @param filter _(Optional)_ The filter to apply. You can use vector metadata to limit your search. |
24 | * See https://www.pinecone.io/docs/metadata-filtering/. |
25 | */ |
26 | type Pinecone = { |
27 | apiKey: string; |
28 | environment: string; |
29 | }; |
30 | export async function main( |
31 | auth: Pinecone, |
32 | index_name: string, |
33 | topK: number, |
34 | vector?: number[], |
35 | id?: string, |
36 | namespace?: string, |
37 | include_values?: boolean, |
38 | include_metadata?: boolean, |
39 | filter?: object, |
40 | raw?: boolean, |
41 | ) { |
42 | const client = new PineconeClient(); |
43 | await client.init(auth); |
44 | const index = client.Index(index_name); |
45 |
|
46 | const queryRequest: QueryOperationRequest = removeObjectEmptyFields({ |
47 | topK, |
48 | vector, |
49 | id, |
50 | namespace, |
51 | includeValues: include_values, |
52 | includeMetadata: include_metadata, |
53 | filter, |
54 | }); |
55 | return await index[raw ? "queryRaw" : "query"]({ queryRequest }); |
56 | } |
57 |
|
58 | function removeObjectEmptyFields( |
59 | object?: Record<string, any>, |
60 | removeEmptyArraysAndObjects = true, |
61 | createNewObject = true, |
62 | ) { |
63 | if (!object || typeof object !== "object") return {} |
64 | const obj = createNewObject ? { ...object } : object |
65 | const emptyValues = [undefined, null, ""] |
66 | for (const key in obj) { |
67 | const value = obj[key] |
68 | if (emptyValues.includes(value)) { |
69 | delete obj[key] |
70 | } else if (typeof value === "object") { |
71 | if (Object.keys(value).length) { |
72 | obj[key] = removeObjectEmptyFields(value, removeEmptyArraysAndObjects, false) |
73 | } |
74 | if (!Object.keys(value).length && removeEmptyArraysAndObjects) { |
75 | delete obj[key] |
76 | } |
77 | } |
78 | } |
79 | return obj |
80 | } |
81 |
|