Troubleshooting TypeScript Error with Typesense
TLDR GM experienced an error with Typesense in TypeScript, requiring help to correct the issues. Jason helped propose solutions and adjustments to the code. Ultimately, they were able to resolve the errors and successfully implement a search function.
3
1
Oct 24, 2022 (14 months ago)
GM
05:40 PMJason
05:41 PMIn your code snippet, that last two lines should be:
const results = await searchClient.collections('companies').documents().search(searchParameters);
return data;
GM
05:51 PMGM
05:51 PM"error": "TypeError",
"message": "searchClient.collections is not a function"
}
GM
05:51 PMGM
05:52 PMconst results = await searchClient.collections('companies').documents('USA').retrieve();
return results;
Jason
05:52 PMsearchClient
?GM
05:53 PMserver: {
apiKey: '2kxogtNROPlHjEBSy8pbd9f7Zxw3HcAQ', // Be sure to use an API key that only allows search operations
nodes: [
{
host: '1bf8hqds9032wpntp-1.a1.typesense.net',
path: '', // Optional. Example: If you have your typesense mounted in localhost:8108/typesense, path should be equal to '/typesense'
port: 443,
protocol: 'https',
},
],
cacheSearchResultsForSeconds: 2 * 60, // Cache search results from server. Defaults to 2 minutes. Set to 0 to disable caching.
},
// The following parameters are directly passed to Typesense's search API endpoint.
// So you can pass any parameters supported by the search endpoint below.
// query_by is required.
additionalSearchParameters: {
query_by: 'country',
},
});
Jason
05:55 PMTypesenseInstantSearchAdapter
which you’d only use if you’re using Instantsearch.js which is a UI library.In your case, in your code snippet you’re using typesense-js directly. So you want to instantiate the client like this:
https://typesense.org/docs/0.23.1/api/authentication.html
Jason
05:55 PMGM
06:10 PMGM
06:10 PM60 responseType = null
node_modules/typesense/src/Typesense/ApiCall.ts:95:7 - error TS2322: Type 'null' is not assignable to type 'ResponseType'.
95 responseType = null
node_modules/typesense/src/Typesense/ApiCall.ts:207:86 - error TS2571: Object is of type 'unknown'.
207
Request #${requestNumber}: Request to Node ${node.index} failed due to "${error.code} ${error.message}${
~~~~~
node_modules/typesense/src/Typesense/ApiCall.ts:207:100 - error TS2571: Object is of type 'unknown'.
207
Request #${requestNumber}: Request to Node ${node.index} failed due to "${error.code} ${error.message}${node_modules/typesense/src/Typesense/ApiCall.ts:208:13 - error TS2571: Object is of type 'unknown'.
208 error.response == null ? '' : ' - ' + JSON.stringify(error.response?.data)
node_modules/typesense/src/Typesense/ApiCall.ts:208:66 - error TS2571: Object is of type 'unknown'.
208 error.response == null ? '' : ' - ' + JSON.stringify(error.response?.data)
node_modules/typesense/src/Typesense/ApiCall.ts:263:96 - error TS2454: Variable 'candidateNode' is used before being assigned.
263
Request #${requestNumber}: No healthy nodes were found. Returning the next node, Node ${candidateNode.index}
node_modules/typesense/src/Typesense/ApiCall.ts:265:12 - error TS2454: Variable 'candidateNode' is used before being assigned.
265 return candidateNode
node_modules/typesense/src/Typesense/ApiCall.ts:268:25 - error TS7006: Parameter 'node' implicitly has an 'any' type.
268 nodeDueForHealthcheck(node, requestNumber: number = 0): boolean {
node_modules/typesense/src/Typesense/ApiCall.ts:290:22 - error TS7006: Parameter 'node' implicitly has an 'any' type.
290 setNodeHealthcheck(node, isHealthy): void {
node_modules/typesense/src/Typesense/ApiCall.ts:290:28 - error TS7006: Parameter 'isHealthy' implicitly has an 'any' type.
290 setNodeHealthcheck(node, isHealthy): void {
node_modules/typesense/src/Typesense/ApiCall.ts:295:28 - error TS7006: Parameter 'node' implicitly has an 'any' type.
295 uriFor(endpoint: string, node): string {
node_modules/typesense/src/Typesense/ApiCall.ts:305:7 - error TS7053: Element implicitly has an 'any' type because expression of type '"X-TYPESENSE-API-KEY"' can't be used to index type '{}'.
Property 'X-TYPESENSE-API-KEY' does not exist on type '{}'.
305 defaultHeaders[APIKEYHEADERNAME] = this.apiKey
node_modules/typesense/src/Typesense/ApiCall.ts:307:5 - error TS7053: Element implicitly has an 'any' type because expression of type '"Content-Type"' can't be used to index type '{}'.
Property 'Content-Type' does not exist on type '{}'.
307 defaultHeaders['Content-Type'] = 'application/json'
node_modules/typesense/src/Typesense/ApiCall.ts:311:15 - error TS7006: Parameter 'seconds' implicitly has an 'any' type.
311 async timer(seconds): Promise<void> {
node_modules/typesense/src/Typesense/Configuration.ts:72:5 - error TS2322: Type 'NodeConfiguration | null' is not assignable to type 'NodeConfiguration'.
Type 'null' is not assignable to type 'NodeConfiguration'.
72 this.nearestNode = options.nearestNode || null
node_modules/typesense/src/Typesense/Configuration.ts:82:5 - error TS2322: Type 'boolean | undefined' is not assignable to type 'boolean'.
Type 'undefined' is not assignable to type 'boolean'.
82 this.sendApiKeyAsQueryParam = options.sendApiKeyAsQueryParam // We will set a default for this in Client and SearchClient
node_modules/typesense/src/Typesense/Configuration.ts:91:5 - error TS2322: Type 'Record<string, string> | undefined' is not assignable to type 'Record<string, string>'.
Type 'undefined' is not assignable to type 'Record<string, string>'.
91 this.additionalHeaders = options.additionalHeaders
node_modules/typesense/src/Typesense/Configuration.ts:166:24 - error TS7006: Parameter 'array' implicitly has an 'any' type.
166 private shuffleArray(array) {
node_modules/typesense/src/Typesense/Documents.ts:201:35 - error TS2359: The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.
201 if (RangeError instanceof error && error?.includes('Too many properties to enumerate')) {
node_modules/typesense/src/Typesense/Documents.ts:201:44 - error TS2571: Object is of type 'unknown'.
201 if (RangeError instanceof error && error?.includes('Too many properties to enumerate')) {
node_modules/typesense/src/Typesense/Documents.ts:210:25 - error TS2345: Argument of type 'unknown' is not assignable to parameter of type 'string | undefined'.
210 throw new Error(error)
node_modules/typesense/src/Typesense/Errors/ImportError.ts:6:15 - error TS7006: Parameter 'message' implicitly has an 'any' type.
6 constructor(message, importResults) {
node_modules/typesense/src/Typesense/Errors/ImportError.ts:6:24 - error TS7006: Parameter 'importResults' implicitly has an 'any' type.
6 constructor(message, importResults) {
node_modules/typesense/src/Typesense/RequestWithCache.ts:22:7 - error TS2322: Type 'unknown' is not assignable to type 'T'.
'unknown' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'unknown'.
22 return requestFunction.call(requestContext, ...requestFunctionArguments)
node_modules/typesense/src/Typesense/SearchOnlyDocuments.ts:22:7 - error TS2322: Type 'null' is not assignable to type 'AbortSignal'.
22 abortSignal = null
node_modules/typesense/src/Typesense/SearchOnlyDocuments.ts:27:7 - error TS7053: Element implicitly has an 'any' type because expression of type '"use_cache"' can't be used to index type '{}'.
Property 'use_cache' does not exist on type '{}'.
27 additionalQueryParams['use_cache'] = true
Found 27 errors in 6 files.
Errors Files
15 node_modules/typesense/src/Typesense/ApiCall.ts:60
4 node_modules/typesense/src/Typesense/Configuration.ts:72
3 node_modules/typesense/src/Typesense/Documents.ts:201
2 node_modules/typesense/src/Typesense/Errors/ImportError.ts:6
1 node_modules/typesense/src/Typesense/RequestWithCache.ts:22
2 node_modules/typesense/src/Typesense/SearchOnlyDocuments.ts:22
GM
06:10 PMGM
06:11 PMGM
06:12 PMimport { ExceptionsHandler } from '../exceptionHandler/exceptionHandler';
import { DataWrapper, ErrorAzureResponse } from '../response/response';
import { Client } from 'typesense';
import Configuration, { NodeConfiguration, ConfigurationOptions } from 'typesense/src/Typesense/Configuration';
import { CollectionCreateSchema } from 'typesense/src/Typesense/Collections';
const typesense = new Client({
nodes: [
{
host: '1bf8hqds9032wpntp-1.a1.typesense.net',
port: 443,
protocol: 'http',
} as NodeConfiguration,
],
apiKey: '2kxogtNROPlHjEBSy8pbd9f7Zxw3HcAQ',
numRetries: 3, // A total of 4 tries (1 original try + 3 retries)
connectionTimeoutSeconds: 120, // Set a longer timeout for large imports
logLevel: 'debug',
} as ConfigurationOptions);
const SearchExceptionHandler = (e: any) => {
throw new ErrorAzureResponse({ error: 'INTERNAL_SERVER_ERROR', message: e });
};
export class Search {
async getTypesearch(latitude: number, longitude: number) {
const searchParameters = {
q: 'USA',
query_by: 'country',
group_by: 'country',
group_limit: '1',
};
const results = await typesense.collections('companies').documents('USA').retrieve();
return results;
}
}
GM
06:18 PMGM
06:18 PMJason
06:19 PMimport Configuration, { NodeConfiguration, ConfigurationOptions } from 'typesense/lib/Typesense/Configuration';
import { CollectionCreateSchema } from 'typesense/lib/Typesense/Collections';
Jason
06:20 PMGM
06:23 PMGM
06:32 PM1
1
GM
06:33 PMJason
06:33 PMGM
06:34 PMGM
06:34 PMGM
06:34 PMGM
06:35 PMGM
06:37 PMq: 'USA',
query_by: 'country',
group_by: 'country',
group_limit: '1',
};
const results = await typesense.collections('companies').documents().search(searchParameters);
return results;
Jason
06:37 PMexport class Search {
async getTypesearch(latitude: number, longitude: number, country: string) {
const searchParameters = {
q: country, // <== change this to a parameter
query_by: 'country',
group_by: 'country',
group_limit: '1',
};
const results = await typesense.collections('companies').documents().search(searchParameters); // <== change this to search instead of retrieve
return results;
}
}
GM
06:44 PMGM
06:44 PMGM
06:45 PMconst searchParameters = {
q: country,
query_by: 'country',
group_by: 'country',
};
const results = await typesense.collections('companies').documents().search(searchParameters);
return results;
}
Jason
06:45 PM1
GM
06:46 PMGM
06:46 PMJason
06:46 PMfilter_by
search parameter for this. It’s documented under this table: https://typesense.org/docs/0.23.1/api/search.html#query-parameters1
GM
06:50 PMGM
06:51 PMTypesense
Indexed 3015 threads (79% resolved)
Similar Threads
Debugging Search Issue with Typesense Server Caching
Jameshwart reported experiencing caching issues with typesense server, despite the server's default setting of not caching. Through troubleshooting steps with Kishore Nallan, they were able to confirm an issue with the Typesense Javascript client and resolved it by adding `cacheSearchResultsForSeconds: 0` after `apiKey` in the initialisation. Laura also participated in discussion, learning about server and client level caching.
Troubleshooting Issues with DocSearch Hits and Scraper Configuration
Rubai encountered issues with search result priorities and ellipsis. Jason helped debug the issue and suggested using different versions of typesense-docsearch.js, updating initialization parameters, and running the scraper on a Linux-based environment. The issues related to hits structure and scraper configuration were resolved.
Typescript Support and Import Issues with Typesense
Ahmad faced trouble with Typesense support for Typescript. Jason assisted by suggesting checks and solutions. Phil suggested modifying the import statement. Ultimately, the issue was resolved with a change from Jason in version `v1.1.2`.
Typesense Error in Unit Testing for Python
Mehdi was encountering errors while running unit tests for Typesense functionalities in Python. Through discussion with Kishore Nallan, they recognized resource constraints might be causing the issue during JSONL file import. As suggested by Kishore Nallan, adding a short sleep after the import resolved the problem.
Querying with Not-in in Typesense
Masahiro inquired about using not-in queries in Typesense. Kishore Nallan explained how to conduct such queries by using the "-" operator in the query string, and assisted Masahiro with issues stemming from a high number of exclusion tokens. The problem was eventually resolved by switching to the `multi_search` endpoint.