diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..f0ccbc9 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[alias] +xtask = "run --package xtask --" \ No newline at end of file diff --git a/.gitignore b/.gitignore index e551aa3..8d7229e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /target Cargo.lock .env +/typesense-data \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index dd9279f..322f339 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,9 @@ + [workspace] members = [ "typesense", "typesense_derive", - "typesense_codegen" + "typesense_codegen", + "xtask", ] + diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..c77de65 --- /dev/null +++ b/compose.yml @@ -0,0 +1,9 @@ +services: + typesense: + image: typesense/typesense:29.0 + restart: on-failure + ports: + - '8108:8108' + volumes: + - ./typesense-data:/data + command: '--data-dir /data --api-key=xyz --enable-cors' diff --git a/openapi.yml b/openapi.yml index 3bac4f6..3c23cba 100644 --- a/openapi.yml +++ b/openapi.yml @@ -2,7 +2,7 @@ openapi: 3.0.3 info: title: Typesense API description: "An open source search engine for building delightful search experiences." - version: 0.25.0 + version: '28.0' externalDocs: description: Find out more about Typsesense url: https://typesense.org @@ -19,8 +19,8 @@ tags: externalDocs: description: Find out more url: https://typesense.org/api/#index-document - - name: promote - description: Promote certain documents over others + - name: curation + description: Hand-curate search results based on conditional business rules externalDocs: description: Find out more url: https://typesense.org/docs/0.23.0/api/#curation @@ -28,7 +28,7 @@ tags: description: Typesense can aggregate search queries for both analytics purposes and for query suggestions. externalDocs: description: Find out more - url: https://typesense.org/docs/0.25.0/api/analytics-query-suggestions.html + url: https://typesense.org/docs/28.0/api/analytics-query-suggestions.html - name: keys description: Manage API Keys with fine-grain access control externalDocs: @@ -40,8 +40,37 @@ tags: description: Manage Typesense cluster externalDocs: description: Find out more - url: https://typesense.org/docs/0.23.0/api/#cluster-operations - + url: https://typesense.org/docs/28.0/api/cluster-operations.html + - name: stopwords + description: Manage stopwords sets + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stopwords.html + - name: presets + description: Store and reference search parameters + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/search.html#presets + - name: conversations + description: Conversational Search (RAG) + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/conversational-search-rag.html + - name: synonyms + description: Manage synonyms + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/synonyms.html + - name: stemming + description: Manage stemming dictionaries + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stemming.html + - name: nl_search_models + description: Manage NL search models + externalDocs: + description: Find out more + url: https://typesense.org/docs/29.0/api/natural-language-search.html paths: /collections: get: @@ -54,7 +83,7 @@ paths: first. operationId: getCollections responses: - 200: + '200': description: List of all collections content: application/json: @@ -79,19 +108,19 @@ paths: $ref: "#/components/schemas/CollectionSchema" required: true responses: - 201: + '201': description: Collection successfully created content: application/json: schema: $ref: "#/components/schemas/CollectionResponse" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 409: + '409': description: Collection already exists content: application/json: @@ -112,13 +141,13 @@ paths: schema: type: string responses: - 200: + '200': description: Collection fetched content: application/json: schema: $ref: "#/components/schemas/CollectionResponse" - 404: + '404': description: Collection not found content: application/json: @@ -146,19 +175,19 @@ paths: $ref: "#/components/schemas/CollectionUpdateSchema" required: true responses: - 200: + '200': description: The updated partial collection schema content: application/json: schema: $ref: "#/components/schemas/CollectionUpdateSchema" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: The collection was not found content: application/json: @@ -180,13 +209,13 @@ paths: schema: type: string responses: - 200: + '200': description: Collection deleted content: application/json: schema: $ref: "#/components/schemas/CollectionResponse" - 404: + '404': description: Collection not found content: application/json: @@ -214,8 +243,12 @@ paths: schema: type: string example: upsert - enum: - - upsert + $ref: "#/components/schemas/IndexAction" + - name: dirty_values + in: query + description: Dealing with Dirty Data + schema: + $ref: "#/components/schemas/DirtyValues" requestBody: description: The document object to be indexed content: @@ -226,14 +259,14 @@ paths: x-go-type: "interface{}" required: true responses: - 201: + '201': description: Document successfully created/indexed content: application/json: schema: type: object description: Can be any key-value pair - 404: + '404': description: Collection not found content: application/json: @@ -320,6 +353,8 @@ paths: in: query schema: type: object + required: + - filter_by properties: filter_by: type: string @@ -330,8 +365,13 @@ paths: at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. type: integer + ignore_not_found: + type: boolean + truncate: + description: When true, removes all documents from the collection while preserving the collection and its schema. + type: boolean responses: - 200: + '200': description: Documents successfully deleted content: application/json: @@ -342,7 +382,7 @@ paths: properties: num_deleted: type: integer - 404: + '404': description: Collection not found content: application/json: @@ -368,19 +408,19 @@ paths: schema: $ref: "#/components/schemas/SearchParameters" responses: - 200: + '200': description: Search results content: application/json: schema: $ref: "#/components/schemas/SearchResult" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: The collection or field was not found content: application/json: @@ -390,7 +430,7 @@ paths: get: tags: - documents - - promote + - curation summary: List all collection overrides operationId: getSearchOverrides parameters: @@ -401,7 +441,7 @@ paths: schema: type: string responses: - 200: + '200': description: List of all search overrides content: application/json: @@ -429,7 +469,7 @@ paths: schema: type: string responses: - 200: + '200': description: Search override fetched content: application/json: @@ -438,7 +478,7 @@ paths: put: tags: - documents - - promote + - curation summary: Create or update an override to promote certain documents over others description: Create or update an override to promote certain documents over others. @@ -465,13 +505,13 @@ paths: $ref: "#/components/schemas/SearchOverrideSchema" required: true responses: - 200: + '200': description: Created/updated search override content: application/json: schema: $ref: "#/components/schemas/SearchOverride" - 404: + '404': description: Search override not found content: application/json: @@ -480,7 +520,7 @@ paths: delete: tags: - documents - - promote + - curation summary: Delete an override associated with a collection operationId: deleteSearchOverride parameters: @@ -497,13 +537,13 @@ paths: schema: type: string responses: - 200: + '200': description: The ID of the deleted search override content: application/json: schema: - $ref: "#/components/schemas/SearchOverride" - 404: + $ref: "#/components/schemas/SearchOverrideDeleteResponse" + '404': description: Search override not found content: application/json: @@ -512,7 +552,7 @@ paths: /collections/{collectionName}/synonyms: get: tags: - - documents + - synonyms summary: List all collection synonyms operationId: getSearchSynonyms parameters: @@ -523,13 +563,13 @@ paths: schema: type: string responses: - 200: + '200': description: List of all search synonyms content: application/json: schema: $ref: "#/components/schemas/SearchSynonymsResponse" - 404: + '404': description: Search synonyms was not found content: application/json: @@ -538,7 +578,7 @@ paths: /collections/{collectionName}/synonyms/{synonymId}: get: tags: - - documents + - synonyms summary: Retrieve a single search synonym description: Retrieve the details of a search synonym, given its id. operationId: getSearchSynonym @@ -556,13 +596,13 @@ paths: schema: type: string responses: - 200: + '200': description: Search synonym fetched content: application/json: schema: $ref: "#/components/schemas/SearchSynonym" - 404: + '404': description: Search synonym was not found content: application/json: @@ -570,7 +610,7 @@ paths: $ref: "#/components/schemas/ApiResponse" put: tags: - - documents + - synonyms summary: Create or update a synonym description: Create or update a synonym to define search terms that should be considered equivalent. operationId: upsertSearchSynonym @@ -595,13 +635,13 @@ paths: $ref: "#/components/schemas/SearchSynonymSchema" required: true responses: - 200: + '200': description: Created/updated search synonym content: application/json: schema: $ref: "#/components/schemas/SearchSynonym" - 404: + '404': description: Search synonym was not found content: application/json: @@ -609,7 +649,7 @@ paths: $ref: "#/components/schemas/ApiResponse" delete: tags: - - documents + - synonyms summary: Delete a synonym associated with a collection operationId: deleteSearchSynonym parameters: @@ -626,13 +666,13 @@ paths: schema: type: string responses: - 200: + '200': description: The ID of the deleted search synonym content: application/json: schema: - $ref: "#/components/schemas/SearchSynonym" - 404: + $ref: "#/components/schemas/SearchSynonymDeleteResponse" + '404': description: Search synonym not found content: application/json: @@ -657,9 +697,6 @@ paths: in: query schema: type: object - required: - - include_fields - - exclude_fields properties: filter_by: description: @@ -674,7 +711,7 @@ paths: type: string responses: - 200: + '200': description: Exports all the documents in a given collection. content: application/octet-stream: @@ -684,7 +721,7 @@ paths: {"id": "124", "company_name": "Stark Industries", "num_employees": 5215, "country": "US"} {"id": "125", "company_name": "Future Technology", "num_employees": 1232,"country": "UK"} {"id": "126", "company_name": "Random Corp.", "num_employees": 531,"country": "AU"} - 404: + '404': description: The collection was not found content: application/json: @@ -707,24 +744,28 @@ paths: required: true schema: type: string + # Do not change the index position of this param - name: importDocumentsParameters in: query schema: type: object properties: - action: - type: string batch_size: type: integer - dirty_values: - type: string - enum: - - coerce_or_reject - - coerce_or_drop - - drop - - reject + return_id: + type: boolean + description: + Returning the id of the imported documents. If you want the + import response to return the ingested document's id in the + response, you can use the return_id parameter. remote_embedding_batch_size: type: integer + return_doc: + type: boolean + action: + $ref: "#/components/schemas/IndexAction" + dirty_values: + $ref: "#/components/schemas/DirtyValues" requestBody: description: The json array of documents or the JSONL file to import content: @@ -734,7 +775,7 @@ paths: description: The JSONL file to import required: true responses: - 200: + '200': description: Result of the import operation. Each line of the response indicates the result of each document present in the request body (in the same order). If the import @@ -748,13 +789,13 @@ paths: example: | {"success": true} {"success": false, "error": "Bad JSON.", "document": "[bad doc"} - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: The collection was not found content: application/json: @@ -781,14 +822,14 @@ paths: schema: type: string responses: - 200: + '200': description: The document referenced by the ID content: application/json: schema: type: object description: Can be any key-value pair - 404: + '404': description: The document or collection was not found content: application/json: @@ -815,6 +856,11 @@ paths: required: true schema: type: string + - name: dirty_values + in: query + description: Dealing with Dirty Data + schema: + $ref: "#/components/schemas/DirtyValues" requestBody: description: The document object with fields to be updated content: @@ -825,14 +871,14 @@ paths: x-go-type: "interface{}" required: true responses: - 200: + '200': description: The document referenced by the ID was updated content: application/json: schema: type: object description: Can be any key-value pair - 404: + '404': description: The document or collection was not found content: application/json: @@ -858,19 +904,127 @@ paths: schema: type: string responses: - 200: + '200': description: The document referenced by the ID was deleted content: application/json: schema: type: object description: Can be any key-value pair - 404: + '404': description: The document or collection was not found content: application/json: schema: $ref: "#/components/schemas/ApiResponse" + /conversations/models: + get: + description: Retrieve all conversation models + operationId: retrieveAllConversationModels + responses: + '200': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/ConversationModelSchema' + type: array + x-go-type: '[]*ConversationModelSchema' + description: List of all conversation models + summary: List all conversation models + tags: + - conversations + post: + description: Create a Conversation Model + operationId: createConversationModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelCreateSchema' + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: Created Conversation Model + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + tags: + - conversations + /conversations/models/{modelId}: + get: + description: Retrieve a conversation model + operationId: retrieveConversationModel + parameters: + - name: modelId + in: path + description: The id of the conversation model to retrieve + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: A conversation model + summary: Retrieve a conversation model + tags: + - conversations + put: + description: Update a conversation model + operationId: updateConversationModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelUpdateSchema' + required: true + parameters: + - name: modelId + in: path + description: The id of the conversation model to update + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: The conversation model was successfully updated + summary: Update a conversation model + tags: + - conversations + delete: + description: Delete a conversation model + operationId: deleteConversationModel + parameters: + - name: modelId + in: path + description: The id of the conversation model to delete + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: The conversation model was successfully deleted + summary: Delete a conversation model + tags: + - conversations /keys: get: tags: @@ -878,7 +1032,7 @@ paths: summary: Retrieve (metadata about) all keys. operationId: getKeys responses: - 200: + '200': description: List of all keys content: application/json: @@ -901,19 +1055,19 @@ paths: schema: $ref: "#/components/schemas/ApiKeySchema" responses: - 201: + '201': description: Created API key content: application/json: schema: $ref: "#/components/schemas/ApiKey" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 409: + '409': description: API key generation conflict content: application/json: @@ -938,13 +1092,13 @@ paths: type: integer format: int64 responses: - 200: + '200': description: The key referenced by the ID content: application/json: schema: $ref: "#/components/schemas/ApiKey" - 404: + '404': description: The key was not found content: application/json: @@ -964,19 +1118,19 @@ paths: type: integer format: int64 responses: - 200: + '200': description: The key referenced by the ID content: application/json: schema: - $ref: "#/components/schemas/ApiKey" - 400: + $ref: "#/components/schemas/ApiKeyDeleteResponse" + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: Key not found content: application/json: @@ -990,7 +1144,7 @@ paths: description: List all aliases and the corresponding collections that they map to. operationId: getAliases responses: - 200: + '200': description: List of all collection aliases content: application/json: @@ -1022,19 +1176,19 @@ paths: schema: $ref: "#/components/schemas/CollectionAliasSchema" responses: - 200: + '200': description: The collection alias was created/updated content: application/json: schema: $ref: "#/components/schemas/CollectionAlias" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: Alias not found content: application/json: @@ -1054,13 +1208,13 @@ paths: schema: type: string responses: - 200: + '200': description: Collection alias fetched content: application/json: schema: $ref: "#/components/schemas/CollectionAlias" - 404: + '404': description: The alias was not found content: application/json: @@ -1079,13 +1233,13 @@ paths: schema: type: string responses: - 200: + '200': description: Collection alias was deleted content: application/json: schema: $ref: "#/components/schemas/CollectionAlias" - 404: + '404': description: Alias not found content: application/json: @@ -1099,7 +1253,7 @@ paths: description: Print debugging information operationId: debug responses: - 200: + '200': description: Debugging information content: application/json: @@ -1116,12 +1270,28 @@ paths: description: Checks if Typesense server is ready to accept requests. operationId: health responses: - 200: + '200': description: Search service is ready for requests. content: application/json: schema: $ref: "#/components/schemas/HealthStatus" + /operations/schema_changes: + get: + tags: + - operations + summary: Get the status of in-progress schema change operations + description: Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. + operationId: getSchemaChanges + responses: + '200': + description: List of schema changes in progress + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/SchemaChangeStatus" /operations/snapshot: post: tags: @@ -1140,7 +1310,7 @@ paths: schema: type: string responses: - 201: + '201': description: Snapshot is created. content: application/json: @@ -1157,7 +1327,7 @@ paths: once this command succeeds. operationId: vote responses: - 200: + '200': description: Re-election is performed. content: application/json: @@ -1184,18 +1354,45 @@ paths: schema: $ref: "#/components/schemas/MultiSearchSearchesParameter" responses: - 200: + '200': description: Search results content: application/json: schema: $ref: "#/components/schemas/MultiSearchResult" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" + /analytics/events: + post: + tags: + - analytics + summary: Create an analytics event + description: Sending events for analytics e.g rank search results based on popularity. + operationId: createAnalyticsEvent + requestBody: + description: The Analytics event to be created + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventCreateSchema' + required: true + responses: + '201': + description: Analytics event successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventCreateResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' /analytics/rules: post: tags: @@ -1212,13 +1409,13 @@ paths: $ref: "#/components/schemas/AnalyticsRuleSchema" required: true responses: - 201: + '201': description: Analytics rule successfully created content: application/json: schema: $ref: "#/components/schemas/AnalyticsRuleSchema" - 400: + '400': description: Bad request, see error message for details content: application/json: @@ -1232,13 +1429,47 @@ paths: Retrieve the details of all analytics rules operationId: retrieveAnalyticsRules responses: - 200: + '200': description: Analytics rules fetched content: application/json: schema: $ref: "#/components/schemas/AnalyticsRulesRetrieveSchema" /analytics/rules/{ruleName}: + put: + tags: + - analytics + summary: Upserts an analytics rule + description: + Upserts an analytics rule with the given name. + operationId: upsertAnalyticsRule + parameters: + - in: path + name: ruleName + description: The name of the analytics rule to upsert + schema: + type: string + required: true + requestBody: + description: The Analytics rule to be upserted + content: + application/json: + schema: + $ref: "#/components/schemas/AnalyticsRuleUpsertSchema" + required: true + responses: + '200': + description: Analytics rule successfully upserted + content: + application/json: + schema: + $ref: "#/components/schemas/AnalyticsRuleSchema" + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" get: tags: - analytics @@ -1254,13 +1485,13 @@ paths: type: string required: true responses: - 200: + '200': description: Analytics rule fetched content: application/json: schema: $ref: "#/components/schemas/AnalyticsRuleSchema" - 404: + '404': description: Analytics rule not found content: application/json: @@ -1281,47 +1512,520 @@ paths: type: string required: true responses: - 200: + '200': description: Analytics rule deleted content: application/json: schema: - $ref: "#/components/schemas/AnalyticsRuleSchema" - 404: + $ref: "#/components/schemas/AnalyticsRuleDeleteResponse" + '404': description: Analytics rule not found content: application/json: schema: $ref: "#/components/schemas/ApiResponse" -components: - schemas: - CollectionSchema: - required: - - name - - fields - type: object - properties: - name: - type: string - description: Name of the collection - example: companies - fields: - type: array - description: A list of fields for querying, filtering and faceting - example: - - name: num_employees - type: int32 - facet: false - - name: company_name - type: string - facet: false - - name: country - type: string - facet: true - items: - $ref: "#/components/schemas/Field" - default_sorting_field: - type: string + /metrics.json: + get: + tags: + - operations + summary: Get current RAM, CPU, Disk & Network usage metrics. + description: + Retrieve the metrics. + operationId: retrieveMetrics + responses: + '200': + description: Metrics fetched. + content: + application/json: + schema: + type: object + /stats.json: + get: + tags: + - operations + summary: Get stats about API endpoints. + description: + Retrieve the stats about API endpoints. + operationId: retrieveAPIStats + responses: + '200': + description: Stats fetched. + content: + application/json: + schema: + $ref: "#/components/schemas/APIStatsResponse" + /stopwords: + get: + tags: + - stopwords + summary: Retrieves all stopwords sets. + description: + Retrieve the details of all stopwords sets + operationId: retrieveStopwordsSets + responses: + '200': + description: Stopwords sets fetched. + content: + application/json: + schema: + $ref: "#/components/schemas/StopwordsSetsRetrieveAllSchema" + /stopwords/{setId}: + put: + tags: + - stopwords + summary: Upserts a stopwords set. + description: + When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. + operationId: upsertStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to upsert. + schema: + type: string + required: true + example: countries + requestBody: + description: The stopwords set to upsert. + content: + application/json: + schema: + $ref: "#/components/schemas/StopwordsSetUpsertSchema" + required: true + responses: + '200': + description: Stopwords set successfully upserted. + content: + application/json: + schema: + $ref: "#/components/schemas/StopwordsSetSchema" + '400': + description: Bad request, see error message for details. + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + get: + tags: + - stopwords + summary: Retrieves a stopwords set. + description: + Retrieve the details of a stopwords set, given it's name. + operationId: retrieveStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to retrieve. + schema: + type: string + required: true + example: countries + responses: + '200': + description: Stopwords set fetched. + content: + application/json: + schema: + $ref: "#/components/schemas/StopwordsSetRetrieveSchema" + '404': + description: Stopwords set not found. + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + delete: + tags: + - stopwords + summary: Delete a stopwords set. + description: + Permanently deletes a stopwords set, given it's name. + operationId: deleteStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to delete. + schema: + type: string + required: true + example: countries + responses: + '200': + description: Stopwords set rule deleted. + content: + application/json: + schema: + type: object + properties: + id: + type: string + required: + - id + example: | + {"id": "countries"} + '404': + description: Stopwords set not found. + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /presets: + get: + tags: + - presets + summary: Retrieves all presets. + description: Retrieve the details of all presets + operationId: retrieveAllPresets + responses: + '200': + description: Presets fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetsRetrieveSchema' + /presets/{presetId}: + get: + tags: + - presets + summary: Retrieves a preset. + description: Retrieve the details of a preset, given it's name. + operationId: retrievePreset + parameters: + - in: path + name: presetId + description: The ID of the preset to retrieve. + schema: + type: string + required: true + example: listing_view + responses: + '200': + description: Preset fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetSchema' + '404': + description: Preset not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + put: + tags: + - presets + summary: Upserts a preset. + description: Create or update an existing preset. + operationId: upsertPreset + parameters: + - in: path + name: presetId + description: The name of the preset set to upsert. + schema: + type: string + required: true + example: listing_view + requestBody: + description: The stopwords set to upsert. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetUpsertSchema' + required: true + responses: + '200': + description: Preset successfully upserted. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - presets + summary: Delete a preset. + description: Permanently deletes a preset, given it's name. + operationId: deletePreset + parameters: + - in: path + name: presetId + description: The ID of the preset to delete. + schema: + type: string + required: true + example: listing_view + responses: + '200': + description: Preset deleted. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetDeleteSchema' + '404': + description: Preset not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /stemming/dictionaries: + get: + tags: + - stemming + summary: List all stemming dictionaries + description: Retrieve a list of all available stemming dictionaries. + operationId: listStemmingDictionaries + responses: + '200': + description: List of all dictionaries + content: + application/json: + schema: + type: object + properties: + dictionaries: + type: array + items: + type: string + example: ["irregular-plurals", "company-terms"] + + /stemming/dictionaries/{dictionaryId}: + get: + tags: + - stemming + summary: Retrieve a stemming dictionary + description: Fetch details of a specific stemming dictionary. + operationId: getStemmingDictionary + parameters: + - name: dictionaryId + in: path + description: The ID of the dictionary to retrieve + required: true + schema: + type: string + example: irregular-plurals + responses: + '200': + description: Stemming dictionary details + content: + application/json: + schema: + $ref: "#/components/schemas/StemmingDictionary" + '404': + description: Dictionary not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + + /stemming/dictionaries/import: + post: + tags: + - stemming + summary: Import a stemming dictionary + description: Upload a JSONL file containing word mappings to create or update a stemming dictionary. + operationId: importStemmingDictionary + parameters: + - name: id + in: query + description: The ID to assign to the dictionary + required: true + schema: + type: string + example: irregular-plurals + requestBody: + description: The JSONL file containing word mappings + required: true + content: + application/json: + schema: + type: string + example: | + {"word": "people", "root": "person"} + {"word": "children", "root": "child"} + responses: + '200': + description: Dictionary successfully imported + content: + application/octet-stream: + schema: + type: string + example: > + {"word": "people", "root": "person"} + {"word": "children", "root": "child"} + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /nl_search_models: + get: + tags: + - nl_search_models + summary: List all NL search models + description: Retrieve all NL search models. + operationId: retrieveAllNLSearchModels + responses: + '200': + description: List of all NL search models + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/NLSearchModelSchema' + post: + tags: + - nl_search_models + summary: Create a NL search model + description: Create a new NL search model. + operationId: createNLSearchModel + requestBody: + description: The NL search model to be created + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelCreateSchema' + required: true + responses: + '201': + description: NL search model successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /nl_search_models/{modelId}: + get: + tags: + - nl_search_models + summary: Retrieve a NL search model + description: Retrieve a specific NL search model by its ID. + operationId: retrieveNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to retrieve + required: true + schema: + type: string + responses: + '200': + description: NL search model fetched + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + put: + tags: + - nl_search_models + summary: Update a NL search model + description: Update an existing NL search model. + operationId: updateNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to update + required: true + schema: + type: string + requestBody: + description: The NL search model fields to update + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelUpdateSchema' + required: true + responses: + '200': + description: NL search model successfully updated + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - nl_search_models + summary: Delete a NL search model + description: Delete a specific NL search model by its ID. + operationId: deleteNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to delete + required: true + schema: + type: string + responses: + '200': + description: NL search model successfully deleted + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelDeleteSchema' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + +components: + schemas: + CollectionSchema: + required: + - name + - fields + type: object + properties: + name: + type: string + description: Name of the collection + example: companies + fields: + type: array + description: A list of fields for querying, filtering and faceting + example: + - name: num_employees + type: int32 + facet: false + - name: company_name + type: string + facet: false + - name: country + type: string + facet: true + items: + $ref: "#/components/schemas/Field" + default_sorting_field: + type: string description: The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during @@ -1331,7 +2035,7 @@ components: token_separators: type: array description: > - List of symbols or special characters to be used for + List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. items: type: string # characters only @@ -1341,12 +2045,12 @@ components: maxLength: 1 default: [] enable_nested_fields: - type: boolean - description: - Enables experimental support at a collection level for nested object or object array fields. - This field is only available if the Typesense server is version `0.24.0.rcn34` or later. - default: false - example: true + type: boolean + description: + Enables experimental support at a collection level for nested object or object array fields. + This field is only available if the Typesense server is version `0.24.0.rcn34` or later. + default: false + example: true symbols_to_index: type: array description: > @@ -1358,6 +2062,8 @@ components: minLength: 1 maxLength: 1 default: [] + voice_query_model: + $ref: "#/components/schemas/VoiceQueryModelCollectionConfig" CollectionUpdateSchema: required: - fields @@ -1428,6 +2134,10 @@ components: type: boolean example: true default: false + reference: + type: string + description: > + Name of a field in another collection that should be linked to this collection so that it can be joined during query. num_dim: type: integer example: 256 @@ -1435,6 +2145,49 @@ components: type: boolean example: true # omitting default value since we want it to be null + store: + type: boolean + description: > + When set to false, the field value will not be stored on disk. Default: true. + vec_dist: + type: string + description: > + The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. + range_index: + type: boolean + description: > + Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. + stem: + type: boolean + description: > + Values are stemmed before indexing in-memory. Default: false. + stem_dictionary: + type: string + description: Name of the stemming dictionary to use for this field + example: irregular-plurals + token_separators: + type: array + description: > + List of symbols or special characters to be used for + splitting the text into individual words in addition to space and new-line characters. + items: + type: string # characters only + # Could `enum` be used instead, given it's symbols/special *characters*, e.g.: + # enum: ["@", "!", ".", "/", ","] + minLength: 1 + maxLength: 1 + default: [] + symbols_to_index: + type: array + description: > + List of symbols or special characters to be indexed. + items: + type: string # characters only + # Could `enum` be used instead, given it's symbols/special *characters*, e.g.: + # enum: ["@", "!", ".", "/", ","] + minLength: 1 + maxLength: 1 + default: [] embed: type: object required: @@ -1454,14 +2207,30 @@ components: type: string api_key: type: string + url: + type: string access_token: type: string + refresh_token: + type: string client_id: type: string client_secret: type: string project_id: type: string + indexing_prefix: + type: string + query_prefix: + type: string + VoiceQueryModelCollectionConfig: + type: object + description: > + Configuration for the voice query model + properties: + model_name: + type: string + example: "ts/whisper/base.en" CollectionAliasSchema: type: object required: @@ -1503,6 +2272,8 @@ components: found: type: integer description: The number of documents found + found_docs: + type: integer search_time_ms: type: integer description: The number of milliseconds the search took @@ -1537,7 +2308,31 @@ components: type: string per_page: type: integer - + voice_query: + type: object + properties: + transcribed_query: + type: string + conversation: + $ref: "#/components/schemas/SearchResultConversation" + SearchResultConversation: + type: object + required: + - answer + - conversation_history + - conversation_id + - query + properties: + answer: + type: string + conversation_history: + type: array + items: + type: object + conversation_id: + type: string + query: + type: string SearchGroupedHit: type: object required: @@ -1574,6 +2369,25 @@ components: text_match: type: integer format: int64 + text_match_info: + type: object + properties: + best_field_score: + type: string + best_field_weight: + type: integer + fields_matched: + type: integer + num_tokens_dropped: + type: integer + format: int64 + x-go-type: uint64 + score: + type: string + tokens_matched: + type: integer + typo_prefix_score: + type: integer geo_distance_meters: type: object description: Can be any key-value pair @@ -1664,6 +2478,37 @@ components: type: boolean description: > Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + metadata: + type: object + description: > + Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + sort_by: + type: string + description: > + A sort by clause that is applied to any search query that matches the override rule. + replace_query: + type: string + description: > + Replaces the current search query with this value, when the search query matches the override rule. + filter_curated_hits: + type: boolean + description: > + When set to true, the filter conditions of the query is applied to the curated records as well. + Default: false. + effective_from_ts: + type: integer + description: > + A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + effective_to_ts: + type: integer + description: > + A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + stop_processing: + type: boolean + description: > + When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. + Overrides are processed in the lexical sort order of their id field. + Default: true. SearchOverride: allOf: - $ref: "#/components/schemas/SearchOverrideSchema" @@ -1674,12 +2519,22 @@ components: id: type: string readOnly: true - SearchOverrideRule: + SearchOverrideDeleteResponse: type: object required: - - query - - match + - id + properties: + id: + type: string + description: The id of the override that was deleted + SearchOverrideRule: + type: object properties: + tags: + type: array + description: List of tag values to associate with this override rule. + items: + type: string query: type: string description: Indicates what search queries should be overridden @@ -1692,6 +2547,10 @@ components: enum: - exact - contains + filter_by: + type: string + description: > + Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). SearchOverrideInclude: type: object required: @@ -1735,6 +2594,14 @@ components: description: Array of words that should be considered as synonyms. items: type: string + locale: + type: string + description: Locale for the synonym, leave blank to use the standard tokenizer. + symbols_to_index: + type: array + description: By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. + items: + type: string SearchSynonym: allOf: - $ref: "#/components/schemas/SearchSynonymSchema" @@ -1745,6 +2612,14 @@ components: id: type: string readOnly: true + SearchSynonymDeleteResponse: + type: object + required: + - id + properties: + id: + type: string + description: The id of the synonym that was deleted SearchSynonymsResponse: type: object required: @@ -1762,6 +2637,18 @@ components: properties: ok: type: boolean + SchemaChangeStatus: + type: object + properties: + collection: + type: string + description: Name of the collection being modified + validated_docs: + type: integer + description: Number of documents that have been validated + altered_docs: + type: integer + description: Number of documents that have been altered SuccessStatus: type: object required: @@ -1810,6 +2697,15 @@ components: value_prefix: type: string readOnly: true + ApiKeyDeleteResponse: + type: object + required: + - id + properties: + id: + type: integer + format: int64 + description: The id of the API key that was deleted ApiKeysResponse: type: object required: @@ -1846,13 +2742,23 @@ components: results: type: array items: - $ref: "#/components/schemas/SearchResult" + $ref: "#/components/schemas/MultiSearchResultItem" + conversation: + $ref: "#/components/schemas/SearchResultConversation" + MultiSearchResultItem: + allOf: + - $ref: "#/components/schemas/SearchResult" + - type: object + properties: + code: + type: integer + description: HTTP error code + format: int64 + error: + type: string + description: Error description SearchParameters: type: object - required: - - q - - query_by - properties: q: description: The query text to search for in the collection. @@ -1865,6 +2771,14 @@ components: against. Multiple fields are separated with a comma. type: string + nl_query: + description: Whether to use natural language processing to parse the query. + type: boolean + + nl_model_id: + description: The ID of the natural language model to use. + type: string + query_by_weights: description: The relative weight to give each `query_by` field when ranking results. @@ -1874,7 +2788,7 @@ components: text_match_type: description: - In a multi-field matching context, this parameter determines how the representative text match + In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. type: string @@ -1887,26 +2801,26 @@ components: infix: description: - If infix index is enabled for this field, infix searching can be done on a per-field - basis by sending a comma separated string parameter called infix to the search query. + If infix index is enabled for this field, infix searching can be done on a per-field + basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default - `always` infix search is performed along with regular search - `fallback` infix search is performed if regular search does not produce results + `always` infix search is performed along with regular search + `fallback` infix search is performed if regular search does not produce results type: string max_extra_prefix: description: - There are also 2 parameters that allow you to control the extent of infix searching - max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before - or after the query that can be present in the token. For example query "K2100" has 2 extra + There are also 2 parameters that allow you to control the extent of infix searching + max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before + or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. type: integer max_extra_suffix: description: - There are also 2 parameters that allow you to control the extent of infix searching - max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before - or after the query that can be present in the token. For example query "K2100" has 2 extra + There are also 2 parameters that allow you to control the extent of infix searching + max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before + or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. type: integer @@ -1917,6 +2831,12 @@ components: type: string example: "num_employees:>100 && country: [USA, UK]" + max_filter_by_candidates: + description: + Controls the number of similar words that Typesense considers during fuzzy search + on filter_by values. Useful for controlling prefix matches like company_name:Acm*. + type: integer + sort_by: description: A list of numerical fields and their corresponding sort orders @@ -1963,7 +2883,7 @@ components: limit: description: > - Number of hits to fetch. Can be used as an alternative to the per_page parameter. + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. type: integer @@ -1985,6 +2905,13 @@ components: Default: 3 type: integer + group_missing_values: + description: > + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. + Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. + Default: true + type: boolean + include_fields: description: List of fields from the document to include in the search result type: string @@ -2034,12 +2961,35 @@ components: enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 type: integer + drop_tokens_mode: + $ref: "#/components/schemas/DropTokensMode" typo_tokens_threshold: description: > If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 type: integer + enable_typos_for_alpha_numerical_tokens: + type: boolean + description: > + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + + filter_curated_hits: + type: boolean + description: > + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + enable_synonyms: + type: boolean + description: > + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + synonym_prefix: + type: boolean + description: > + Allow synonym resolution on word prefixes in the query. Default: false + synonym_num_typos: + type: integer + description: > + Allow synonym resolution on typo-corrected words in the query. Default: 0 pinned_hits: description: > @@ -2051,7 +3001,7 @@ components: you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based - on rules. Overrides are applied first, followed by `pinned_hits` and + on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. type: string @@ -2066,9 +3016,13 @@ components: finally `hidden_hits`. type: string + override_tags: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + highlight_fields: description: > - A list of custom fields that must be highlighted even if you don't query + A list of custom fields that must be highlighted even if you don't query for them type: string @@ -2083,7 +3037,7 @@ components: pre_segmented_query: description: > You can index content from any logographic language into Typesense if you - are able to segment / split the text into space-separated words yourself + are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same @@ -2100,12 +3054,14 @@ components: If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false type: boolean + default: false prioritize_exact_match: description: > Set this parameter to true to ensure that an exact match is ranked above the others type: boolean + default: true max_candidates: description: > Control the number of words that Typesense considers for typo and prefix searching. @@ -2114,15 +3070,26 @@ components: description: > Make Typesense prioritize documents where the query words appear earlier in the text. type: boolean + default: false + prioritize_num_matching_fields: + description: > + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + enable_typos_for_numerical_tokens: + description: > + Make Typesense disable typos for numerical tokens. + type: boolean + default: true exhaustive_search: description: > - Setting this to true will make Typesense consider all prefixes and typo - corrections of the words in the query without stopping early when enough results are found + Setting this to true will make Typesense consider all prefixes and typo + corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). type: boolean search_cutoff_ms: description: > - Typesense will attempt to return results early if the cutoff time has elapsed. + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. type: integer use_cache: @@ -2131,17 +3098,17 @@ components: type: boolean cache_ttl: description: > - The duration (in seconds) that determines how long the search query is cached. + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. type: integer min_len_1typo: description: > - Minimum word length for 1-typo correction to be applied. + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. type: integer min_len_2typo: description: > - Minimum word length for 2-typo correction to be applied. + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. type: integer vector_query: @@ -2156,6 +3123,36 @@ components: description: > Number of times to retry fetching remote embeddings. type: integer + facet_strategy: + description: > + Choose the underlying faceting strategy used. Comma separated string of allows values: + exhaustive, top_values or automatic (default). + type: string + stopwords: + description: > + Name of the stopwords set to apply for this search, + the keywords present in the set will be removed from the search query. + type: string + facet_return_parent: + description: > + Comma separated string of nested facet fields whose parent object should be returned in facet response. + type: string + voice_query: + description: > + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + conversation: + description: > + Enable conversational search. + type: boolean + conversation_model_id: + description: > + The Id of Conversation Model to be used. + type: string + conversation_id: + description: > + The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + type: string MultiSearchParameters: description: > @@ -2195,26 +3192,26 @@ components: infix: description: - If infix index is enabled for this field, infix searching can be done on a per-field - basis by sending a comma separated string parameter called infix to the search query. + If infix index is enabled for this field, infix searching can be done on a per-field + basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default - `always` infix search is performed along with regular search - `fallback` infix search is performed if regular search does not produce results + `always` infix search is performed along with regular search + `fallback` infix search is performed if regular search does not produce results type: string max_extra_prefix: description: - There are also 2 parameters that allow you to control the extent of infix searching - max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before - or after the query that can be present in the token. For example query "K2100" has 2 extra + There are also 2 parameters that allow you to control the extent of infix searching + max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before + or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. type: integer max_extra_suffix: description: - There are also 2 parameters that allow you to control the extent of infix searching - max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before - or after the query that can be present in the token. For example query "K2100" has 2 extra + There are also 2 parameters that allow you to control the extent of infix searching + max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before + or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. type: integer @@ -2270,7 +3267,7 @@ components: limit: description: > - Number of hits to fetch. Can be used as an alternative to the per_page parameter. + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. type: integer @@ -2292,6 +3289,13 @@ components: Default: 3 type: integer + group_missing_values: + description: > + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. + Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. + Default: true + type: boolean + include_fields: description: List of fields from the document to include in the search result type: string @@ -2334,12 +3338,35 @@ components: enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 type: integer + drop_tokens_mode: + $ref: "#/components/schemas/DropTokensMode" typo_tokens_threshold: description: > - If the number of results found for a specific query is less than this number, - Typesense will attempt to look for tokens with more typos until - enough results are found. Default: 100 + If the number of results found for a specific query is less than this number, + Typesense will attempt to look for tokens with more typos until + enough results are found. Default: 100 + type: integer + enable_typos_for_alpha_numerical_tokens: + type: boolean + description: > + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + + filter_curated_hits: + type: boolean + description: > + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + enable_synonyms: + type: boolean + description: > + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + synonym_prefix: + type: boolean + description: > + Allow synonym resolution on word prefixes in the query. Default: false + synonym_num_typos: type: integer + description: > + Allow synonym resolution on typo-corrected words in the query. Default: 0 pinned_hits: description: > @@ -2351,7 +3378,7 @@ components: you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based - on rules. Overrides are applied first, followed by `pinned_hits` and + on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. type: string @@ -2366,20 +3393,25 @@ components: finally `hidden_hits`. type: string + override_tags: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + highlight_fields: description: > - A list of custom fields that must be highlighted even if you don't query + A list of custom fields that must be highlighted even if you don't query for them type: string pre_segmented_query: description: > You can index content from any logographic language into Typesense if you - are able to segment / split the text into space-separated words yourself + are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same type: boolean + default: false preset: description: > @@ -2392,21 +3424,42 @@ components: If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false type: boolean + default: false prioritize_exact_match: description: > Set this parameter to true to ensure that an exact match is ranked above the others type: boolean + default: true + + prioritize_token_position: + description: > + Make Typesense prioritize documents where the query words appear earlier in the text. + type: boolean + default: false + + prioritize_num_matching_fields: + description: > + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + + enable_typos_for_numerical_tokens: + description: > + Make Typesense disable typos for numerical tokens. + type: boolean + default: true + exhaustive_search: description: > - Setting this to true will make Typesense consider all prefixes and typo - corrections of the words in the query without stopping early when enough results are found + Setting this to true will make Typesense consider all prefixes and typo + corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). type: boolean search_cutoff_ms: description: > - Typesense will attempt to return results early if the cutoff time has elapsed. + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. type: integer use_cache: @@ -2415,17 +3468,17 @@ components: type: boolean cache_ttl: description: > - The duration (in seconds) that determines how long the search query is cached. + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. type: integer min_len_1typo: description: > - Minimum word length for 1-typo correction to be applied. + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. type: integer min_len_2typo: description: > - Minimum word length for 2-typo correction to be applied. + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. type: integer vector_query: @@ -2440,11 +3493,44 @@ components: description: > Number of times to retry fetching remote embeddings. type: integer + facet_strategy: + description: > + Choose the underlying faceting strategy used. Comma separated string of allows values: + exhaustive, top_values or automatic (default). + type: string + stopwords: + description: > + Name of the stopwords set to apply for this search, + the keywords present in the set will be removed from the search query. + type: string + facet_return_parent: + description: > + Comma separated string of nested facet fields whose parent object should be returned in facet response. + type: string + voice_query: + description: > + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + conversation: + description: > + Enable conversational search. + type: boolean + conversation_model_id: + description: > + The Id of Conversation Model to be used. + type: string + conversation_id: + description: > + The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + type: string MultiSearchSearchesParameter: type: object required: - searches properties: + union: + type: boolean + description: When true, merges the search results from each search query into a single ordered set of hits. searches: type: array items: @@ -2453,13 +3539,21 @@ components: allOf: - $ref: "#/components/schemas/MultiSearchParameters" - type: object - required: - - collection properties: collection: type: string description: > The collection to search in. + x-typesense-api-key: + type: string + description: A separate search API key for each search within a multi_search request + rerank_hybrid_matches: + type: boolean + description: > + When true, computes both text match and vector distance scores for all matches in hybrid search. + Documents found only through keyword search will get a vector distance score, and + documents found only through vector search will get a text match score. + default: false FacetCounts: type: object properties: @@ -2474,6 +3568,8 @@ components: type: string value: type: string + parent: + type: object field_name: type: string stats: @@ -2493,17 +3589,38 @@ components: avg: type: number format: double - AnalyticsRuleSchema: + AnalyticsEventCreateResponse: + type: object + required: + - ok + properties: + ok: + type: boolean + AnalyticsEventCreateSchema: type: object required: - - name - type - - params + - name + - data properties: + type: + type: string name: type: string + data: + type: object + AnalyticsRuleUpsertSchema: + type: object + required: + - type + - params + properties: type: type: string + enum: + - popular_queries + - nohits_queries + - counter params: $ref: "#/components/schemas/AnalyticsRuleParameters" AnalyticsRuleParameters: @@ -2511,22 +3628,65 @@ components: required: - source - destination - - limit properties: source: - type: object - properties: - collections: - type: array - items: - type: string + $ref: '#/components/schemas/AnalyticsRuleParametersSource' destination: - type: object - properties: - collection: - type: string + $ref: '#/components/schemas/AnalyticsRuleParametersDestination' limit: type: integer + expand_query: + type: boolean + AnalyticsRuleParametersSource: + type: object + required: + - collections + properties: + collections: + type: array + items: + type: string + events: + type: array + items: + type: object + required: + - type + - weight + - name + properties: + type: + type: string + weight: + type: number + format: float + name: + type: string + AnalyticsRuleParametersDestination: + type: object + required: + - collection + properties: + collection: + type: string + counter_field: + type: string + AnalyticsRuleDeleteResponse: + type: object + required: + - name + properties: + name: + type: string + AnalyticsRuleSchema: + allOf: + - $ref: '#/components/schemas/AnalyticsRuleUpsertSchema' + - type: object + required: + - name + properties: + name: + type: string AnalyticsRulesRetrieveSchema: type: object properties: @@ -2534,6 +3694,335 @@ components: type: array items: $ref: "#/components/schemas/AnalyticsRuleSchema" + x-go-type: '[]*AnalyticsRuleSchema' + APIStatsResponse: + type: object + properties: + delete_latency_ms: + type: number + format: double + delete_requests_per_second: + type: number + format: double + import_latency_ms: + type: number + format: double + import_requests_per_second: + type: number + format: double + latency_ms: + type: object + x-go-type: "map[string]float64" + overloaded_requests_per_second: + type: number + format: double + pending_write_batches: + type: number + format: double + requests_per_second: + type: object + x-go-type: "map[string]float64" + search_latency_ms: + type: number + format: double + search_requests_per_second: + type: number + format: double + total_requests_per_second: + type: number + format: double + write_latency_ms: + type: number + format: double + write_requests_per_second: + type: number + format: double + StopwordsSetUpsertSchema: + type: object + properties: + stopwords: + type: array + items: + type: string + locale: + type: string + required: + - stopwords + example: | + {"stopwords": ["Germany", "France", "Italy"], "locale": "en"} + StopwordsSetSchema: + type: object + properties: + id: + type: string + stopwords: + type: array + items: + type: string + locale: + type: string + required: + - id + - stopwords + example: | + {"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"} + StopwordsSetRetrieveSchema: + type: object + properties: + stopwords: + $ref: "#/components/schemas/StopwordsSetSchema" + required: + - stopwords + example: | + {"stopwords": {"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"}} + StopwordsSetsRetrieveAllSchema: + type: object + properties: + stopwords: + type: array + items: + $ref: "#/components/schemas/StopwordsSetSchema" + required: + - stopwords + example: | + {"stopwords": [{"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"}]} + PresetUpsertSchema: + properties: + value: + oneOf: + - $ref: '#/components/schemas/SearchParameters' + - $ref: '#/components/schemas/MultiSearchSearchesParameter' + required: + - value + PresetSchema: + allOf: + - $ref: '#/components/schemas/PresetUpsertSchema' + - type: object + required: + - name + properties: + name: + type: string + PresetsRetrieveSchema: + type: object + required: + - presets + properties: + presets: + type: array + items: + $ref: '#/components/schemas/PresetSchema' + x-go-type: '[]*PresetSchema' + PresetDeleteSchema: + type: object + required: + - name + properties: + name: + type: string + # client libraries already have .create, .upsert,... methods so we omit the `action` param + DocumentIndexParameters: + type: object + properties: + dirty_values: + $ref: "#/components/schemas/DirtyValues" + DirtyValues: + type: string + enum: [coerce_or_reject, coerce_or_drop, drop, reject] + IndexAction: + type: string + enum: [create, update, upsert, emplace] + DropTokensMode: + type: string + enum: [right_to_left, left_to_right, both_sides:3] + description: > + Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. + Values: right_to_left (default), left_to_right, both_sides:3 + A note on both_sides:3 - for queries upto 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. + If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left + ConversationModelCreateSchema: + required: + - model_name + - max_bytes + allOf: + - $ref: '#/components/schemas/ConversationModelUpdateSchema' + - type: object + required: + - model_name + - max_bytes + - history_collection + properties: + model_name: + description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM + type: string + max_bytes: + description: | + The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + type: integer + history_collection: + type: string + description: Typesense collection that stores the historical conversations + ConversationModelUpdateSchema: + type: object + properties: + id: + type: string + description: An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + model_name: + description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM + type: string + api_key: + description: The LLM service's API Key + type: string + history_collection: + type: string + description: Typesense collection that stores the historical conversations + account_id: + description: LLM service's account ID (only applicable for Cloudflare) + type: string + system_prompt: + description: The system prompt that contains special instructions to the LLM + type: string + ttl: + type: integer + description: | + Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + max_bytes: + description: | + The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + type: integer + vllm_url: + description: URL of vLLM service + type: string + ConversationModelSchema: + allOf: + - $ref: '#/components/schemas/ConversationModelCreateSchema' + - type: object + required: + - id + properties: + id: + type: string + description: An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + StemmingDictionary: + type: object + required: + - id + - words + properties: + id: + type: string + description: Unique identifier for the dictionary + example: irregular-plurals + words: + type: array + description: List of word mappings in the dictionary + items: + type: object + required: + - word + - root + properties: + word: + type: string + description: The word form to be stemmed + example: people + root: + type: string + description: The root form of the word + example: person + NLSearchModelBase: + type: object + properties: + model_name: + type: string + description: Name of the NL model to use + api_key: + type: string + description: API key for the NL model service + api_url: + type: string + description: Custom API URL for the NL model service + max_bytes: + type: integer + description: Maximum number of bytes to process + temperature: + type: number + description: Temperature parameter for the NL model + system_prompt: + type: string + description: System prompt for the NL model + top_p: + type: number + description: Top-p parameter for the NL model (Google-specific) + top_k: + type: integer + description: Top-k parameter for the NL model (Google-specific) + stop_sequences: + type: array + items: + type: string + description: Stop sequences for the NL model (Google-specific) + api_version: + type: string + description: API version for the NL model service + project_id: + type: string + description: Project ID for GCP Vertex AI + access_token: + type: string + description: Access token for GCP Vertex AI + refresh_token: + type: string + description: Refresh token for GCP Vertex AI + client_id: + type: string + description: Client ID for GCP Vertex AI + client_secret: + type: string + description: Client secret for GCP Vertex AI + region: + type: string + description: Region for GCP Vertex AI + max_output_tokens: + type: integer + description: Maximum output tokens for GCP Vertex AI + account_id: + type: string + description: Account ID for Cloudflare-specific models + + NLSearchModelCreateSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelBase' + - type: object + properties: + id: + type: string + description: Optional ID for the NL search model + + NLSearchModelSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelCreateSchema' + - type: object + required: + - id + properties: + id: + type: string + description: ID of the NL search model + + NLSearchModelUpdateSchema: + $ref: '#/components/schemas/NLSearchModelCreateSchema' + + NLSearchModelDeleteSchema: + type: object + required: + - id + properties: + id: + type: string + description: ID of the deleted NL search model + securitySchemes: api_key_header: type: apiKey diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml new file mode 100644 index 0000000..b2740e7 --- /dev/null +++ b/preprocessed_openapi.yml @@ -0,0 +1,4481 @@ +openapi: 3.0.3 +info: + title: Typesense API + description: An open source search engine for building delightful search experiences. + version: '28.0' +externalDocs: + description: Find out more about Typsesense + url: https://typesense.org +security: +- api_key_header: [] +tags: +- name: collections + description: A collection is defined by a schema + externalDocs: + description: Find out more + url: https://typesense.org/api/#create-collection +- name: documents + description: A document is an individual record to be indexed and belongs to a collection + externalDocs: + description: Find out more + url: https://typesense.org/api/#index-document +- name: curation + description: Hand-curate search results based on conditional business rules + externalDocs: + description: Find out more + url: https://typesense.org/docs/0.23.0/api/#curation +- name: analytics + description: Typesense can aggregate search queries for both analytics purposes and for query suggestions. + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/analytics-query-suggestions.html +- name: keys + description: Manage API Keys with fine-grain access control + externalDocs: + description: Find out more + url: https://typesense.org/docs/0.23.0/api/#api-keys +- name: debug + description: Debugging information +- name: operations + description: Manage Typesense cluster + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/cluster-operations.html +- name: stopwords + description: Manage stopwords sets + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stopwords.html +- name: presets + description: Store and reference search parameters + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/search.html#presets +- name: conversations + description: Conversational Search (RAG) + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/conversational-search-rag.html +- name: synonyms + description: Manage synonyms + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/synonyms.html +- name: stemming + description: Manage stemming dictionaries + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stemming.html +- name: nl_search_models + description: Manage NL search models + externalDocs: + description: Find out more + url: https://typesense.org/docs/29.0/api/natural-language-search.html +paths: + /collections: + get: + tags: + - collections + summary: List all collections + description: Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first. + operationId: getCollections + responses: + '200': + description: List of all collections + content: + application/json: + schema: + type: array + x-go-type: '[]*CollectionResponse' + items: + $ref: '#/components/schemas/CollectionResponse' + post: + tags: + - collections + summary: Create a new collection + description: When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. + operationId: createCollection + requestBody: + description: The collection object to be created + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionSchema' + required: true + responses: + '201': + description: Collection successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '409': + description: Collection already exists + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}: + get: + tags: + - collections + summary: Retrieve a single collection + description: Retrieve the details of a collection, given its name. + operationId: getCollection + parameters: + - name: collectionName + in: path + description: The name of the collection to retrieve + required: true + schema: + type: string + responses: + '200': + description: Collection fetched + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionResponse' + '404': + description: Collection not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + patch: + tags: + - collections + summary: Update a collection + description: Update a collection's schema to modify the fields and their types. + operationId: updateCollection + parameters: + - name: collectionName + in: path + description: The name of the collection to update + required: true + schema: + type: string + requestBody: + description: The document object with fields to be updated + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionUpdateSchema' + required: true + responses: + '200': + description: The updated partial collection schema + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionUpdateSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: The collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - collections + summary: Delete a collection + description: Permanently drops a collection. This action cannot be undone. For large collections, this might have an impact on read latencies. + operationId: deleteCollection + parameters: + - name: collectionName + in: path + description: The name of the collection to delete + required: true + schema: + type: string + responses: + '200': + description: Collection deleted + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionResponse' + '404': + description: Collection not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/documents: + post: + tags: + - documents + summary: Index a document + description: A document to be indexed in a given collection must conform to the schema of the collection. + operationId: indexDocument + parameters: + - name: collectionName + in: path + description: The name of the collection to add the document to + required: true + schema: + type: string + - name: action + in: query + description: Additional action to perform + schema: + type: string + example: upsert + $ref: '#/components/schemas/IndexAction' + - name: dirty_values + in: query + description: Dealing with Dirty Data + schema: + $ref: '#/components/schemas/DirtyValues' + requestBody: + description: The document object to be indexed + content: + application/json: + schema: + type: object + description: Can be any key-value pair + x-go-type: interface{} + required: true + responses: + '201': + description: Document successfully created/indexed + content: + application/json: + schema: + type: object + description: Can be any key-value pair + '404': + description: Collection not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + patch: + tags: + - documents + summary: Update documents with conditional query + description: The filter_by query parameter is used to filter to specify a condition against which the documents are matched. The request body contains the fields that should be updated for any documents that match the filter condition. This endpoint is only available if the Typesense server is version `0.25.0.rc12` or later. + operationId: updateDocuments + parameters: + - name: collectionName + in: path + description: The name of the collection to update documents in + required: true + schema: + type: string + - name: filter_by + in: query + schema: + type: string + example: 'num_employees:>100 && country: [USA, UK]' + responses: + '200': + description: The response contains a single field, `num_updated`, indicating the number of documents affected. + content: + application/json: + schema: + type: object + required: + - num_updated + properties: + num_updated: + type: integer + description: The number of documents that have been updated + example: 1 + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: The collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + requestBody: + description: The document fields to be updated + content: + application/json: + schema: + type: object + description: Can be any key-value pair + x-go-type: interface{} + required: true + delete: + tags: + - documents + summary: Delete a bunch of documents + description: Delete a bunch of documents that match a specific filter condition. Use the `batch_size` parameter to control the number of documents that should deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. + operationId: deleteDocuments + parameters: + - name: collectionName + in: path + description: The name of the collection to delete documents from + required: true + schema: + type: string + - name: filter_by + in: query + schema: + type: string + example: 'num_employees:>100 && country: [USA, UK]' + - name: batch_size + in: query + schema: + description: Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. + type: integer + - name: ignore_not_found + in: query + schema: + type: boolean + - name: truncate + in: query + schema: + description: When true, removes all documents from the collection while preserving the collection and its schema. + type: boolean + responses: + '200': + description: Documents successfully deleted + content: + application/json: + schema: + type: object + required: + - num_deleted + properties: + num_deleted: + type: integer + '404': + description: Collection not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/documents/search: + get: + tags: + - documents + summary: Search for documents in a collection + description: Search for documents in a collection that match the search criteria. + operationId: searchCollection + parameters: + - name: collectionName + in: path + description: The name of the collection to search for the document under + required: true + schema: + type: string + - name: q + in: query + schema: + description: The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. + type: string + - name: query_by + in: query + schema: + description: A list of `string` fields that should be queried against. Multiple fields are separated with a comma. + type: string + - name: nl_query + in: query + schema: + description: Whether to use natural language processing to parse the query. + type: boolean + - name: nl_model_id + in: query + schema: + description: The ID of the natural language model to use. + type: string + - name: query_by_weights + in: query + schema: + description: The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. + type: string + - name: text_match_type + in: query + schema: + description: In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. + type: string + - name: prefix + in: query + schema: + description: Boolean field to indicate that the last word in the query should be treated as a prefix, and not as a whole word. This is used for building autocomplete and instant search interfaces. Defaults to true. + type: string + - name: infix + in: query + schema: + description: If infix index is enabled for this field, infix searching can be done on a per-field basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default `always` infix search is performed along with regular search `fallback` infix search is performed if regular search does not produce results + type: string + - name: max_extra_prefix + in: query + schema: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + - name: max_extra_suffix + in: query + schema: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + - name: filter_by + in: query + schema: + description: Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. + type: string + example: 'num_employees:>100 && country: [USA, UK]' + - name: max_filter_by_candidates + in: query + schema: + description: Controls the number of similar words that Typesense considers during fuzzy search on filter_by values. Useful for controlling prefix matches like company_name:Acm*. + type: integer + - name: sort_by + in: query + schema: + description: A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` + type: string + example: num_employees:desc + - name: facet_by + in: query + schema: + description: A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. + type: string + - name: max_facet_values + in: query + schema: + description: Maximum number of facet values to be returned. + type: integer + - name: facet_query + in: query + schema: + description: Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix "shoe". + type: string + - name: num_typos + in: query + schema: + description: | + The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + type: string + - name: page + in: query + schema: + description: Results from this specific page number would be fetched. + type: integer + - name: per_page + in: query + schema: + description: 'Number of results to fetch per page. Default: 10' + type: integer + - name: limit + in: query + schema: + description: | + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + type: integer + - name: offset + in: query + schema: + description: Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. + type: integer + - name: group_by + in: query + schema: + description: You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. + type: string + - name: group_limit + in: query + schema: + description: | + Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + type: integer + - name: group_missing_values + in: query + schema: + description: | + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + type: boolean + - name: include_fields + in: query + schema: + description: List of fields from the document to include in the search result + type: string + - name: exclude_fields + in: query + schema: + description: List of fields from the document to exclude in the search result + type: string + - name: highlight_full_fields + in: query + schema: + description: List of fields which should be highlighted fully without snippeting + type: string + - name: highlight_affix_num_tokens + in: query + schema: + description: | + The number of tokens that should surround the highlighted text on each side. Default: 4 + type: integer + - name: highlight_start_tag + in: query + schema: + description: | + The start tag used for the highlighted snippets. Default: `` + type: string + - name: highlight_end_tag + in: query + schema: + description: | + The end tag used for the highlighted snippets. Default: `` + type: string + - name: enable_highlight_v1 + in: query + schema: + description: | + Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true + type: boolean + default: true + - name: snippet_threshold + in: query + schema: + description: | + Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + type: integer + - name: drop_tokens_threshold + in: query + schema: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + type: integer + - name: drop_tokens_mode + in: query + schema: + $ref: '#/components/schemas/DropTokensMode' + - name: typo_tokens_threshold + in: query + schema: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + type: integer + - name: enable_typos_for_alpha_numerical_tokens + in: query + schema: + type: boolean + description: | + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + - name: filter_curated_hits + in: query + schema: + type: boolean + description: | + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + - name: enable_synonyms + in: query + schema: + type: boolean + description: | + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + - name: synonym_prefix + in: query + schema: + type: boolean + description: | + Allow synonym resolution on word prefixes in the query. Default: false + - name: synonym_num_typos + in: query + schema: + type: integer + description: | + Allow synonym resolution on typo-corrected words in the query. Default: 0 + - name: pinned_hits + in: query + schema: + description: | + A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + - name: hidden_hits + in: query + schema: + description: | + A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + - name: override_tags + in: query + schema: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + - name: highlight_fields + in: query + schema: + description: | + A list of custom fields that must be highlighted even if you don't query for them + type: string + - name: split_join_tokens + in: query + schema: + description: | + Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. + type: string + - name: pre_segmented_query + in: query + schema: + description: | + You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. + Set this parameter to true to do the same + type: boolean + - name: preset + in: query + schema: + description: | + Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + type: string + - name: enable_overrides + in: query + schema: + description: | + If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + type: boolean + default: false + - name: prioritize_exact_match + in: query + schema: + description: | + Set this parameter to true to ensure that an exact match is ranked above the others + type: boolean + default: true + - name: max_candidates + in: query + schema: + description: | + Control the number of words that Typesense considers for typo and prefix searching. + type: integer + - name: prioritize_token_position + in: query + schema: + description: | + Make Typesense prioritize documents where the query words appear earlier in the text. + type: boolean + default: false + - name: prioritize_num_matching_fields + in: query + schema: + description: | + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + - name: enable_typos_for_numerical_tokens + in: query + schema: + description: | + Make Typesense disable typos for numerical tokens. + type: boolean + default: true + - name: exhaustive_search + in: query + schema: + description: | + Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + type: boolean + - name: search_cutoff_ms + in: query + schema: + description: | + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + type: integer + - name: use_cache + in: query + schema: + description: | + Enable server side caching of search query results. By default, caching is disabled. + type: boolean + - name: cache_ttl + in: query + schema: + description: | + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + type: integer + - name: min_len_1typo + in: query + schema: + description: | + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + - name: min_len_2typo + in: query + schema: + description: | + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + - name: vector_query + in: query + schema: + description: | + Vector query expression for fetching documents "closest" to a given query/document vector. + type: string + - name: remote_embedding_timeout_ms + in: query + schema: + description: | + Timeout (in milliseconds) for fetching remote embeddings. + type: integer + - name: remote_embedding_num_tries + in: query + schema: + description: | + Number of times to retry fetching remote embeddings. + type: integer + - name: facet_strategy + in: query + schema: + description: | + Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + type: string + - name: stopwords + in: query + schema: + description: | + Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + type: string + - name: facet_return_parent + in: query + schema: + description: | + Comma separated string of nested facet fields whose parent object should be returned in facet response. + type: string + - name: voice_query + in: query + schema: + description: | + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + - name: conversation + in: query + schema: + description: | + Enable conversational search. + type: boolean + - name: conversation_model_id + in: query + schema: + description: | + The Id of Conversation Model to be used. + type: string + - name: conversation_id + in: query + schema: + description: | + The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + type: string + responses: + '200': + description: Search results + content: + application/json: + schema: + $ref: '#/components/schemas/SearchResult' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: The collection or field was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/overrides: + get: + tags: + - documents + - curation + summary: List all collection overrides + operationId: getSearchOverrides + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + responses: + '200': + description: List of all search overrides + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverridesResponse' + /collections/{collectionName}/overrides/{overrideId}: + get: + tags: + - documents + - override + summary: Retrieve a single search override + description: Retrieve the details of a search override, given its id. + operationId: getSearchOverride + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: overrideId + in: path + description: The id of the search override + required: true + schema: + type: string + responses: + '200': + description: Search override fetched + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverride' + put: + tags: + - documents + - curation + summary: Create or update an override to promote certain documents over others + description: Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. + operationId: upsertSearchOverride + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: overrideId + in: path + description: The ID of the search override to create/update + required: true + schema: + type: string + requestBody: + description: The search override object to be created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverrideSchema' + required: true + responses: + '200': + description: Created/updated search override + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverride' + '404': + description: Search override not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - documents + - curation + summary: Delete an override associated with a collection + operationId: deleteSearchOverride + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: overrideId + in: path + description: The ID of the search override to delete + required: true + schema: + type: string + responses: + '200': + description: The ID of the deleted search override + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverrideDeleteResponse' + '404': + description: Search override not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/synonyms: + get: + tags: + - synonyms + summary: List all collection synonyms + operationId: getSearchSynonyms + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + responses: + '200': + description: List of all search synonyms + content: + application/json: + schema: + $ref: '#/components/schemas/SearchSynonymsResponse' + '404': + description: Search synonyms was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/synonyms/{synonymId}: + get: + tags: + - synonyms + summary: Retrieve a single search synonym + description: Retrieve the details of a search synonym, given its id. + operationId: getSearchSynonym + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: synonymId + in: path + description: The id of the search synonym + required: true + schema: + type: string + responses: + '200': + description: Search synonym fetched + content: + application/json: + schema: + $ref: '#/components/schemas/SearchSynonym' + '404': + description: Search synonym was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + put: + tags: + - synonyms + summary: Create or update a synonym + description: Create or update a synonym to define search terms that should be considered equivalent. + operationId: upsertSearchSynonym + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: synonymId + in: path + description: The ID of the search synonym to create/update + required: true + schema: + type: string + requestBody: + description: The search synonym object to be created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/SearchSynonymSchema' + required: true + responses: + '200': + description: Created/updated search synonym + content: + application/json: + schema: + $ref: '#/components/schemas/SearchSynonym' + '404': + description: Search synonym was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - synonyms + summary: Delete a synonym associated with a collection + operationId: deleteSearchSynonym + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: synonymId + in: path + description: The ID of the search synonym to delete + required: true + schema: + type: string + responses: + '200': + description: The ID of the deleted search synonym + content: + application/json: + schema: + $ref: '#/components/schemas/SearchSynonymDeleteResponse' + '404': + description: Search synonym not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/documents/export: + get: + tags: + - documents + summary: Export all documents in a collection + description: Export all documents in a collection in JSON lines format. + operationId: exportDocuments + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: filter_by + in: query + schema: + description: Filter conditions for refining your search results. Separate multiple conditions with &&. + type: string + - name: include_fields + in: query + schema: + description: List of fields from the document to include in the search result + type: string + - name: exclude_fields + in: query + schema: + description: List of fields from the document to exclude in the search result + type: string + responses: + '200': + description: Exports all the documents in a given collection. + content: + application/octet-stream: + schema: + type: string + example: | + {"id": "124", "company_name": "Stark Industries", "num_employees": 5215, "country": "US"} + {"id": "125", "company_name": "Future Technology", "num_employees": 1232,"country": "UK"} + {"id": "126", "company_name": "Random Corp.", "num_employees": 531,"country": "AU"} + '404': + description: The collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/documents/import: + post: + tags: + - documents + summary: Import documents into a collection + description: The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. + operationId: importDocuments + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: batch_size + in: query + schema: + type: integer + - name: return_id + in: query + schema: + type: boolean + description: Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. + - name: remote_embedding_batch_size + in: query + schema: + type: integer + - name: return_doc + in: query + schema: + type: boolean + - name: action + in: query + schema: + $ref: '#/components/schemas/IndexAction' + - name: dirty_values + in: query + schema: + $ref: '#/components/schemas/DirtyValues' + requestBody: + description: The json array of documents or the JSONL file to import + content: + application/octet-stream: + schema: + type: string + description: The JSONL file to import + required: true + responses: + '200': + description: Result of the import operation. Each line of the response indicates the result of each document present in the request body (in the same order). If the import of a single document fails, it does not affect the other documents. If there is a failure, the response line will include a corresponding error message and as well as the actual document content. + content: + application/octet-stream: + schema: + type: string + example: | + {"success": true} + {"success": false, "error": "Bad JSON.", "document": "[bad doc"} + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: The collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /collections/{collectionName}/documents/{documentId}: + get: + tags: + - documents + summary: Retreive a document + description: Fetch an individual document from a collection by using its ID. + operationId: getDocument + parameters: + - name: collectionName + in: path + description: The name of the collection to search for the document under + required: true + schema: + type: string + - name: documentId + in: path + description: The Document ID + required: true + schema: + type: string + responses: + '200': + description: The document referenced by the ID + content: + application/json: + schema: + type: object + description: Can be any key-value pair + '404': + description: The document or collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + patch: + tags: + - documents + summary: Update a document + description: Update an individual document from a collection by using its ID. The update can be partial. + operationId: updateDocument + parameters: + - name: collectionName + in: path + description: The name of the collection to search for the document under + required: true + schema: + type: string + - name: documentId + in: path + description: The Document ID + required: true + schema: + type: string + - name: dirty_values + in: query + description: Dealing with Dirty Data + schema: + $ref: '#/components/schemas/DirtyValues' + requestBody: + description: The document object with fields to be updated + content: + application/json: + schema: + type: object + description: Can be any key-value pair + x-go-type: interface{} + required: true + responses: + '200': + description: The document referenced by the ID was updated + content: + application/json: + schema: + type: object + description: Can be any key-value pair + '404': + description: The document or collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - documents + summary: Delete a document + description: Delete an individual document from a collection by using its ID. + operationId: deleteDocument + parameters: + - name: collectionName + in: path + description: The name of the collection to search for the document under + required: true + schema: + type: string + - name: documentId + in: path + description: The Document ID + required: true + schema: + type: string + responses: + '200': + description: The document referenced by the ID was deleted + content: + application/json: + schema: + type: object + description: Can be any key-value pair + '404': + description: The document or collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /conversations/models: + get: + description: Retrieve all conversation models + operationId: retrieveAllConversationModels + responses: + '200': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/ConversationModelSchema' + type: array + x-go-type: '[]*ConversationModelSchema' + description: List of all conversation models + summary: List all conversation models + tags: + - conversations + post: + description: Create a Conversation Model + operationId: createConversationModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelCreateSchema' + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: Created Conversation Model + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + tags: + - conversations + /conversations/models/{modelId}: + get: + description: Retrieve a conversation model + operationId: retrieveConversationModel + parameters: + - name: modelId + in: path + description: The id of the conversation model to retrieve + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: A conversation model + summary: Retrieve a conversation model + tags: + - conversations + put: + description: Update a conversation model + operationId: updateConversationModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelUpdateSchema' + required: true + parameters: + - name: modelId + in: path + description: The id of the conversation model to update + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: The conversation model was successfully updated + summary: Update a conversation model + tags: + - conversations + delete: + description: Delete a conversation model + operationId: deleteConversationModel + parameters: + - name: modelId + in: path + description: The id of the conversation model to delete + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: The conversation model was successfully deleted + summary: Delete a conversation model + tags: + - conversations + /keys: + get: + tags: + - keys + summary: Retrieve (metadata about) all keys. + operationId: getKeys + responses: + '200': + description: List of all keys + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeysResponse' + post: + tags: + - keys + summary: Create an API Key + description: Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. + operationId: createKey + requestBody: + description: The object that describes API key scope + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeySchema' + responses: + '201': + description: Created API key + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKey' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '409': + description: API key generation conflict + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /keys/{keyId}: + get: + tags: + - keys + summary: Retrieve (metadata about) a key + description: Retrieve (metadata about) a key. Only the key prefix is returned when you retrieve a key. Due to security reasons, only the create endpoint returns the full API key. + operationId: getKey + parameters: + - name: keyId + in: path + description: The ID of the key to retrieve + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: The key referenced by the ID + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKey' + '404': + description: The key was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - keys + summary: Delete an API key given its ID. + operationId: deleteKey + parameters: + - name: keyId + in: path + description: The ID of the key to delete + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: The key referenced by the ID + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeyDeleteResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: Key not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /aliases: + get: + tags: + - collections + summary: List all aliases + description: List all aliases and the corresponding collections that they map to. + operationId: getAliases + responses: + '200': + description: List of all collection aliases + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAliasesResponse' + /aliases/{aliasName}: + put: + tags: + - collections + summary: Create or update a collection alias + description: Create or update a collection alias. An alias is a virtual collection name that points to a real collection. If you're familiar with symbolic links on Linux, it's very similar to that. Aliases are useful when you want to reindex your data in the background on a new collection and switch your application to it without any changes to your code. + operationId: upsertAlias + parameters: + - name: aliasName + in: path + description: The name of the alias to create/update + required: true + schema: + type: string + requestBody: + description: Collection alias to be created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAliasSchema' + responses: + '200': + description: The collection alias was created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAlias' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: Alias not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - collections + summary: Retrieve an alias + description: Find out which collection an alias points to by fetching it + operationId: getAlias + parameters: + - name: aliasName + in: path + description: The name of the alias to retrieve + required: true + schema: + type: string + responses: + '200': + description: Collection alias fetched + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAlias' + '404': + description: The alias was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - collections + summary: Delete an alias + operationId: deleteAlias + parameters: + - name: aliasName + in: path + description: The name of the alias to delete + required: true + schema: + type: string + responses: + '200': + description: Collection alias was deleted + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAlias' + '404': + description: Alias not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /debug: + get: + tags: + - debug + summary: Print debugging information + description: Print debugging information + operationId: debug + responses: + '200': + description: Debugging information + content: + application/json: + schema: + type: object + properties: + version: + type: string + /health: + get: + tags: + - health + summary: Checks if Typesense server is ready to accept requests. + description: Checks if Typesense server is ready to accept requests. + operationId: health + responses: + '200': + description: Search service is ready for requests. + content: + application/json: + schema: + $ref: '#/components/schemas/HealthStatus' + /operations/schema_changes: + get: + tags: + - operations + summary: Get the status of in-progress schema change operations + description: Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. + operationId: getSchemaChanges + responses: + '200': + description: List of schema changes in progress + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaChangeStatus' + /operations/snapshot: + post: + tags: + - operations + summary: Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. + description: Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. + operationId: takeSnapshot + parameters: + - name: snapshot_path + in: query + description: The directory on the server where the snapshot should be saved. + required: true + schema: + type: string + responses: + '201': + description: Snapshot is created. + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + /operations/vote: + post: + tags: + - operations + summary: Triggers a follower node to initiate the raft voting process, which triggers leader re-election. + description: Triggers a follower node to initiate the raft voting process, which triggers leader re-election. The follower node that you run this operation against will become the new leader, once this command succeeds. + operationId: vote + responses: + '200': + description: Re-election is performed. + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + /multi_search: + post: + operationId: multiSearch + tags: + - documents + summary: send multiple search requests in a single HTTP request + description: This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. + parameters: + - name: q + in: query + schema: + description: The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. + type: string + - name: query_by + in: query + schema: + description: A list of `string` fields that should be queried against. Multiple fields are separated with a comma. + type: string + - name: query_by_weights + in: query + schema: + description: The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. + type: string + - name: text_match_type + in: query + schema: + description: In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. + type: string + - name: prefix + in: query + schema: + description: Boolean field to indicate that the last word in the query should be treated as a prefix, and not as a whole word. This is used for building autocomplete and instant search interfaces. Defaults to true. + type: string + - name: infix + in: query + schema: + description: If infix index is enabled for this field, infix searching can be done on a per-field basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default `always` infix search is performed along with regular search `fallback` infix search is performed if regular search does not produce results + type: string + - name: max_extra_prefix + in: query + schema: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + - name: max_extra_suffix + in: query + schema: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + - name: filter_by + in: query + schema: + description: Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. + type: string + example: 'num_employees:>100 && country: [USA, UK]' + - name: sort_by + in: query + schema: + description: A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` + type: string + - name: facet_by + in: query + schema: + description: A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. + type: string + - name: max_facet_values + in: query + schema: + description: Maximum number of facet values to be returned. + type: integer + - name: facet_query + in: query + schema: + description: Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix "shoe". + type: string + - name: num_typos + in: query + schema: + description: | + The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + type: string + - name: page + in: query + schema: + description: Results from this specific page number would be fetched. + type: integer + - name: per_page + in: query + schema: + description: 'Number of results to fetch per page. Default: 10' + type: integer + - name: limit + in: query + schema: + description: | + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + type: integer + - name: offset + in: query + schema: + description: Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. + type: integer + - name: group_by + in: query + schema: + description: You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. + type: string + - name: group_limit + in: query + schema: + description: | + Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + type: integer + - name: group_missing_values + in: query + schema: + description: | + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + type: boolean + - name: include_fields + in: query + schema: + description: List of fields from the document to include in the search result + type: string + - name: exclude_fields + in: query + schema: + description: List of fields from the document to exclude in the search result + type: string + - name: highlight_full_fields + in: query + schema: + description: List of fields which should be highlighted fully without snippeting + type: string + - name: highlight_affix_num_tokens + in: query + schema: + description: | + The number of tokens that should surround the highlighted text on each side. Default: 4 + type: integer + - name: highlight_start_tag + in: query + schema: + description: | + The start tag used for the highlighted snippets. Default: `` + type: string + - name: highlight_end_tag + in: query + schema: + description: | + The end tag used for the highlighted snippets. Default: `` + type: string + - name: snippet_threshold + in: query + schema: + description: | + Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + type: integer + - name: drop_tokens_threshold + in: query + schema: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + type: integer + - name: drop_tokens_mode + in: query + schema: + $ref: '#/components/schemas/DropTokensMode' + - name: typo_tokens_threshold + in: query + schema: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + type: integer + - name: enable_typos_for_alpha_numerical_tokens + in: query + schema: + type: boolean + description: | + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + - name: filter_curated_hits + in: query + schema: + type: boolean + description: | + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + - name: enable_synonyms + in: query + schema: + type: boolean + description: | + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + - name: synonym_prefix + in: query + schema: + type: boolean + description: | + Allow synonym resolution on word prefixes in the query. Default: false + - name: synonym_num_typos + in: query + schema: + type: integer + description: | + Allow synonym resolution on typo-corrected words in the query. Default: 0 + - name: pinned_hits + in: query + schema: + description: | + A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + - name: hidden_hits + in: query + schema: + description: | + A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + - name: override_tags + in: query + schema: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + - name: highlight_fields + in: query + schema: + description: | + A list of custom fields that must be highlighted even if you don't query for them + type: string + - name: pre_segmented_query + in: query + schema: + description: | + You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. + Set this parameter to true to do the same + type: boolean + default: false + - name: preset + in: query + schema: + description: | + Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + type: string + - name: enable_overrides + in: query + schema: + description: | + If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + type: boolean + default: false + - name: prioritize_exact_match + in: query + schema: + description: | + Set this parameter to true to ensure that an exact match is ranked above the others + type: boolean + default: true + - name: prioritize_token_position + in: query + schema: + description: | + Make Typesense prioritize documents where the query words appear earlier in the text. + type: boolean + default: false + - name: prioritize_num_matching_fields + in: query + schema: + description: | + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + - name: enable_typos_for_numerical_tokens + in: query + schema: + description: | + Make Typesense disable typos for numerical tokens. + type: boolean + default: true + - name: exhaustive_search + in: query + schema: + description: | + Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + type: boolean + - name: search_cutoff_ms + in: query + schema: + description: | + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + type: integer + - name: use_cache + in: query + schema: + description: | + Enable server side caching of search query results. By default, caching is disabled. + type: boolean + - name: cache_ttl + in: query + schema: + description: | + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + type: integer + - name: min_len_1typo + in: query + schema: + description: | + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + - name: min_len_2typo + in: query + schema: + description: | + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + - name: vector_query + in: query + schema: + description: | + Vector query expression for fetching documents "closest" to a given query/document vector. + type: string + - name: remote_embedding_timeout_ms + in: query + schema: + description: | + Timeout (in milliseconds) for fetching remote embeddings. + type: integer + - name: remote_embedding_num_tries + in: query + schema: + description: | + Number of times to retry fetching remote embeddings. + type: integer + - name: facet_strategy + in: query + schema: + description: | + Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + type: string + - name: stopwords + in: query + schema: + description: | + Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + type: string + - name: facet_return_parent + in: query + schema: + description: | + Comma separated string of nested facet fields whose parent object should be returned in facet response. + type: string + - name: voice_query + in: query + schema: + description: | + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + - name: conversation + in: query + schema: + description: | + Enable conversational search. + type: boolean + - name: conversation_model_id + in: query + schema: + description: | + The Id of Conversation Model to be used. + type: string + - name: conversation_id + in: query + schema: + description: | + The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MultiSearchSearchesParameter' + responses: + '200': + description: Search results + content: + application/json: + schema: + $ref: '#/components/schemas/MultiSearchResult' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /analytics/events: + post: + tags: + - analytics + summary: Create an analytics event + description: Sending events for analytics e.g rank search results based on popularity. + operationId: createAnalyticsEvent + requestBody: + description: The Analytics event to be created + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventCreateSchema' + required: true + responses: + '201': + description: Analytics event successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventCreateResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /analytics/rules: + post: + tags: + - analytics + summary: Creates an analytics rule + description: When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. + operationId: createAnalyticsRule + requestBody: + description: The Analytics rule to be created + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRuleSchema' + required: true + responses: + '201': + description: Analytics rule successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRuleSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - analytics + summary: Retrieves all analytics rules + description: Retrieve the details of all analytics rules + operationId: retrieveAnalyticsRules + responses: + '200': + description: Analytics rules fetched + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRulesRetrieveSchema' + /analytics/rules/{ruleName}: + put: + tags: + - analytics + summary: Upserts an analytics rule + description: Upserts an analytics rule with the given name. + operationId: upsertAnalyticsRule + parameters: + - in: path + name: ruleName + description: The name of the analytics rule to upsert + schema: + type: string + required: true + requestBody: + description: The Analytics rule to be upserted + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRuleUpsertSchema' + required: true + responses: + '200': + description: Analytics rule successfully upserted + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRuleSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - analytics + summary: Retrieves an analytics rule + description: Retrieve the details of an analytics rule, given it's name + operationId: retrieveAnalyticsRule + parameters: + - in: path + name: ruleName + description: The name of the analytics rule to retrieve + schema: + type: string + required: true + responses: + '200': + description: Analytics rule fetched + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRuleSchema' + '404': + description: Analytics rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - analytics + summary: Delete an analytics rule + description: Permanently deletes an analytics rule, given it's name + operationId: deleteAnalyticsRule + parameters: + - in: path + name: ruleName + description: The name of the analytics rule to delete + schema: + type: string + required: true + responses: + '200': + description: Analytics rule deleted + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRuleDeleteResponse' + '404': + description: Analytics rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /metrics.json: + get: + tags: + - operations + summary: Get current RAM, CPU, Disk & Network usage metrics. + description: Retrieve the metrics. + operationId: retrieveMetrics + responses: + '200': + description: Metrics fetched. + content: + application/json: + schema: + type: object + /stats.json: + get: + tags: + - operations + summary: Get stats about API endpoints. + description: Retrieve the stats about API endpoints. + operationId: retrieveAPIStats + responses: + '200': + description: Stats fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/APIStatsResponse' + /stopwords: + get: + tags: + - stopwords + summary: Retrieves all stopwords sets. + description: Retrieve the details of all stopwords sets + operationId: retrieveStopwordsSets + responses: + '200': + description: Stopwords sets fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetsRetrieveAllSchema' + /stopwords/{setId}: + put: + tags: + - stopwords + summary: Upserts a stopwords set. + description: When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. + operationId: upsertStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to upsert. + schema: + type: string + required: true + example: countries + requestBody: + description: The stopwords set to upsert. + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetUpsertSchema' + required: true + responses: + '200': + description: Stopwords set successfully upserted. + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetSchema' + '400': + description: Bad request, see error message for details. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - stopwords + summary: Retrieves a stopwords set. + description: Retrieve the details of a stopwords set, given it's name. + operationId: retrieveStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to retrieve. + schema: + type: string + required: true + example: countries + responses: + '200': + description: Stopwords set fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetRetrieveSchema' + '404': + description: Stopwords set not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - stopwords + summary: Delete a stopwords set. + description: Permanently deletes a stopwords set, given it's name. + operationId: deleteStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to delete. + schema: + type: string + required: true + example: countries + responses: + '200': + description: Stopwords set rule deleted. + content: + application/json: + schema: + type: object + properties: + id: + type: string + required: + - id + example: | + {"id": "countries"} + '404': + description: Stopwords set not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /presets: + get: + tags: + - presets + summary: Retrieves all presets. + description: Retrieve the details of all presets + operationId: retrieveAllPresets + responses: + '200': + description: Presets fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetsRetrieveSchema' + /presets/{presetId}: + get: + tags: + - presets + summary: Retrieves a preset. + description: Retrieve the details of a preset, given it's name. + operationId: retrievePreset + parameters: + - in: path + name: presetId + description: The ID of the preset to retrieve. + schema: + type: string + required: true + example: listing_view + responses: + '200': + description: Preset fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetSchema' + '404': + description: Preset not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + put: + tags: + - presets + summary: Upserts a preset. + description: Create or update an existing preset. + operationId: upsertPreset + parameters: + - in: path + name: presetId + description: The name of the preset set to upsert. + schema: + type: string + required: true + example: listing_view + requestBody: + description: The stopwords set to upsert. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetUpsertSchema' + required: true + responses: + '200': + description: Preset successfully upserted. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - presets + summary: Delete a preset. + description: Permanently deletes a preset, given it's name. + operationId: deletePreset + parameters: + - in: path + name: presetId + description: The ID of the preset to delete. + schema: + type: string + required: true + example: listing_view + responses: + '200': + description: Preset deleted. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetDeleteSchema' + '404': + description: Preset not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /stemming/dictionaries: + get: + tags: + - stemming + summary: List all stemming dictionaries + description: Retrieve a list of all available stemming dictionaries. + operationId: listStemmingDictionaries + responses: + '200': + description: List of all dictionaries + content: + application/json: + schema: + type: object + properties: + dictionaries: + type: array + items: + type: string + example: + - irregular-plurals + - company-terms + /stemming/dictionaries/{dictionaryId}: + get: + tags: + - stemming + summary: Retrieve a stemming dictionary + description: Fetch details of a specific stemming dictionary. + operationId: getStemmingDictionary + parameters: + - name: dictionaryId + in: path + description: The ID of the dictionary to retrieve + required: true + schema: + type: string + example: irregular-plurals + responses: + '200': + description: Stemming dictionary details + content: + application/json: + schema: + $ref: '#/components/schemas/StemmingDictionary' + '404': + description: Dictionary not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /stemming/dictionaries/import: + post: + tags: + - stemming + summary: Import a stemming dictionary + description: Upload a JSONL file containing word mappings to create or update a stemming dictionary. + operationId: importStemmingDictionary + parameters: + - name: id + in: query + description: The ID to assign to the dictionary + required: true + schema: + type: string + example: irregular-plurals + requestBody: + description: The JSONL file containing word mappings + required: true + content: + application/json: + schema: + type: string + example: | + {"word": "people", "root": "person"} + {"word": "children", "root": "child"} + responses: + '200': + description: Dictionary successfully imported + content: + application/octet-stream: + schema: + type: string + example: | + {"word": "people", "root": "person"} {"word": "children", "root": "child"} + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /nl_search_models: + get: + tags: + - nl_search_models + summary: List all NL search models + description: Retrieve all NL search models. + operationId: retrieveAllNLSearchModels + responses: + '200': + description: List of all NL search models + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/NLSearchModelSchema' + post: + tags: + - nl_search_models + summary: Create a NL search model + description: Create a new NL search model. + operationId: createNLSearchModel + requestBody: + description: The NL search model to be created + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelCreateSchema' + required: true + responses: + '201': + description: NL search model successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /nl_search_models/{modelId}: + get: + tags: + - nl_search_models + summary: Retrieve a NL search model + description: Retrieve a specific NL search model by its ID. + operationId: retrieveNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to retrieve + required: true + schema: + type: string + responses: + '200': + description: NL search model fetched + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + put: + tags: + - nl_search_models + summary: Update a NL search model + description: Update an existing NL search model. + operationId: updateNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to update + required: true + schema: + type: string + requestBody: + description: The NL search model fields to update + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelUpdateSchema' + required: true + responses: + '200': + description: NL search model successfully updated + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - nl_search_models + summary: Delete a NL search model + description: Delete a specific NL search model by its ID. + operationId: deleteNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to delete + required: true + schema: + type: string + responses: + '200': + description: NL search model successfully deleted + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelDeleteSchema' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' +components: + schemas: + CollectionSchema: + required: + - name + - fields + type: object + properties: + name: + type: string + description: Name of the collection + example: companies + fields: + type: array + description: A list of fields for querying, filtering and faceting + example: + - name: num_employees + type: int32 + facet: false + - name: company_name + type: string + facet: false + - name: country + type: string + facet: true + items: + $ref: '#/components/schemas/Field' + default_sorting_field: + type: string + description: The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. + example: num_employees + default: '' + token_separators: + type: array + description: | + List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + items: + type: string + minLength: 1 + maxLength: 1 + default: [] + enable_nested_fields: + type: boolean + description: Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. + default: false + example: true + symbols_to_index: + type: array + description: | + List of symbols or special characters to be indexed. + items: + type: string + minLength: 1 + maxLength: 1 + default: [] + voice_query_model: + $ref: '#/components/schemas/VoiceQueryModelCollectionConfig' + CollectionUpdateSchema: + required: + - fields + type: object + properties: + fields: + type: array + description: A list of fields for querying, filtering and faceting + example: + - name: company_name + type: string + facet: false + - name: num_employees + type: int32 + facet: false + - name: country + type: string + facet: true + items: + $ref: '#/components/schemas/Field' + CollectionResponse: + allOf: + - $ref: '#/components/schemas/CollectionSchema' + - type: object + required: + - num_documents + - created_at + properties: + num_documents: + type: integer + description: Number of documents in the collection + format: int64 + readOnly: true + created_at: + type: integer + description: Timestamp of when the collection was created (Unix epoch in seconds) + format: int64 + readOnly: true + Field: + required: + - name + - type + type: object + properties: + name: + type: string + example: company_name + type: + type: string + example: string + optional: + type: boolean + example: true + facet: + type: boolean + example: false + index: + type: boolean + example: true + default: true + locale: + type: string + example: el + sort: + type: boolean + example: true + infix: + type: boolean + example: true + default: false + reference: + type: string + description: | + Name of a field in another collection that should be linked to this collection so that it can be joined during query. + num_dim: + type: integer + example: 256 + drop: + type: boolean + example: true + store: + type: boolean + description: | + When set to false, the field value will not be stored on disk. Default: true. + vec_dist: + type: string + description: | + The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. + range_index: + type: boolean + description: | + Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. + stem: + type: boolean + description: | + Values are stemmed before indexing in-memory. Default: false. + stem_dictionary: + type: string + description: Name of the stemming dictionary to use for this field + example: irregular-plurals + token_separators: + type: array + description: | + List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + items: + type: string + minLength: 1 + maxLength: 1 + default: [] + symbols_to_index: + type: array + description: | + List of symbols or special characters to be indexed. + items: + type: string + minLength: 1 + maxLength: 1 + default: [] + embed: + type: object + required: + - from + - model_config + properties: + from: + type: array + items: + type: string + model_config: + type: object + required: + - model_name + properties: + model_name: + type: string + api_key: + type: string + url: + type: string + access_token: + type: string + refresh_token: + type: string + client_id: + type: string + client_secret: + type: string + project_id: + type: string + indexing_prefix: + type: string + query_prefix: + type: string + VoiceQueryModelCollectionConfig: + type: object + description: | + Configuration for the voice query model + properties: + model_name: + type: string + example: ts/whisper/base.en + CollectionAliasSchema: + type: object + required: + - collection_name + properties: + collection_name: + type: string + description: Name of the collection you wish to map the alias to + CollectionAlias: + type: object + required: + - collection_name + - name + properties: + name: + type: string + readOnly: true + description: Name of the collection alias + collection_name: + type: string + description: Name of the collection the alias mapped to + CollectionAliasesResponse: + type: object + required: + - aliases + properties: + aliases: + type: array + x-go-type: '[]*CollectionAlias' + items: + $ref: '#/components/schemas/CollectionAlias' + SearchResult: + type: object + properties: + facet_counts: + type: array + items: + $ref: '#/components/schemas/FacetCounts' + found: + type: integer + description: The number of documents found + found_docs: + type: integer + search_time_ms: + type: integer + description: The number of milliseconds the search took + out_of: + type: integer + description: The total number of documents in the collection + search_cutoff: + type: boolean + description: Whether the search was cut off + page: + type: integer + description: The search result page number + grouped_hits: + type: array + items: + $ref: '#/components/schemas/SearchGroupedHit' + hits: + type: array + description: The documents that matched the search query + items: + $ref: '#/components/schemas/SearchResultHit' + request_params: + type: object + required: + - collection_name + - q + - per_page + properties: + collection_name: + type: string + q: + type: string + per_page: + type: integer + voice_query: + type: object + properties: + transcribed_query: + type: string + conversation: + $ref: '#/components/schemas/SearchResultConversation' + SearchResultConversation: + type: object + required: + - answer + - conversation_history + - conversation_id + - query + properties: + answer: + type: string + conversation_history: + type: array + items: + type: object + conversation_id: + type: string + query: + type: string + SearchGroupedHit: + type: object + required: + - group_key + - hits + properties: + found: + type: integer + group_key: + type: array + items: {} + hits: + type: array + description: The documents that matched the search query + items: + $ref: '#/components/schemas/SearchResultHit' + SearchResultHit: + type: object + properties: + highlights: + type: array + description: (Deprecated) Contains highlighted portions of the search fields + items: + $ref: '#/components/schemas/SearchHighlight' + highlight: + type: object + description: Highlighted version of the matching document + additionalProperties: true + document: + type: object + description: Can be any key-value pair + text_match: + type: integer + format: int64 + text_match_info: + type: object + properties: + best_field_score: + type: string + best_field_weight: + type: integer + fields_matched: + type: integer + num_tokens_dropped: + type: integer + format: int64 + x-go-type: uint64 + score: + type: string + tokens_matched: + type: integer + typo_prefix_score: + type: integer + geo_distance_meters: + type: object + description: Can be any key-value pair + additionalProperties: + type: integer + vector_distance: + type: number + format: float + description: Distance between the query vector and matching document's vector value + example: + highlights: + company_name: + field: company_name + snippet: Stark Industries + document: + id: '124' + company_name: Stark Industries + num_employees: 5215 + country: USA + text_match: 1234556 + SearchHighlight: + type: object + properties: + field: + type: string + example: company_name + snippet: + type: string + description: Present only for (non-array) string fields + example: Stark Industries + snippets: + type: array + description: Present only for (array) string[] fields + example: + - Stark Industries + - Stark Corp + items: + type: string + value: + type: string + description: Full field value with highlighting, present only for (non-array) string fields + example: Stark Industries is a major supplier of space equipment. + values: + type: array + description: Full field value with highlighting, present only for (array) string[] fields + example: + - Stark Industries + - Stark Corp + items: + type: string + indices: + type: array + description: The indices property will be present only for string[] fields and will contain the corresponding indices of the snippets in the search field + example: 1 + items: + type: integer + matched_tokens: + type: array + items: + type: object + x-go-type: interface{} + SearchOverrideSchema: + type: object + required: + - rule + properties: + rule: + $ref: '#/components/schemas/SearchOverrideRule' + includes: + type: array + description: List of document `id`s that should be included in the search results with their corresponding `position`s. + items: + $ref: '#/components/schemas/SearchOverrideInclude' + excludes: + type: array + description: List of document `id`s that should be excluded from the search results. + items: + $ref: '#/components/schemas/SearchOverrideExclude' + filter_by: + type: string + description: | + A filter by clause that is applied to any search query that matches the override rule. + remove_matched_tokens: + type: boolean + description: | + Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + metadata: + type: object + description: | + Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + sort_by: + type: string + description: | + A sort by clause that is applied to any search query that matches the override rule. + replace_query: + type: string + description: | + Replaces the current search query with this value, when the search query matches the override rule. + filter_curated_hits: + type: boolean + description: | + When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + effective_from_ts: + type: integer + description: | + A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + effective_to_ts: + type: integer + description: | + A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + stop_processing: + type: boolean + description: | + When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + SearchOverride: + allOf: + - $ref: '#/components/schemas/SearchOverrideSchema' + - type: object + required: + - id + properties: + id: + type: string + readOnly: true + SearchOverrideDeleteResponse: + type: object + required: + - id + properties: + id: + type: string + description: The id of the override that was deleted + SearchOverrideRule: + type: object + properties: + tags: + type: array + description: List of tag values to associate with this override rule. + items: + type: string + query: + type: string + description: Indicates what search queries should be overridden + match: + type: string + description: | + Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. + enum: + - exact + - contains + filter_by: + type: string + description: | + Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). + SearchOverrideInclude: + type: object + required: + - id + - position + properties: + id: + type: string + description: document id that should be included + position: + type: integer + description: position number where document should be included in the search results + SearchOverrideExclude: + type: object + required: + - id + properties: + id: + type: string + description: document id that should be excluded from the search results. + SearchOverridesResponse: + type: object + required: + - overrides + properties: + overrides: + type: array + x-go-type: '[]*SearchOverride' + items: + $ref: '#/components/schemas/SearchOverride' + SearchSynonymSchema: + type: object + required: + - synonyms + properties: + root: + type: string + description: For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. + synonyms: + type: array + description: Array of words that should be considered as synonyms. + items: + type: string + locale: + type: string + description: Locale for the synonym, leave blank to use the standard tokenizer. + symbols_to_index: + type: array + description: By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. + items: + type: string + SearchSynonym: + allOf: + - $ref: '#/components/schemas/SearchSynonymSchema' + - type: object + required: + - id + properties: + id: + type: string + readOnly: true + SearchSynonymDeleteResponse: + type: object + required: + - id + properties: + id: + type: string + description: The id of the synonym that was deleted + SearchSynonymsResponse: + type: object + required: + - synonyms + properties: + synonyms: + type: array + x-go-type: '[]*SearchSynonym' + items: + $ref: '#/components/schemas/SearchSynonym' + HealthStatus: + type: object + required: + - ok + properties: + ok: + type: boolean + SchemaChangeStatus: + type: object + properties: + collection: + type: string + description: Name of the collection being modified + validated_docs: + type: integer + description: Number of documents that have been validated + altered_docs: + type: integer + description: Number of documents that have been altered + SuccessStatus: + type: object + required: + - success + properties: + success: + type: boolean + ApiResponse: + type: object + required: + - message + properties: + message: + type: string + ApiKeySchema: + type: object + required: + - actions + - collections + - description + properties: + value: + type: string + description: + type: string + actions: + type: array + items: + type: string + collections: + type: array + items: + type: string + expires_at: + type: integer + format: int64 + ApiKey: + allOf: + - $ref: '#/components/schemas/ApiKeySchema' + - type: object + properties: + id: + type: integer + format: int64 + readOnly: true + value_prefix: + type: string + readOnly: true + ApiKeyDeleteResponse: + type: object + required: + - id + properties: + id: + type: integer + format: int64 + description: The id of the API key that was deleted + ApiKeysResponse: + type: object + required: + - keys + properties: + keys: + type: array + x-go-type: '[]*ApiKey' + items: + $ref: '#/components/schemas/ApiKey' + ScopedKeyParameters: + type: object + properties: + filter_by: + type: string + expires_at: + type: integer + format: int64 + SnapshotParameters: + type: object + properties: + snapshot_path: + type: string + ErrorResponse: + type: object + properties: + message: + type: string + MultiSearchResult: + type: object + required: + - results + properties: + results: + type: array + items: + $ref: '#/components/schemas/MultiSearchResultItem' + conversation: + $ref: '#/components/schemas/SearchResultConversation' + MultiSearchResultItem: + allOf: + - $ref: '#/components/schemas/SearchResult' + - type: object + properties: + code: + type: integer + description: HTTP error code + format: int64 + error: + type: string + description: Error description + SearchParameters: + type: object + properties: + q: + description: The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. + type: string + query_by: + description: A list of `string` fields that should be queried against. Multiple fields are separated with a comma. + type: string + nl_query: + description: Whether to use natural language processing to parse the query. + type: boolean + nl_model_id: + description: The ID of the natural language model to use. + type: string + query_by_weights: + description: The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. + type: string + text_match_type: + description: In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. + type: string + prefix: + description: Boolean field to indicate that the last word in the query should be treated as a prefix, and not as a whole word. This is used for building autocomplete and instant search interfaces. Defaults to true. + type: string + infix: + description: If infix index is enabled for this field, infix searching can be done on a per-field basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default `always` infix search is performed along with regular search `fallback` infix search is performed if regular search does not produce results + type: string + max_extra_prefix: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + max_extra_suffix: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + filter_by: + description: Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. + type: string + example: 'num_employees:>100 && country: [USA, UK]' + max_filter_by_candidates: + description: Controls the number of similar words that Typesense considers during fuzzy search on filter_by values. Useful for controlling prefix matches like company_name:Acm*. + type: integer + sort_by: + description: A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` + type: string + example: num_employees:desc + facet_by: + description: A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. + type: string + max_facet_values: + description: Maximum number of facet values to be returned. + type: integer + facet_query: + description: Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix "shoe". + type: string + num_typos: + description: | + The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + type: string + page: + description: Results from this specific page number would be fetched. + type: integer + per_page: + description: 'Number of results to fetch per page. Default: 10' + type: integer + limit: + description: | + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + type: integer + offset: + description: Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. + type: integer + group_by: + description: You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. + type: string + group_limit: + description: | + Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + type: integer + group_missing_values: + description: | + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + type: boolean + include_fields: + description: List of fields from the document to include in the search result + type: string + exclude_fields: + description: List of fields from the document to exclude in the search result + type: string + highlight_full_fields: + description: List of fields which should be highlighted fully without snippeting + type: string + highlight_affix_num_tokens: + description: | + The number of tokens that should surround the highlighted text on each side. Default: 4 + type: integer + highlight_start_tag: + description: | + The start tag used for the highlighted snippets. Default: `` + type: string + highlight_end_tag: + description: | + The end tag used for the highlighted snippets. Default: `` + type: string + enable_highlight_v1: + description: | + Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true + type: boolean + default: true + snippet_threshold: + description: | + Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + type: integer + drop_tokens_threshold: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + type: integer + drop_tokens_mode: + $ref: '#/components/schemas/DropTokensMode' + typo_tokens_threshold: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + type: integer + enable_typos_for_alpha_numerical_tokens: + type: boolean + description: | + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + filter_curated_hits: + type: boolean + description: | + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + enable_synonyms: + type: boolean + description: | + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + synonym_prefix: + type: boolean + description: | + Allow synonym resolution on word prefixes in the query. Default: false + synonym_num_typos: + type: integer + description: | + Allow synonym resolution on typo-corrected words in the query. Default: 0 + pinned_hits: + description: | + A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + hidden_hits: + description: | + A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + override_tags: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + highlight_fields: + description: | + A list of custom fields that must be highlighted even if you don't query for them + type: string + split_join_tokens: + description: | + Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. + type: string + pre_segmented_query: + description: | + You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. + Set this parameter to true to do the same + type: boolean + preset: + description: | + Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + type: string + enable_overrides: + description: | + If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + type: boolean + default: false + prioritize_exact_match: + description: | + Set this parameter to true to ensure that an exact match is ranked above the others + type: boolean + default: true + max_candidates: + description: | + Control the number of words that Typesense considers for typo and prefix searching. + type: integer + prioritize_token_position: + description: | + Make Typesense prioritize documents where the query words appear earlier in the text. + type: boolean + default: false + prioritize_num_matching_fields: + description: | + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + enable_typos_for_numerical_tokens: + description: | + Make Typesense disable typos for numerical tokens. + type: boolean + default: true + exhaustive_search: + description: | + Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + type: boolean + search_cutoff_ms: + description: | + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + type: integer + use_cache: + description: | + Enable server side caching of search query results. By default, caching is disabled. + type: boolean + cache_ttl: + description: | + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + type: integer + min_len_1typo: + description: | + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + min_len_2typo: + description: | + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + vector_query: + description: | + Vector query expression for fetching documents "closest" to a given query/document vector. + type: string + remote_embedding_timeout_ms: + description: | + Timeout (in milliseconds) for fetching remote embeddings. + type: integer + remote_embedding_num_tries: + description: | + Number of times to retry fetching remote embeddings. + type: integer + facet_strategy: + description: | + Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + type: string + stopwords: + description: | + Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + type: string + facet_return_parent: + description: | + Comma separated string of nested facet fields whose parent object should be returned in facet response. + type: string + voice_query: + description: | + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + conversation: + description: | + Enable conversational search. + type: boolean + conversation_model_id: + description: | + The Id of Conversation Model to be used. + type: string + conversation_id: + description: | + The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + type: string + MultiSearchParameters: + description: | + Parameters for the multi search API. + type: object + properties: + q: + description: The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. + type: string + query_by: + description: A list of `string` fields that should be queried against. Multiple fields are separated with a comma. + type: string + query_by_weights: + description: The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. + type: string + text_match_type: + description: In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. + type: string + prefix: + description: Boolean field to indicate that the last word in the query should be treated as a prefix, and not as a whole word. This is used for building autocomplete and instant search interfaces. Defaults to true. + type: string + infix: + description: If infix index is enabled for this field, infix searching can be done on a per-field basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default `always` infix search is performed along with regular search `fallback` infix search is performed if regular search does not produce results + type: string + max_extra_prefix: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + max_extra_suffix: + description: There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. + type: integer + filter_by: + description: Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. + type: string + example: 'num_employees:>100 && country: [USA, UK]' + sort_by: + description: A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` + type: string + facet_by: + description: A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. + type: string + max_facet_values: + description: Maximum number of facet values to be returned. + type: integer + facet_query: + description: Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix "shoe". + type: string + num_typos: + description: | + The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + type: string + page: + description: Results from this specific page number would be fetched. + type: integer + per_page: + description: 'Number of results to fetch per page. Default: 10' + type: integer + limit: + description: | + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + type: integer + offset: + description: Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. + type: integer + group_by: + description: You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. + type: string + group_limit: + description: | + Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + type: integer + group_missing_values: + description: | + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + type: boolean + include_fields: + description: List of fields from the document to include in the search result + type: string + exclude_fields: + description: List of fields from the document to exclude in the search result + type: string + highlight_full_fields: + description: List of fields which should be highlighted fully without snippeting + type: string + highlight_affix_num_tokens: + description: | + The number of tokens that should surround the highlighted text on each side. Default: 4 + type: integer + highlight_start_tag: + description: | + The start tag used for the highlighted snippets. Default: `` + type: string + highlight_end_tag: + description: | + The end tag used for the highlighted snippets. Default: `` + type: string + snippet_threshold: + description: | + Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + type: integer + drop_tokens_threshold: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + type: integer + drop_tokens_mode: + $ref: '#/components/schemas/DropTokensMode' + typo_tokens_threshold: + description: | + If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + type: integer + enable_typos_for_alpha_numerical_tokens: + type: boolean + description: | + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + filter_curated_hits: + type: boolean + description: | + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + enable_synonyms: + type: boolean + description: | + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + synonym_prefix: + type: boolean + description: | + Allow synonym resolution on word prefixes in the query. Default: false + synonym_num_typos: + type: integer + description: | + Allow synonym resolution on typo-corrected words in the query. Default: 0 + pinned_hits: + description: | + A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + hidden_hits: + description: | + A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. + You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + type: string + override_tags: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + highlight_fields: + description: | + A list of custom fields that must be highlighted even if you don't query for them + type: string + pre_segmented_query: + description: | + You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. + Set this parameter to true to do the same + type: boolean + default: false + preset: + description: | + Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + type: string + enable_overrides: + description: | + If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + type: boolean + default: false + prioritize_exact_match: + description: | + Set this parameter to true to ensure that an exact match is ranked above the others + type: boolean + default: true + prioritize_token_position: + description: | + Make Typesense prioritize documents where the query words appear earlier in the text. + type: boolean + default: false + prioritize_num_matching_fields: + description: | + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + enable_typos_for_numerical_tokens: + description: | + Make Typesense disable typos for numerical tokens. + type: boolean + default: true + exhaustive_search: + description: | + Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + type: boolean + search_cutoff_ms: + description: | + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + type: integer + use_cache: + description: | + Enable server side caching of search query results. By default, caching is disabled. + type: boolean + cache_ttl: + description: | + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + type: integer + min_len_1typo: + description: | + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + min_len_2typo: + description: | + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + type: integer + vector_query: + description: | + Vector query expression for fetching documents "closest" to a given query/document vector. + type: string + remote_embedding_timeout_ms: + description: | + Timeout (in milliseconds) for fetching remote embeddings. + type: integer + remote_embedding_num_tries: + description: | + Number of times to retry fetching remote embeddings. + type: integer + facet_strategy: + description: | + Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + type: string + stopwords: + description: | + Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + type: string + facet_return_parent: + description: | + Comma separated string of nested facet fields whose parent object should be returned in facet response. + type: string + voice_query: + description: | + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + conversation: + description: | + Enable conversational search. + type: boolean + conversation_model_id: + description: | + The Id of Conversation Model to be used. + type: string + conversation_id: + description: | + The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + type: string + MultiSearchSearchesParameter: + type: object + required: + - searches + properties: + union: + type: boolean + description: When true, merges the search results from each search query into a single ordered set of hits. + searches: + type: array + items: + $ref: '#/components/schemas/MultiSearchCollectionParameters' + MultiSearchCollectionParameters: + allOf: + - $ref: '#/components/schemas/MultiSearchParameters' + - type: object + properties: + collection: + type: string + description: | + The collection to search in. + x-typesense-api-key: + type: string + description: A separate search API key for each search within a multi_search request + rerank_hybrid_matches: + type: boolean + description: | + When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. + default: false + FacetCounts: + type: object + properties: + counts: + type: array + items: + type: object + properties: + count: + type: integer + highlighted: + type: string + value: + type: string + parent: + type: object + field_name: + type: string + stats: + type: object + properties: + max: + type: number + format: double + min: + type: number + format: double + sum: + type: number + format: double + total_values: + type: integer + avg: + type: number + format: double + AnalyticsEventCreateResponse: + type: object + required: + - ok + properties: + ok: + type: boolean + AnalyticsEventCreateSchema: + type: object + required: + - type + - name + - data + properties: + type: + type: string + name: + type: string + data: + type: object + AnalyticsRuleUpsertSchema: + type: object + required: + - type + - params + properties: + type: + type: string + enum: + - popular_queries + - nohits_queries + - counter + params: + $ref: '#/components/schemas/AnalyticsRuleParameters' + AnalyticsRuleParameters: + type: object + required: + - source + - destination + properties: + source: + $ref: '#/components/schemas/AnalyticsRuleParametersSource' + destination: + $ref: '#/components/schemas/AnalyticsRuleParametersDestination' + limit: + type: integer + expand_query: + type: boolean + AnalyticsRuleParametersSource: + type: object + required: + - collections + properties: + collections: + type: array + items: + type: string + events: + type: array + items: + type: object + required: + - type + - weight + - name + properties: + type: + type: string + weight: + type: number + format: float + name: + type: string + AnalyticsRuleParametersDestination: + type: object + required: + - collection + properties: + collection: + type: string + counter_field: + type: string + AnalyticsRuleDeleteResponse: + type: object + required: + - name + properties: + name: + type: string + AnalyticsRuleSchema: + allOf: + - $ref: '#/components/schemas/AnalyticsRuleUpsertSchema' + - type: object + required: + - name + properties: + name: + type: string + AnalyticsRulesRetrieveSchema: + type: object + properties: + rules: + type: array + items: + $ref: '#/components/schemas/AnalyticsRuleSchema' + x-go-type: '[]*AnalyticsRuleSchema' + APIStatsResponse: + type: object + properties: + delete_latency_ms: + type: number + format: double + delete_requests_per_second: + type: number + format: double + import_latency_ms: + type: number + format: double + import_requests_per_second: + type: number + format: double + latency_ms: + type: object + x-go-type: map[string]float64 + overloaded_requests_per_second: + type: number + format: double + pending_write_batches: + type: number + format: double + requests_per_second: + type: object + x-go-type: map[string]float64 + search_latency_ms: + type: number + format: double + search_requests_per_second: + type: number + format: double + total_requests_per_second: + type: number + format: double + write_latency_ms: + type: number + format: double + write_requests_per_second: + type: number + format: double + StopwordsSetUpsertSchema: + type: object + properties: + stopwords: + type: array + items: + type: string + locale: + type: string + required: + - stopwords + example: | + {"stopwords": ["Germany", "France", "Italy"], "locale": "en"} + StopwordsSetSchema: + type: object + properties: + id: + type: string + stopwords: + type: array + items: + type: string + locale: + type: string + required: + - id + - stopwords + example: | + {"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"} + StopwordsSetRetrieveSchema: + type: object + properties: + stopwords: + $ref: '#/components/schemas/StopwordsSetSchema' + required: + - stopwords + example: | + {"stopwords": {"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"}} + StopwordsSetsRetrieveAllSchema: + type: object + properties: + stopwords: + type: array + items: + $ref: '#/components/schemas/StopwordsSetSchema' + required: + - stopwords + example: | + {"stopwords": [{"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"}]} + PresetUpsertSchema: + properties: + value: + oneOf: + - $ref: '#/components/schemas/SearchParameters' + - $ref: '#/components/schemas/MultiSearchSearchesParameter' + required: + - value + PresetSchema: + allOf: + - $ref: '#/components/schemas/PresetUpsertSchema' + - type: object + required: + - name + properties: + name: + type: string + PresetsRetrieveSchema: + type: object + required: + - presets + properties: + presets: + type: array + items: + $ref: '#/components/schemas/PresetSchema' + x-go-type: '[]*PresetSchema' + PresetDeleteSchema: + type: object + required: + - name + properties: + name: + type: string + DocumentIndexParameters: + type: object + properties: + dirty_values: + $ref: '#/components/schemas/DirtyValues' + DirtyValues: + type: string + enum: + - coerce_or_reject + - coerce_or_drop + - drop + - reject + IndexAction: + type: string + enum: + - create + - update + - upsert + - emplace + DropTokensMode: + type: string + enum: + - right_to_left + - left_to_right + - both_sides:3 + description: | + Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries upto 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left + ConversationModelCreateSchema: + required: + - model_name + - max_bytes + allOf: + - $ref: '#/components/schemas/ConversationModelUpdateSchema' + - type: object + required: + - model_name + - max_bytes + - history_collection + properties: + model_name: + description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM + type: string + max_bytes: + description: | + The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + type: integer + history_collection: + type: string + description: Typesense collection that stores the historical conversations + ConversationModelUpdateSchema: + type: object + properties: + id: + type: string + description: An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + model_name: + description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM + type: string + api_key: + description: The LLM service's API Key + type: string + history_collection: + type: string + description: Typesense collection that stores the historical conversations + account_id: + description: LLM service's account ID (only applicable for Cloudflare) + type: string + system_prompt: + description: The system prompt that contains special instructions to the LLM + type: string + ttl: + type: integer + description: | + Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + max_bytes: + description: | + The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + type: integer + vllm_url: + description: URL of vLLM service + type: string + ConversationModelSchema: + allOf: + - $ref: '#/components/schemas/ConversationModelCreateSchema' + - type: object + required: + - id + properties: + id: + type: string + description: An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + StemmingDictionary: + type: object + required: + - id + - words + properties: + id: + type: string + description: Unique identifier for the dictionary + example: irregular-plurals + words: + type: array + description: List of word mappings in the dictionary + items: + type: object + required: + - word + - root + properties: + word: + type: string + description: The word form to be stemmed + example: people + root: + type: string + description: The root form of the word + example: person + NLSearchModelBase: + type: object + properties: + model_name: + type: string + description: Name of the NL model to use + api_key: + type: string + description: API key for the NL model service + api_url: + type: string + description: Custom API URL for the NL model service + max_bytes: + type: integer + description: Maximum number of bytes to process + temperature: + type: number + description: Temperature parameter for the NL model + system_prompt: + type: string + description: System prompt for the NL model + top_p: + type: number + description: Top-p parameter for the NL model (Google-specific) + top_k: + type: integer + description: Top-k parameter for the NL model (Google-specific) + stop_sequences: + type: array + items: + type: string + description: Stop sequences for the NL model (Google-specific) + api_version: + type: string + description: API version for the NL model service + project_id: + type: string + description: Project ID for GCP Vertex AI + access_token: + type: string + description: Access token for GCP Vertex AI + refresh_token: + type: string + description: Refresh token for GCP Vertex AI + client_id: + type: string + description: Client ID for GCP Vertex AI + client_secret: + type: string + description: Client secret for GCP Vertex AI + region: + type: string + description: Region for GCP Vertex AI + max_output_tokens: + type: integer + description: Maximum output tokens for GCP Vertex AI + account_id: + type: string + description: Account ID for Cloudflare-specific models + NLSearchModelCreateSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelBase' + - type: object + properties: + id: + type: string + description: Optional ID for the NL search model + NLSearchModelSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelCreateSchema' + - type: object + required: + - id + properties: + id: + type: string + description: ID of the NL search model + NLSearchModelUpdateSchema: + $ref: '#/components/schemas/NLSearchModelCreateSchema' + NLSearchModelDeleteSchema: + type: object + required: + - id + properties: + id: + type: string + description: ID of the deleted NL search model + ImportDocumentsParameters: + type: object + properties: + batch_size: + type: integer + return_id: + type: boolean + description: Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. + remote_embedding_batch_size: + type: integer + return_doc: + type: boolean + action: + $ref: '#/components/schemas/IndexAction' + dirty_values: + $ref: '#/components/schemas/DirtyValues' + ExportDocumentsParameters: + type: object + properties: + filter_by: + description: Filter conditions for refining your search results. Separate multiple conditions with &&. + type: string + include_fields: + description: List of fields from the document to include in the search result + type: string + exclude_fields: + description: List of fields from the document to exclude in the search result + type: string + UpdateDocumentsParameters: + type: object + properties: + filter_by: + type: string + example: 'num_employees:>100 && country: [USA, UK]' + DeleteDocumentsParameters: + type: object + required: + - filter_by + properties: + filter_by: + type: string + example: 'num_employees:>100 && country: [USA, UK]' + batch_size: + description: Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. + type: integer + ignore_not_found: + type: boolean + truncate: + description: When true, removes all documents from the collection while preserving the collection and its schema. + type: boolean + securitySchemes: + api_key_header: + type: apiKey + name: X-TYPESENSE-API-KEY + in: header diff --git a/typesense/Cargo.toml b/typesense/Cargo.toml index b09567f..9106a53 100644 --- a/typesense/Cargo.toml +++ b/typesense/Cargo.toml @@ -2,7 +2,7 @@ name = "typesense" version = "0.1.0" authors = ["Typesense "] -edition = "2018" +edition = "2021" license = "Apache-2.0" description = "WIP client for typesense" repository = "https://github.com/typesense/typesense-rust" @@ -26,10 +26,17 @@ serde_json = "1.0" sha2 = "0.10" typesense_derive = { version = "0.1.0", path = "../typesense_derive", optional = true } typesense_codegen = { version = "0.25.0", path = "../typesense_codegen" } +reqwest-retry = "0.7.0" +reqwest = { version = "0.12", features = ["json"] } +reqwest-middleware = { version = "0.4.2", features = ["json"] } +thiserror = "1.0" [dev-dependencies] dotenvy = "0.15" trybuild = "1.0.42" +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +wiremock = "0.5" +nanoid = "0.4" [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] tokio = { version = "1.5", features = ["macros", "rt", "rt-multi-thread"] } @@ -47,3 +54,7 @@ required-features = ["derive"] [[test]] name = "api_tests" path = "tests/api/lib.rs" + +[[test]] +name = "client" +path = "tests/client/mod.rs" \ No newline at end of file diff --git a/typesense/src/client/alias.rs b/typesense/src/client/alias.rs new file mode 100644 index 0000000..c49bf86 --- /dev/null +++ b/typesense/src/client/alias.rs @@ -0,0 +1,56 @@ +//! Provides access to the collection alias-related API endpoints. +//! +//! An `Alias` instance is created via the main `client.alias()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{collections_api, configuration}, + models, +}; + +/// Provides methods for interacting with a specific Typesense collection alias. +/// +/// This struct is created by calling `client.alias()`. +pub struct Alias<'a> { + pub(super) client: &'a Client, + pub(super) name: &'a str, +} + +impl<'a> Alias<'a> { + /// Creates a new `Alias` instance. + pub(super) fn new(client: &'a Client, name: &'a str) -> Self { + Self { client, name } + } + + /// Retrieves the details of a collection alias, including the collection it points to. + pub async fn retrieve( + &self, + ) -> Result> { + let params = collections_api::GetAliasParams { + alias_name: self.name.to_string(), + }; + + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { collections_api::get_alias(&config, params_for_move).await } + }) + .await + } + + /// Deletes a collection alias. + pub async fn delete( + &self, + ) -> Result> { + let params = collections_api::DeleteAliasParams { + alias_name: self.name.to_string(), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { collections_api::delete_alias(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/aliases.rs b/typesense/src/client/aliases.rs new file mode 100644 index 0000000..53594ce --- /dev/null +++ b/typesense/src/client/aliases.rs @@ -0,0 +1,61 @@ +//! Provides access to the collection aliases-related API endpoints. +//! +//! An `Aliases` instance is created via the main `client.aliases()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{collections_api, configuration}, + models, +}; + +/// Provides methods for interacting with Typesense collection aliases. +/// +/// This struct is created by calling `client.aliases()`. +pub struct Aliases<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Aliases<'a> { + /// Creates a new `Aliases` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Creates or updates a collection alias. + /// + /// An alias is a virtual collection name that points to a real collection. + /// Aliases are useful when you want to re-index your data in the background + /// on a new collection and then switch your application to it without any + /// changes to your code. + /// + /// # Arguments + /// * `schema` - A `CollectionAliasSchema` pointing to the target collection. + pub async fn upsert( + &self, + alias_name: &str, + schema: models::CollectionAliasSchema, + ) -> Result> { + let params = collections_api::UpsertAliasParams { + alias_name: alias_name.to_string(), + collection_alias_schema: Some(schema), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { collections_api::upsert_alias(&config, params_for_move).await } + }) + .await + } + + /// Lists all aliases and the corresponding collections that they map to. + pub async fn retrieve( + &self, + ) -> Result> { + self.client + .execute(|config: Arc| async move { + collections_api::get_aliases(&config).await + }) + .await + } +} diff --git a/typesense/src/client/analytics/events.rs b/typesense/src/client/analytics/events.rs new file mode 100644 index 0000000..55bafac --- /dev/null +++ b/typesense/src/client/analytics/events.rs @@ -0,0 +1,46 @@ +//! Provides access to the API endpoint for posting analytics events. +//! +//! An `Events` instance is created via the `Client::analytics().events()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{analytics_api, configuration}, + models, +}; + +/// Provides methods for interacting with analytics events. +/// +/// This struct is created by calling `client.analytics().events()`. +pub struct Events<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Events<'a> { + /// Creates a new `Events` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Posts an analytics event for tracking user behavior. + /// + /// This is useful for features like "search result ranking based on popularity." + /// + /// # Arguments + /// * `schema` - An `AnalyticsEventCreateSchema` object representing the event. + pub async fn create( + &self, + schema: models::AnalyticsEventCreateSchema, + ) -> Result> + { + let params = analytics_api::CreateAnalyticsEventParams { + analytics_event_create_schema: schema, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { analytics_api::create_analytics_event(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/analytics/mod.rs b/typesense/src/client/analytics/mod.rs new file mode 100644 index 0000000..cb49810 --- /dev/null +++ b/typesense/src/client/analytics/mod.rs @@ -0,0 +1,44 @@ +//! Provides access to the analytics API endpoints for managing rules and posting events. +//! +//! An `Analytics` instance is created via the main `Client::analytics()` method. +pub mod events; +pub mod rule; +pub mod rules; +use super::{Client, Error}; +pub use events::Events; +pub use rule::Rule; +pub use rules::Rules; + +/// Provides methods for interacting with Typesense analytics rules and events. +/// +/// This struct is created by calling `client.analytics()`. +pub struct Analytics<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Analytics<'a> { + /// Creates a new `Analytics` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Provides access to endpoints for managing a collection of analytics rules. + pub fn rules(&self) -> Rules<'a> { + Rules::new(self.client) + } + + /// Provides access to endpoints for managing a single analytics rule. + /// + /// # Arguments + /// * `rule_name` - The name of the analytics rule to manage. + pub fn rule(&self, rule_name: &'a str) -> Rule<'a> { + Rule::new(self.client, rule_name) + } + + /// Provides access to the endpoint for creating analytics events. + /// + /// Example: `client.analytics().events().create(...).await` + pub fn events(&self) -> Events<'a> { + Events::new(self.client) + } +} diff --git a/typesense/src/client/analytics/rule.rs b/typesense/src/client/analytics/rule.rs new file mode 100644 index 0000000..7fc8222 --- /dev/null +++ b/typesense/src/client/analytics/rule.rs @@ -0,0 +1,56 @@ +//! Provides access to the API endpoints for managing a single analytics rule. +//! +//! An `Rule` instance is created via the `Client::analytics().rule("rule_name")` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{analytics_api, configuration}, + models, +}; + +/// Provides methods for interacting with a specific analytics rule. +/// +/// This struct is created by calling `analytics.rule("rule_name")`. +pub struct Rule<'a> { + pub(super) client: &'a Client, + pub(super) rule_name: &'a str, +} + +impl<'a> Rule<'a> { + /// Creates a new `Rule` instance for a specific rule name. + pub(super) fn new(client: &'a Client, rule_name: &'a str) -> Self { + Self { client, rule_name } + } + + /// Retrieves the details of this specific analytics rule. + pub async fn retrieve( + &self, + ) -> Result> { + let params = analytics_api::RetrieveAnalyticsRuleParams { + rule_name: self.rule_name.to_string(), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { analytics_api::retrieve_analytics_rule(&config, params_for_move).await } + }) + .await + } + + /// Permanently deletes this specific analytics rule. + pub async fn delete( + &self, + ) -> Result> + { + let params = analytics_api::DeleteAnalyticsRuleParams { + rule_name: self.rule_name.to_string(), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { analytics_api::delete_analytics_rule(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/analytics/rules.rs b/typesense/src/client/analytics/rules.rs new file mode 100644 index 0000000..8425048 --- /dev/null +++ b/typesense/src/client/analytics/rules.rs @@ -0,0 +1,79 @@ +//! Provides access to the API endpoints for managing analytics rules. +//! +//! An `Rules` instance is created via the `Client::analytics().rules()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{analytics_api, configuration}, + models, +}; + +/// Provides methods for interacting with a collection of analytics rules. +/// +/// This struct is created by calling `client.analytics().rules()`. +pub struct Rules<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Rules<'a> { + /// Creates a new `Rules` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Creates a new analytics rule. + /// + /// # Arguments + /// * `schema` - An `AnalyticsRuleSchema` object describing the rule to be created. + pub async fn create( + &self, + schema: models::AnalyticsRuleSchema, + ) -> Result> { + let params = analytics_api::CreateAnalyticsRuleParams { + analytics_rule_schema: schema, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { analytics_api::create_analytics_rule(&config, params_for_move).await } + }) + .await + } + + /// Creates or updates an analytics rule with the given name. + /// + /// # Arguments + /// * `rule_name` - The name of the analytics rule to create or update. + /// * `schema` - An `AnalyticsRuleUpsertSchema` object with the rule's parameters. + pub async fn upsert( + &self, + rule_name: &str, + schema: models::AnalyticsRuleUpsertSchema, + ) -> Result> { + let params = analytics_api::UpsertAnalyticsRuleParams { + rule_name: rule_name.to_string(), + analytics_rule_upsert_schema: schema, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { analytics_api::upsert_analytics_rule(&config, params_for_move).await } + }) + .await + } + + /// Retrieves the details of all analytics rules. + pub async fn retrieve( + &self, + ) -> Result< + models::AnalyticsRulesRetrieveSchema, + Error, + > { + self.client + .execute(|config: Arc| async move { + analytics_api::retrieve_analytics_rules(&config).await + }) + .await + } +} diff --git a/typesense/src/client/collection/document.rs b/typesense/src/client/collection/document.rs new file mode 100644 index 0000000..8ff1cd5 --- /dev/null +++ b/typesense/src/client/collection/document.rs @@ -0,0 +1,85 @@ +//! Provides access to API endpoints for a single document within a Typesense collection. +//! +//! An instance of `Document` is scoped to a specific document and is created +//! via a parent `Collection` struct, for example: +//! `client.collection("collection_name").document("document_id")` + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::apis::{configuration, documents_api}; + +/// Provides methods for interacting with a single document within a specific Typesense collection. +/// +/// This struct is created by calling a method like `client.collection("collection_name").document("document_id")`. +pub struct Document<'a> { + pub(super) client: &'a Client, + pub(super) collection_name: &'a str, + pub(super) document_id: &'a str, +} + +impl<'a> Document<'a> { + /// Creates a new `Document` instance for a specific document ID. + /// This is intended for internal use by the parent `Documents` struct. + pub(super) fn new(client: &'a Client, collection_name: &'a str, document_id: &'a str) -> Self { + Self { + client, + collection_name, + document_id, + } + } + + /// Fetches this individual document from the collection. + pub async fn retrieve( + &self, + ) -> Result> { + let params = documents_api::GetDocumentParams { + collection_name: self.collection_name.to_string(), + document_id: self.document_id.to_string(), + }; + + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { documents_api::get_document(&config, params_for_move).await } + }) + .await + } + + /// Updates this individual document. The update can be partial. + /// + /// # Arguments + /// * `document` - A `serde_json::Value` containing the fields to update. + pub async fn update( + &self, + document: serde_json::Value, + ) -> Result> { + let params = documents_api::UpdateDocumentParams { + collection_name: self.collection_name.to_string(), + document_id: self.document_id.to_string(), + body: document, + dirty_values: None, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { documents_api::update_document(&config, params_for_move).await } + }) + .await + } + + /// Deletes this individual document from the collection. + pub async fn delete( + &self, + ) -> Result> { + let params = documents_api::DeleteDocumentParams { + collection_name: self.collection_name.to_string(), + document_id: self.document_id.to_string(), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { documents_api::delete_document(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/collection/documents.rs b/typesense/src/client/collection/documents.rs new file mode 100644 index 0000000..e4b7360 --- /dev/null +++ b/typesense/src/client/collection/documents.rs @@ -0,0 +1,285 @@ +//! Provides access to the document, search, and override-related API endpoints. +//! +//! An instance of `Documents` is scoped to a specific collection and is created +//! via the main `client.collection("collection_name").documents()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, documents_api}, + models::{ + self, DeleteDocumentsParameters, ExportDocumentsParameters, ImportDocumentsParameters, + UpdateDocumentsParameters, + }, +}; + +/// Provides methods for interacting with documents within a specific Typesense collection. +/// +/// This struct is created by calling `client.collection("collection_name").documents("collection_name")`. +pub struct Documents<'a> { + pub(super) client: &'a Client, + pub(super) collection_name: &'a str, +} + +impl<'a> Documents<'a> { + /// Creates a new `Documents` instance. + /// + /// This is typically called by `Client::documents()`. + pub(super) fn new(client: &'a Client, collection_name: &'a str) -> Self { + Self { + client, + collection_name, + } + } + + /// Indexes a document in the collection. + /// + + /// + /// # Arguments + /// * `document` - A `serde_json::Value` representing the document. + /// * `action` - The indexing action to perform (e.g., "create", "upsert"). + async fn index( + &self, + document: serde_json::Value, + action: &str, + ) -> Result> { + let params = documents_api::IndexDocumentParams { + collection_name: self.collection_name.to_string(), + body: document, + action: Some(action.to_string()), + dirty_values: None, // Or expose this as an argument if needed + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { documents_api::index_document(&config, params_for_move).await } + }) + .await + } + + /// Creates a new document in the collection. + /// Fails if a document with the same id already exists + /// + /// If the document has an `id` field of type `string`, it will be used as the document's ID. + /// Otherwise, Typesense will auto-generate an ID. + /// + /// # Arguments + /// * `document` - A `serde_json::Value` representing the document to create. + pub async fn create( + &self, + document: serde_json::Value, + ) -> Result> { + self.index(document, "create").await + } + + /// Creates a new document or updates an existing document if a document with the same id already exists. + /// Requires the whole document to be sent. For partial updates, use the `update()` action. + /// + /// # Arguments + /// * `document` - A `serde_json::Value` representing the document to upsert. + pub async fn upsert( + &self, + document: serde_json::Value, + ) -> Result> { + self.index(document, "upsert").await + } + + // --- Bulk Operation Methods --- + + /// Imports a batch of documents in JSONL format. + /// + /// The documents to be imported must be formatted as a newline-delimited JSON string. + /// + /// # Arguments + /// * `documents_jsonl` - A string containing the documents in JSONL format. + /// * `params` - An `ImportDocumentsParameters` struct containing options like `action` and `batch_size`. + pub async fn import( + &self, + documents_jsonl: String, + params: ImportDocumentsParameters, + ) -> Result> { + let params = documents_api::ImportDocumentsParams { + body: documents_jsonl, + collection_name: self.collection_name.to_string(), + + action: params.action, + batch_size: params.batch_size, + dirty_values: params.dirty_values, + remote_embedding_batch_size: params.remote_embedding_batch_size, + return_doc: params.return_doc, + return_id: params.return_id, + }; + + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { documents_api::import_documents(&config, params_for_move).await } + }) + .await + } + + /// Exports all documents in a collection in JSONL format. + /// + /// # Arguments + /// * `params` - An `ExportDocumentsParameters` struct containing options like `filter_by` and `include_fields`. + pub async fn export( + &self, + params: ExportDocumentsParameters, + ) -> Result> { + let params = documents_api::ExportDocumentsParams { + collection_name: self.collection_name.to_string(), + exclude_fields: params.exclude_fields, + filter_by: params.filter_by, + include_fields: params.include_fields, + }; + + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { documents_api::export_documents(&config, params_for_move).await } + }) + .await + } + + /// Deletes a batch of documents matching a specific filter condition. + /// + /// # Arguments + /// * `params` - A `DeleteDocumentsParameters` describing the conditions for deleting documents. + pub async fn delete( + &self, + params: DeleteDocumentsParameters, + ) -> Result> + { + let params = documents_api::DeleteDocumentsParams { + collection_name: self.collection_name.to_string(), + filter_by: Some(params.filter_by), + batch_size: params.batch_size, + ignore_not_found: params.ignore_not_found, + truncate: params.truncate, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { documents_api::delete_documents(&config, params_for_move).await } + }) + .await + } + + /// Updates a batch of documents matching a specific filter condition. + /// + /// # Arguments + /// * `document` - A `serde_json::Value` containing the fields to update. + /// * `params` - A `UpdateDocumentsParameters` describing the conditions for updating documents. + pub async fn update( + &self, + document: serde_json::Value, + params: UpdateDocumentsParameters, + ) -> Result> + { + let params = documents_api::UpdateDocumentsParams { + collection_name: self.collection_name.to_string(), + filter_by: params.filter_by, + body: document, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { documents_api::update_documents(&config, params_for_move).await } + }) + .await + } + + /// Searches for documents in the collection that match the given criteria. + /// + /// # Arguments + /// * `params` - A `SearchParameters` struct containing all search parameters. + /// you can construct it like this: + /// `SearchParameters { q: Some("...".into()), query_by: Some("...".into()), ..Default::default() }` + pub async fn search( + &self, + params: models::SearchParameters, + ) -> Result> { + let search_params = documents_api::SearchCollectionParams { + collection_name: self.collection_name.to_string(), + + // Map all corresponding fields directly. + cache_ttl: params.cache_ttl, + conversation: params.conversation, + conversation_id: params.conversation_id, + conversation_model_id: params.conversation_model_id, + drop_tokens_mode: params.drop_tokens_mode, + drop_tokens_threshold: params.drop_tokens_threshold, + enable_highlight_v1: params.enable_highlight_v1, + enable_overrides: params.enable_overrides, + enable_synonyms: params.enable_synonyms, + enable_typos_for_alpha_numerical_tokens: params.enable_typos_for_alpha_numerical_tokens, + enable_typos_for_numerical_tokens: params.enable_typos_for_numerical_tokens, + exclude_fields: params.exclude_fields, + exhaustive_search: params.exhaustive_search, + facet_by: params.facet_by, + facet_query: params.facet_query, + facet_return_parent: params.facet_return_parent, + facet_strategy: params.facet_strategy, + filter_by: params.filter_by, + filter_curated_hits: params.filter_curated_hits, + group_by: params.group_by, + group_limit: params.group_limit, + group_missing_values: params.group_missing_values, + hidden_hits: params.hidden_hits, + highlight_affix_num_tokens: params.highlight_affix_num_tokens, + highlight_end_tag: params.highlight_end_tag, + highlight_fields: params.highlight_fields, + highlight_full_fields: params.highlight_full_fields, + highlight_start_tag: params.highlight_start_tag, + include_fields: params.include_fields, + infix: params.infix, + limit: params.limit, + max_candidates: params.max_candidates, + max_extra_prefix: params.max_extra_prefix, + max_extra_suffix: params.max_extra_suffix, + max_facet_values: params.max_facet_values, + max_filter_by_candidates: params.max_filter_by_candidates, + min_len_1typo: params.min_len_1typo, + min_len_2typo: params.min_len_2typo, + num_typos: params.num_typos, + offset: params.offset, + override_tags: params.override_tags, + page: params.page, + per_page: params.per_page, + pinned_hits: params.pinned_hits, + pre_segmented_query: params.pre_segmented_query, + prefix: params.prefix, + preset: params.preset, + prioritize_exact_match: params.prioritize_exact_match, + prioritize_num_matching_fields: params.prioritize_num_matching_fields, + prioritize_token_position: params.prioritize_token_position, + q: params.q, + query_by: params.query_by, + query_by_weights: params.query_by_weights, + remote_embedding_num_tries: params.remote_embedding_num_tries, + remote_embedding_timeout_ms: params.remote_embedding_timeout_ms, + search_cutoff_ms: params.search_cutoff_ms, + snippet_threshold: params.snippet_threshold, + sort_by: params.sort_by, + split_join_tokens: params.split_join_tokens, + stopwords: params.stopwords, + synonym_num_typos: params.synonym_num_typos, + synonym_prefix: params.synonym_prefix, + text_match_type: params.text_match_type, + typo_tokens_threshold: params.typo_tokens_threshold, + use_cache: params.use_cache, + vector_query: params.vector_query, + voice_query: params.voice_query, + nl_model_id: params.nl_model_id, + nl_query: params.nl_query, + }; + + self.client + .execute(|config: Arc| { + let params_for_move = search_params.clone(); + async move { documents_api::search_collection(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/collection/mod.rs b/typesense/src/client/collection/mod.rs new file mode 100644 index 0000000..3acad6f --- /dev/null +++ b/typesense/src/client/collection/mod.rs @@ -0,0 +1,145 @@ +//! Provides access to the collection and alias-related API endpoints. +//! +//! A `Collections` instance is created via the main `Client::collections()` method. + +pub mod document; +pub mod documents; +pub mod search_override; +pub mod search_overrides; +pub mod synonym; +pub mod synonyms; +use super::{Client, Error}; +pub use document::Document; +pub use documents::Documents; +pub use search_override::SearchOverride; +pub use search_overrides::SearchOverrides; +use std::sync::Arc; +pub use synonym::Synonym; +pub use synonyms::Synonyms; +use typesense_codegen::{ + apis::{collections_api, configuration}, + models, +}; + +/// Provides methods for interacting with a Typesense collection. +/// +/// This struct is created by calling `client.collection("collection_name")`. +pub struct Collection<'a> { + pub(super) client: &'a Client, + pub(super) collection_name: &'a str, +} + +impl<'a> Collection<'a> { + /// Creates a new `Collection` instance. + pub(super) fn new(client: &'a Client, collection_name: &'a str) -> Self { + Self { + client, + collection_name, + } + } + // --- Documents Accessors --- + + /// Provides access to the document-related API endpoints for a specific collection. + pub fn documents(&'a self) -> documents::Documents<'a> { + documents::Documents::new(self.client, self.collection_name) + } + + /// Provides access to the API endpoints for a single document within a Typesense collection. + pub fn document(&'a self, document_id: &'a str) -> document::Document<'a> { + document::Document::new(self.client, self.collection_name, document_id) + } + + // --- Overrides Accessors --- + + /// Provides access to endpoints for managing the collection of search overrides. + /// + /// Example: `client.collection("collection_name").search_overrides().retrieve().await` + pub fn search_overrides(&self) -> SearchOverrides<'a> { + SearchOverrides::new(self.client, self.collection_name) + } + + /// Provides access to endpoints for managing a single search override. + /// + /// # Arguments + /// * `override_id` - The ID of the search override to manage. + /// + /// Example: `client.collection("collection_name").search_override("...").retrieve().await` + pub fn search_override(&self, override_id: &'a str) -> SearchOverride<'a> { + SearchOverride::new(self.client, self.collection_name, override_id) + } + + // --- Synonym Accessors --- + + /// Provides access to endpoints for managing the collection of search synonyms. + /// + /// Example: `client.collection("collection_name").synonyms().retrieve().await` + pub fn synonyms(&self) -> Synonyms<'a> { + Synonyms::new(self.client, self.collection_name) + } + + /// Provides access to endpoints for managing a single search synonym. + /// + /// # Arguments + /// * `synonym_id` - The ID of the search synonym to manage. + /// + /// Example: `client.collection("collection_name").synonym("synonym_id").delete().await` + pub fn synonym(&self, synonym_id: &'a str) -> Synonym<'a> { + Synonym::new(self.client, self.collection_name, synonym_id) + } + + // --- Methods for this collection --- + + /// Retrieves the details of a collection, given its name. + pub async fn retrieve( + &self, + ) -> Result> { + let params = collections_api::GetCollectionParams { + collection_name: self.collection_name.to_string(), + }; + + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { collections_api::get_collection(&config, params_for_move).await } + }) + .await + } + + /// Permanently drops a collection. + /// + /// This action cannot be undone. For large collections, this might have an + /// impact on read latencies during the delete operation. + pub async fn delete( + &self, + ) -> Result> { + let params = collections_api::DeleteCollectionParams { + collection_name: self.collection_name.to_string(), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { collections_api::delete_collection(&config, params_for_move).await } + }) + .await + } + + /// Updates a collection's schema to modify the fields and their types. + /// + /// # Arguments + /// * `update_schema` - A `CollectionUpdateSchema` object describing the fields to update. + pub async fn update( + &self, + update_schema: models::CollectionUpdateSchema, + ) -> Result> { + let params = collections_api::UpdateCollectionParams { + collection_name: self.collection_name.to_string(), + collection_update_schema: update_schema, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { collections_api::update_collection(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/collection/search_override.rs b/typesense/src/client/collection/search_override.rs new file mode 100644 index 0000000..9805a5d --- /dev/null +++ b/typesense/src/client/collection/search_override.rs @@ -0,0 +1,65 @@ +//! Provides access to the API endpoints for managing a single search override. +//! +//! An instance of `SearchOverride` is created via the `Client::collection("collection_name").search_override("search_override_id")` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, documents_api}, + models, +}; + +/// Provides methods for interacting with a specific search override. +/// +/// This struct is created by calling `client.collection("colelction_name").search_override("override_id")`. +pub struct SearchOverride<'a> { + pub(super) client: &'a Client, + pub(super) collection_name: &'a str, + pub(super) override_id: &'a str, +} + +impl<'a> SearchOverride<'a> { + /// Creates a new `Override` instance for a specific override ID. + pub(super) fn new(client: &'a Client, collection_name: &'a str, override_id: &'a str) -> Self { + Self { + client, + collection_name, + override_id, + } + } + + /// Retrieves this specific search override. + pub async fn retrieve( + &self, + ) -> Result> { + let params = documents_api::GetSearchOverrideParams { + collection_name: self.collection_name.to_string(), + override_id: self.override_id.to_string(), + }; + + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { documents_api::get_search_override(&config, params_for_move).await } + }) + .await + } + + /// Deletes this specific search override. + pub async fn delete( + &self, + ) -> Result> + { + let params = documents_api::DeleteSearchOverrideParams { + collection_name: self.collection_name.to_string(), + override_id: self.override_id.to_string(), + }; + + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { documents_api::delete_search_override(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/collection/search_overrides.rs b/typesense/src/client/collection/search_overrides.rs new file mode 100644 index 0000000..11151a1 --- /dev/null +++ b/typesense/src/client/collection/search_overrides.rs @@ -0,0 +1,70 @@ +//! Provides access to the API endpoints for managing a collection's search overrides. +//! +//! An instance of `SearchOverrides` is created via the `Client::collection("collection_name").search_overrides()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, documents_api}, + models, +}; + +/// Provides methods for interacting with a collection of search overrides. +/// +/// This struct is created by calling `client.collection("collection_name").search_overrides()`. +pub struct SearchOverrides<'a> { + pub(super) client: &'a Client, + pub(super) collection_name: &'a str, +} + +impl<'a> SearchOverrides<'a> { + /// Creates a new `Overrides` instance. + pub(super) fn new(client: &'a Client, collection_name: &'a str) -> Self { + Self { + client, + collection_name, + } + } + + /// Creates or updates a search override. + /// + /// Overrides allow you to rank certain documents higher than others for specific queries. + /// + /// # Arguments + /// * `override_id` - The ID of the search override to create or update. + /// * `schema` - The `SearchOverrideSchema` defining the override rules. + pub async fn upsert( + &self, + override_id: &str, + schema: models::SearchOverrideSchema, + ) -> Result> { + let params = documents_api::UpsertSearchOverrideParams { + collection_name: self.collection_name.to_string(), + override_id: override_id.to_string(), + search_override_schema: schema, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { documents_api::upsert_search_override(&config, params_for_move).await } + }) + .await + } + + /// Lists all search overrides associated with the collection. + pub async fn list( + &self, + ) -> Result> + { + let params = documents_api::GetSearchOverridesParams { + collection_name: self.collection_name.to_string(), + }; + + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { documents_api::get_search_overrides(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/collection/synonym.rs b/typesense/src/client/collection/synonym.rs new file mode 100644 index 0000000..d3b9b05 --- /dev/null +++ b/typesense/src/client/collection/synonym.rs @@ -0,0 +1,65 @@ +//! Provides access to the API endpoints for managing a single search synonym. +//! +//! An instance of `Synonym` is created via the `client.collection("collection_name").synonym("synonym_id")` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, synonyms_api}, + models, +}; + +/// Provides methods for interacting with a specific search synonym. +/// +/// This struct is created by calling `client.collection("collection_name").synonym("synonym_id")`. +pub struct Synonym<'a> { + pub(super) client: &'a Client, + pub(super) collection_name: &'a str, + pub(super) synonym_id: &'a str, +} + +impl<'a> Synonym<'a> { + /// Creates a new `Synonym` instance for a specific synonym ID. + pub(super) fn new(client: &'a Client, collection_name: &'a str, synonym_id: &'a str) -> Self { + Self { + client, + collection_name, + synonym_id, + } + } + + /// Retrieves this specific search synonym. + pub async fn get( + &self, + ) -> Result> { + let params = synonyms_api::GetSearchSynonymParams { + collection_name: self.collection_name.to_string(), + synonym_id: self.synonym_id.to_string(), + }; + + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { synonyms_api::get_search_synonym(&config, params_for_move).await } + }) + .await + } + + /// Deletes this specific search synonym. + pub async fn delete( + &self, + ) -> Result> + { + let params = synonyms_api::DeleteSearchSynonymParams { + collection_name: self.collection_name.to_string(), + synonym_id: self.synonym_id.to_string(), + }; + + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { synonyms_api::delete_search_synonym(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/collection/synonyms.rs b/typesense/src/client/collection/synonyms.rs new file mode 100644 index 0000000..a78300b --- /dev/null +++ b/typesense/src/client/collection/synonyms.rs @@ -0,0 +1,67 @@ +//! Provides access to the API endpoints for managing a collection's search synonyms. +//! +//! An instance of `Synonyms` is created via the `client.collection("collection_name").synonyms()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, synonyms_api}, + models, +}; + +/// Provides methods for interacting with a collection of search synonyms. +/// +/// This struct is created by calling `client.collection("collection_name").synonyms()`. +pub struct Synonyms<'a> { + pub(super) client: &'a Client, + pub(super) collection_name: &'a str, +} + +impl<'a> Synonyms<'a> { + /// Creates a new `Synonyms` instance. + pub(super) fn new(client: &'a Client, collection_name: &'a str) -> Self { + Self { + client, + collection_name, + } + } + + /// Creates or updates a search synonym. + /// + /// # Arguments + /// * `synonym_id` - The ID of the search synonym to create or update. + /// * `schema` - A `SearchSynonymSchema` object defining the equivalent terms. + pub async fn upsert( + &self, + synonym_id: &str, + schema: models::SearchSynonymSchema, + ) -> Result> { + let params = synonyms_api::UpsertSearchSynonymParams { + collection_name: self.collection_name.to_string(), + synonym_id: synonym_id.to_string(), + search_synonym_schema: schema, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { synonyms_api::upsert_search_synonym(&config, params_for_move).await } + }) + .await + } + + /// Retrieve all search synonyms associated with the collection. + pub async fn retrieve( + &self, + ) -> Result> { + let params = synonyms_api::GetSearchSynonymsParams { + collection_name: self.collection_name.to_string(), + }; + + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { synonyms_api::get_search_synonyms(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/collections.rs b/typesense/src/client/collections.rs new file mode 100644 index 0000000..9378810 --- /dev/null +++ b/typesense/src/client/collections.rs @@ -0,0 +1,62 @@ +//! Provides access to the collection and alias-related API endpoints. +//! +//! A `Collections` instance is created via the main `client.collections()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{collections_api, configuration}, + models, +}; + +/// Provides methods for interacting with Typesense collections and aliases. +/// +/// This struct is created by calling `client.collections()`. +pub struct Collections<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Collections<'a> { + /// Creates a new `Collection` instance + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + // --- Collection-Specific Methods --- + + /// Creates a new collection with the given schema. + /// + /// When a collection is created, you give it a name and describe the fields + /// that will be indexed from the documents added to the collection. + /// + /// # Arguments + /// * `schema` - A `CollectionSchema` object describing the collection to be created. + pub async fn create( + &self, + schema: models::CollectionSchema, + ) -> Result> { + let params = collections_api::CreateCollectionParams { + collection_schema: schema, + }; + + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { collections_api::create_collection(&config, params_for_move).await } + }) + .await + } + + /// Returns a summary of all collections in the Typesense cluster. + /// + /// The collections are returned sorted by creation date, with the most + /// recent collections appearing first. + pub async fn retrieve( + &self, + ) -> Result, Error> { + self.client + .execute(|config: Arc| async move { + collections_api::get_collections(&config).await + }) + .await + } +} diff --git a/typesense/src/client/conversations/mod.rs b/typesense/src/client/conversations/mod.rs new file mode 100644 index 0000000..392070b --- /dev/null +++ b/typesense/src/client/conversations/mod.rs @@ -0,0 +1,41 @@ +//! Provides access to the API endpoints for managing conversation models. +//! +//! An `Conversations` instance is created via the main `Client::conversations()` method. + +use super::Client; +pub use model::Model; +pub use models::Models; + +pub mod model; +pub mod models; + +/// Provides methods for managing Typesense conversation models. +/// +/// This struct is created by calling `client.conversations()`. +pub struct Conversations<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Conversations<'a> { + /// Creates a new `Conversations` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Provides access to endpoints for managing the collection of conversation models. + /// + /// Example: `client.conversations().models().list().await` + pub fn models(&self) -> Models<'a> { + Models::new(self.client) + } + + /// Provides access to endpoints for managing a single conversation model. + /// + /// # Arguments + /// * `model_id` - The ID of the conversation model to manage. + /// + /// Example: `client.conversations().model("...").get().await` + pub fn model(&self, model_id: &'a str) -> Model<'a> { + Model::new(self.client, model_id) + } +} diff --git a/typesense/src/client/conversations/model.rs b/typesense/src/client/conversations/model.rs new file mode 100644 index 0000000..79540bb --- /dev/null +++ b/typesense/src/client/conversations/model.rs @@ -0,0 +1,90 @@ +//! Provides access to the API endpoints for managing a single conversation model. +//! +//! An instance of `Model` is created via the `Conversations::model()` method. + +use crate::client::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, conversations_api}, + models, +}; + +/// Provides methods for interacting with a specific conversation model. +/// +/// This struct is created by calling `client.conversations().model("model_id")`. +pub struct Model<'a> { + pub(super) client: &'a Client, + pub(super) model_id: &'a str, +} + +impl<'a> Model<'a> { + /// Creates a new `Model` instance for a specific model ID. + pub(super) fn new(client: &'a Client, model_id: &'a str) -> Self { + Self { client, model_id } + } + + /// Retrieves the details of this specific conversation model. + pub async fn retrieve( + &self, + ) -> Result< + models::ConversationModelSchema, + Error, + > { + let params = conversations_api::RetrieveConversationModelParams { + model_id: self.model_id.to_string(), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { + conversations_api::retrieve_conversation_model(&config, params_for_move).await + } + }) + .await + } + + /// Updates this specific conversation model. + /// + /// # Arguments + /// * `schema` - A `ConversationModelUpdateSchema` object with the fields to update. + pub async fn update( + &self, + schema: models::ConversationModelUpdateSchema, + ) -> Result< + models::ConversationModelSchema, + Error, + > { + let params = conversations_api::UpdateConversationModelParams { + model_id: self.model_id.to_string(), + conversation_model_update_schema: schema, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { + conversations_api::update_conversation_model(&config, params_for_move).await + } + }) + .await + } + + /// Deletes this specific conversation model. + pub async fn delete( + &self, + ) -> Result< + models::ConversationModelSchema, + Error, + > { + let params = conversations_api::DeleteConversationModelParams { + model_id: self.model_id.to_string(), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { + conversations_api::delete_conversation_model(&config, params_for_move).await + } + }) + .await + } +} diff --git a/typesense/src/client/conversations/models.rs b/typesense/src/client/conversations/models.rs new file mode 100644 index 0000000..d4b585d --- /dev/null +++ b/typesense/src/client/conversations/models.rs @@ -0,0 +1,62 @@ +//! Provides access to the API endpoints for managing conversation models. +//! +//! An instance of `Models` is created via the `Conversations::models()` method. + +use crate::client::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, conversations_api}, + models, +}; + +/// Provides methods for creating and listing conversation models. +/// +/// This struct is created by calling `conversations.models()`. +pub struct Models<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Models<'a> { + /// Creates a new `Models` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Creates a new conversation model. + /// + /// # Arguments + /// * `schema` - A `ConversationModelCreateSchema` object describing the model. + pub async fn create( + &self, + schema: models::ConversationModelCreateSchema, + ) -> Result< + models::ConversationModelSchema, + Error, + > { + let params = conversations_api::CreateConversationModelParams { + conversation_model_create_schema: schema, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { + conversations_api::create_conversation_model(&config, params_for_move).await + } + }) + .await + } + + /// Retrieves a summary of all conversation models. + pub async fn retrieve( + &self, + ) -> Result< + Vec, + Error, + > { + self.client + .execute(|config: Arc| async move { + conversations_api::retrieve_all_conversation_models(&config).await + }) + .await + } +} diff --git a/typesense/src/client/key.rs b/typesense/src/client/key.rs new file mode 100644 index 0000000..dcd33ef --- /dev/null +++ b/typesense/src/client/key.rs @@ -0,0 +1,56 @@ +//! Provides access to the API endpoints for managing a single API key. +//! +//! A `Key` instance is created via the `Client::key(key_id)` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, keys_api}, + models, +}; + +/// Provides methods for managing a specific Typesense API key. +/// +/// This struct is created by calling `client.key(key_id)`. +pub struct Key<'a> { + pub(super) client: &'a Client, + pub(super) key_id: i64, +} + +impl<'a> Key<'a> { + /// Creates a new `Key` instance for a specific key ID. + pub(super) fn new(client: &'a Client, key_id: i64) -> Self { + Self { client, key_id } + } + + /// Retrieves metadata about this specific API key. + /// + /// For security reasons, this endpoint only returns the key prefix and metadata, + /// not the full key value. + pub async fn retrieve(&self) -> Result> { + let params = keys_api::GetKeyParams { + key_id: self.key_id, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { keys_api::get_key(&config, params_for_move).await } + }) + .await + } + + /// Deletes this specific API key. + pub async fn delete( + &self, + ) -> Result> { + let params = keys_api::DeleteKeyParams { + key_id: self.key_id, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { keys_api::delete_key(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/keys.rs b/typesense/src/client/keys.rs new file mode 100644 index 0000000..004ae7c --- /dev/null +++ b/typesense/src/client/keys.rs @@ -0,0 +1,55 @@ +//! Provides access to the API endpoints for managing the collection of API keys. +//! +//! An `Keys` instance is created via the `Client::keys()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, keys_api}, + models, +}; + +/// Provides methods for managing a collection of Typesense API keys. +/// +/// This struct is created by calling `client.keys()`. +pub struct Keys<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Keys<'a> { + /// Creates a new `Keys` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Creates a new API key with fine-grained access control. + /// + /// You can restrict access on a per-collection and per-action level. + /// The full, unhashed key is only returned on creation. + /// + /// # Arguments + /// * `schema` - An `ApiKeySchema` object describing the key's permissions. + pub async fn create( + &self, + schema: models::ApiKeySchema, + ) -> Result> { + let params = keys_api::CreateKeyParams { + api_key_schema: Some(schema), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { keys_api::create_key(&config, params_for_move).await } + }) + .await + } + + /// Lists all API keys and their metadata. + pub async fn retrieve(&self) -> Result> { + self.client + .execute(|config: Arc| async move { + keys_api::get_keys(&config).await + }) + .await + } +} diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs new file mode 100644 index 0000000..1613178 --- /dev/null +++ b/typesense/src/client/mod.rs @@ -0,0 +1,765 @@ +//! # A batteries-included, multi-node-aware client for the Typesense API. +//! +//! This module provides the main `Client` for interacting with a Typesense cluster. +//! It is designed for resilience and ease of use, incorporating features like +//! automatic failover, health checks, and a structured, ergonomic API. +//! +//! ## Key Features: +//! - **Multi-Node Operation**: Automatically manages connections to multiple Typesense nodes. +//! - **Health Checks & Failover**: Monitors node health and seamlessly fails over to healthy nodes upon encountering server or network errors. +//! - **Nearest Node Priority**: Can be configured to always prioritize a specific "nearest" node to reduce latency. +//! - **Fluent, Namespaced API**: Operations are grouped into logical namespaces like `.collections()`, `.documents("books")`, and `.operations()`, making the API discoverable and easy to use. +//! - **Built-in Retries**: Handles transient network errors with an exponential backoff policy for each node. +//! +//! ## Example Usage +//! +//! ```no_run +//! use typesense::client::{Client, MultiNodeConfiguration}; +//! use typesense_codegen::models; +//! use reqwest::Url; +//! use reqwest_retry::policies::ExponentialBackoff; +//! use std::time::Duration; +//! +//! #[tokio::main] +//! async fn main() -> Result<(), Box> { +//! let config = MultiNodeConfiguration { +//! nodes: vec![Url::parse("http://localhost:8108")?], +//! nearest_node: None, +//! api_key: "your-api-key".to_string(), +//! healthcheck_interval: Duration::from_secs(60), +//! retry_policy: ExponentialBackoff::builder().build_with_max_retries(3), +//! connection_timeout: Duration::from_secs(10), +//! }; +//! +//! let client = Client::new(config)?; +//! +//! // Retrieve details for a collection +//! let collection = client.collection("products").retrieve().await?; +//! println!("Collection Name: {}", collection.name); +//! +//! // Search for a document +//! let search_params = models::SearchParameters { +//! q: Some("phone".to_string()), +//! query_by: Some("name".to_string()), +//! ..Default::default() +//! }; +//! let search_results = client.collection("products").documents().search(search_params).await?; +//! println!("Found {} hits.", search_results.found.unwrap_or(0)); +//! +//! Ok(()) +//! } +//! ``` + +pub mod alias; +pub mod aliases; +pub mod analytics; +pub mod collection; +pub mod collections; +pub mod conversations; +pub mod key; +pub mod keys; +pub mod multi_search; +pub mod operations; +pub mod preset; +pub mod presets; +pub mod stemming; +pub mod stopword; +pub mod stopwords; + +pub use alias::Alias; +pub use aliases::Aliases; +pub use analytics::Analytics; +pub use collection::Collection; +pub use collections::Collections; +pub use conversations::Conversations; +pub use key::Key; +pub use keys::Keys; +pub use operations::Operations; +pub use preset::Preset; +pub use presets::Presets; +pub use stemming::Stemming; +pub use stopword::Stopword; +pub use stopwords::Stopwords; + +use reqwest::Url; +use reqwest_middleware::ClientBuilder; +use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware}; +use std::future::Future; +use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, Mutex, +}; +use std::time::{Duration, Instant}; +use thiserror::Error; +use typesense_codegen::apis::{self, configuration}; + +use crate::client::multi_search::MultiSearch; + +// --- Internal Node Health Struct --- +// This is an internal detail to track the state of each node. +#[derive(Debug)] +struct Node { + url: Url, + is_healthy: bool, + last_access_timestamp: Instant, +} + +/// Configuration for the multi-node Typesense client. +#[derive(Clone, Debug)] +pub struct MultiNodeConfiguration { + /// A list of all nodes in the Typesense cluster. + pub nodes: Vec, + /// An optional, preferred node to try first for every request. Ideal for reducing latency. + pub nearest_node: Option, + /// The Typesense API key used for authentication. + pub api_key: String, + /// The duration after which an unhealthy node will be retried for requests. + pub healthcheck_interval: Duration, + /// The retry policy for transient network errors on a *single* node. + pub retry_policy: ExponentialBackoff, + /// The timeout for each individual network request. + pub connection_timeout: Duration, +} +impl Default for MultiNodeConfiguration { + /// Provides a default configuration suitable for local development. + /// + /// - **nodes**: Empty. + /// - **nearest_node**: None. + /// - **api_key**: "xyz" (a common placeholder). + /// - **healthcheck_interval**: 60 seconds. + /// - **retry_policy**: Exponential backoff with a maximum of 3 retries. + /// - **connection_timeout**: 5 seconds. + fn default() -> Self { + Self { + nodes: vec![], + nearest_node: None, + api_key: "xyz".to_string(), + healthcheck_interval: Duration::from_secs(60), + retry_policy: ExponentialBackoff::builder().build_with_max_retries(3), + connection_timeout: Duration::from_secs(5), + } + } +} + +/// The primary error type for the Typesense client. +#[derive(Debug, Error)] +pub enum Error +where + E: std::fmt::Debug + 'static, + apis::Error: std::error::Error + 'static, +{ + /// Indicates that all configured nodes failed to process a request. + #[error("All API nodes failed to respond. Last error: {source}")] + AllNodesFailed { + /// The last underlying API or network error received from a node before giving up. + #[source] + source: apis::Error, + }, + + // Any middleware error will be wrapped in the Api variant below. + /// An API-level error returned by the Typesense server (e.g., 503 Service Unavailable) + /// or a network-level error from the underlying HTTP client (e.g. connection refused). + #[error("A single node failed with an API or network error")] + Api(#[from] apis::Error), +} + +/// The main entry point for all interactions with the Typesense API. +/// +/// The client manages connections to multiple nodes and provides access to different +/// API resource groups (namespaces) like `collections`, `documents`, and `operations`. +#[derive(Debug)] +pub struct Client { + // The Client now holds the stateful Node list. + nodes: Vec>>, + nearest_node: Option>>, + api_key: String, + healthcheck_interval: Duration, + retry_policy: ExponentialBackoff, + connection_timeout: Duration, + current_node_index: AtomicUsize, +} + +impl Client { + /// Creates a new `Client` with the given configuration. + /// + /// Returns an error if the configuration contains no nodes. + pub fn new(config: MultiNodeConfiguration) -> Result { + if config.nodes.is_empty() && config.nearest_node.is_none() { + return Err("Configuration must include at least one node or a nearest_node."); + } + + let nodes = config + .nodes + .into_iter() + .map(|url| { + Arc::new(Mutex::new(Node { + url, + is_healthy: true, + last_access_timestamp: Instant::now(), + })) + }) + .collect(); + + let nearest_node = config.nearest_node.map(|url| { + Arc::new(Mutex::new(Node { + url, + is_healthy: true, + last_access_timestamp: Instant::now(), + })) + }); + + Ok(Self { + nodes, + nearest_node, + api_key: config.api_key, + healthcheck_interval: config.healthcheck_interval, + retry_policy: config.retry_policy, + connection_timeout: config.connection_timeout, + current_node_index: AtomicUsize::new(0), + }) + } + + /// Selects the next node to use for a request based on health and priority. + fn get_next_node(&self) -> Arc> { + // 1. Always try the nearest_node first if it exists. + if let Some(nearest_node_arc) = &self.nearest_node { + let node = nearest_node_arc.lock().unwrap(); + let is_due_for_check = Instant::now().duration_since(node.last_access_timestamp) + >= self.healthcheck_interval; + + if node.is_healthy || is_due_for_check { + return Arc::clone(nearest_node_arc); + } + } + + // 2. Fallback to the main list of nodes if no healthy nearest_node is available. + if self.nodes.is_empty() { + // This can only happen if ONLY a nearest_node was provided and it's unhealthy. + // We must return it to give it a chance to recover. + return Arc::clone(self.nearest_node.as_ref().unwrap()); + } + + // 3. Loop through all nodes once to find a healthy one. + for _ in 0..self.nodes.len() { + let index = self.current_node_index.fetch_add(1, Ordering::Relaxed) % self.nodes.len(); + let node_arc = &self.nodes[index]; + let node = node_arc.lock().unwrap(); + let is_due_for_check = Instant::now().duration_since(node.last_access_timestamp) + >= self.healthcheck_interval; + + if node.is_healthy || is_due_for_check { + return Arc::clone(node_arc); + } + } + + // 4. If all nodes are unhealthy and not due for a check, just pick the next one in the round-robin. + // This gives it a chance to prove it has recovered. + let index = self.current_node_index.load(Ordering::Relaxed) % self.nodes.len(); + Arc::clone(&self.nodes[index]) + } + + /// Sets the health status of a given node after a request attempt. + fn set_node_health(&self, node_arc: &Arc>, is_healthy: bool) { + let mut node = node_arc.lock().unwrap(); + node.is_healthy = is_healthy; + node.last_access_timestamp = Instant::now(); + } + + /// The core execution method that handles multi-node failover and retries. + /// This internal method is called by all public API methods. + pub(super) async fn execute(&self, api_call: F) -> Result> + where + F: Fn(Arc) -> Fut, + Fut: Future>>, + E: std::fmt::Debug + 'static, + apis::Error: std::error::Error + 'static, + { + let mut last_api_error: Option> = None; + let num_nodes_to_try = self.nodes.len() + self.nearest_node.is_some() as usize; + + // Loop up to the total number of available nodes. + for _ in 0..num_nodes_to_try { + let node_arc = self.get_next_node(); + let node_url = { + // Lock is held for a very short duration. + let node = node_arc.lock().unwrap(); + node.url.clone() + }; + + // This client handles transient retries (e.g. network blips) on the *current node*. + let http_client = ClientBuilder::new( + reqwest::Client::builder() + .timeout(self.connection_timeout) + .build() + .expect("Failed to build reqwest client"), + ) + .with(RetryTransientMiddleware::new_with_policy( + self.retry_policy.clone(), + )) + .build(); + + // Create a temporary, single-node config for the generated API function. + let gen_config = Arc::new(configuration::Configuration { + base_path: node_url + .to_string() + .strip_suffix('/') + .unwrap_or(node_url.as_str()) + .to_string(), + api_key: Some(configuration::ApiKey { + prefix: None, + key: self.api_key.clone(), + }), + client: http_client, + ..Default::default() + }); + + match api_call(gen_config).await { + Ok(response) => { + self.set_node_health(&node_arc, true); // Mark as healthy on success. + return Ok(response); + } + Err(e) => { + if is_retriable(&e) { + self.set_node_health(&node_arc, false); // Mark as unhealthy on retriable error. + last_api_error = Some(e); + // Continue loop to try the next node. + } else { + // Non-retriable error (e.g., 404 Not Found), fail fast. + return Err(e.into()); + } + } + } + } + + // If the loop finishes, all nodes have failed. + Err(Error::AllNodesFailed { + source: last_api_error + .expect("No nodes were available to try, or all errors were non-retriable."), + }) + } + /// Provides access to the collection aliases-related API endpoints. + /// + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use typesense_codegen::models; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// let all_aliases = client.aliases().retrieve().await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn aliases(&self) -> Aliases<'_> { + Aliases::new(self) + } + + /// Provides access to a specific collection alias's-related API endpoints. + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use typesense_codegen::models; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// let specific_alias = client.alias("books_alias").retrieve().await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn alias<'a>(&'a self, name: &'a str) -> Alias<'a> { + Alias::new(self, name) + } + + /// Provides access to API endpoints for managing collections like `create()` and `retrieve()`. + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use typesense_codegen::models; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// let all_collections = client.collections().retrieve().await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn collections(&self) -> collections::Collections<'_> { + collections::Collections::new(self) + } + + /// Provides access to API endpoints of a specific collection. + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use typesense_codegen::models; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// let my_collection = client.collection("products").retrieve().await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn collection<'a>(&'a self, collection_name: &'a str) -> Collection<'a> { + Collection::new(self, collection_name) + } + + /// Provides access to the analytics-related API endpoints. + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use typesense_codegen::models; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// let analytics_rules = client.analytics().rules().retrieve().await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn analytics(&self) -> Analytics<'_> { + Analytics::new(self) + } + + /// Returns a `Conversations` instance for managing conversation models. + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use typesense_codegen::models; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// let conversation = client.conversations().models().retrieve().await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn conversations(&self) -> Conversations { + Conversations::new(self) + } + + /// Provides access to top-level, non-namespaced API endpoints like `health` and `debug`. + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use typesense_codegen::models; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// let health = client.operations().health().await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn operations(&self) -> Operations<'_> { + Operations::new(self) + } + + /// Provides access to endpoints for managing the collection of API keys. + /// + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use typesense_codegen::models; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// # let schema = models::ApiKeySchema { + /// # description: "Search-only key.".to_string(), + /// # actions: vec!["documents:search".to_string()], + /// # collections: vec!["*".to_string()], + /// # ..Default::default() + /// # }; + /// let new_key = client.keys().create(schema).await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn keys(&self) -> Keys<'_> { + Keys::new(self) + } + + /// Provides access to endpoints for managing a single API key. + /// + /// # Arguments + /// * `key_id` - The ID of the key to manage. + /// + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use typesense_codegen::models; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// let deleted_key = client.key(123).delete().await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn key(&self, key_id: i64) -> Key<'_> { + Key::new(self, key_id) + } + + /// Provides access to endpoints for managing all of your presets. + /// + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use typesense_codegen::models; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// let list_of_presets = client.presets().retrieve().await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn presets(&self) -> Presets { + Presets::new(self) + } + + /// Provides access to endpoints for managing a single preset. + /// + /// # Arguments + /// * `preset_id` - The ID of the preset to manage. + /// + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use typesense_codegen::models; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// let preset = client.preset("my-preset").retrieve().await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn preset<'a>(&'a self, preset_id: &'a str) -> Preset<'a> { + Preset::new(self, preset_id) + } + + /// Provides access to the stemming-related API endpoints. + /// + /// # Example + /// + /// ``` + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # + /// # let client = Client::new(config)?; + /// let response = client.stemming().dictionaries().retrieve().await.unwrap(); + /// # println!("{:#?}", response); + /// # Ok(()) + /// # } + /// ``` + pub fn stemming(&self) -> Stemming { + Stemming::new(self) + } + + /// Provides access to endpoints for managing the collection of stopwords sets. + /// + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// let all_stopwords = client.stopwords().retrieve().await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn stopwords(&self) -> Stopwords<'_> { + Stopwords::new(self) + } + + /// Provides access to endpoints for managing a single stopwords set. + /// + /// # Arguments + /// * `set_id` - The ID of the stopwords set to manage. + /// + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// let my_stopword_set = client.stopword("common_words").retrieve().await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn stopword<'a>(&'a self, set_id: &'a str) -> Stopword<'a> { + Stopword::new(self, set_id) + } + + /// Provides access to the multi search endpoint. + /// + /// # Example + /// ```ignore + /// # use typesense::client::{Client, MultiNodeConfiguration}; + /// # use typesense_codegen::models; + /// # use reqwest::Url; + /// # use reqwest_retry::policies::ExponentialBackoff; + /// # use std::time::Duration; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let config = MultiNodeConfiguration { + /// # nodes: vec![Url::parse("http://localhost:8108")?], + /// # api_key: "xyz".to_string(), + /// # ..Default::default() + /// # }; + /// # let client = Client::new(config)?; + /// # let search_requests = models::MultiSearchSearchesParameter { + /// # searches: vec![models::MultiSearchCollectionParameters { + /// # collection: Some("products".to_string()), + /// # q: Some("phone".to_string()), + /// # query_by: Some("name".to_string()), + /// # ..Default::default() + /// # }], + /// # ..Default::default() + /// # }; + /// # let common_params = models::MultiSearchParameters::default(); + /// let results = client.multi_search().perform(search_requests, common_params).await.unwrap(); + /// # Ok(()) + /// # } + /// ``` + pub fn multi_search(&self) -> MultiSearch<'_> { + MultiSearch::new(self) + } +} + +/// A helper function to determine if an error is worth retrying on another node. +fn is_retriable(error: &apis::Error) -> bool +where + E: std::fmt::Debug + 'static, + apis::Error: std::error::Error + 'static, +{ + match error { + // Server-side errors (5xx) indicate a problem with the node, so we should try another. + apis::Error::ResponseError(content) => content.status.is_server_error(), + // Underlying reqwest errors (e.g. connection refused) are retriable. + // Network-level errors from middleware are always retriable. + apis::Error::Reqwest(_) | apis::Error::ReqwestMiddleware(_) => true, + // Client-side (4xx) or parsing errors are not retriable as the request is likely invalid. + _ => false, + } +} diff --git a/typesense/src/client/multi_search.rs b/typesense/src/client/multi_search.rs new file mode 100644 index 0000000..54e3f1a --- /dev/null +++ b/typesense/src/client/multi_search.rs @@ -0,0 +1,124 @@ +//! Provides access to the API endpoints for Multi Search. +//! +//! A `MultiSearch` instance is created via the main `Client::multi_search()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{ + configuration::Configuration, + documents_api::{self, MultiSearchParams}, + }, + models, // The generated model structs +}; + +/// Provides methods for managing Typesense API keys. +/// +/// This struct is created by calling `client.keys()`. +pub struct MultiSearch<'a> { + pub(super) client: &'a Client, +} + +impl<'a> MultiSearch<'a> { + /// Creates a new `MultiSearch` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Make multiple search requests in a single HTTP request to avoid round-trip network latencies. + /// + /// You can use it in two different modes: + + /// - Federated search: each search request in the multi-search payload returns results as independently. + /// The results vector in the `multi_search` response is guaranteed to be in the same order as the queries you send in the `searches` vector in your request. + /// - Union search: the response of each search request is merged into a single unified order. + /// + /// # Arguments + /// * `search_requests` - A `MultiSearchSearchesParameter` contain multiple search requests, this will be sent in the request body. + /// * `common_search_params` - A `MultiSearchParameters` describing search parameters that are common to all searches, these will be sent as URL query parameters. + pub async fn perform( + &self, + search_requests: models::MultiSearchSearchesParameter, + common_search_params: models::MultiSearchParameters, + ) -> Result> { + let params = common_search_params; + let multi_search_params = MultiSearchParams { + // enable_highlight_v1: None, + // max_candidates: None, + // max_filter_by_candidates: None, + // split_join_tokens: None, + multi_search_searches_parameter: Some(search_requests), + + // Common URL search params + cache_ttl: params.cache_ttl, + conversation: params.conversation, + conversation_id: params.conversation_id, + conversation_model_id: params.conversation_model_id, + drop_tokens_mode: params.drop_tokens_mode, + drop_tokens_threshold: params.drop_tokens_threshold, + enable_overrides: params.enable_overrides, + enable_synonyms: params.enable_synonyms, + enable_typos_for_alpha_numerical_tokens: params.enable_typos_for_alpha_numerical_tokens, + enable_typos_for_numerical_tokens: params.enable_typos_for_numerical_tokens, + exclude_fields: params.exclude_fields, + exhaustive_search: params.exhaustive_search, + facet_by: params.facet_by, + facet_query: params.facet_query, + facet_return_parent: params.facet_return_parent, + facet_strategy: params.facet_strategy, + filter_by: params.filter_by, + filter_curated_hits: params.filter_curated_hits, + group_by: params.group_by, + group_limit: params.group_limit, + group_missing_values: params.group_missing_values, + hidden_hits: params.hidden_hits, + highlight_affix_num_tokens: params.highlight_affix_num_tokens, + highlight_end_tag: params.highlight_end_tag, + highlight_fields: params.highlight_fields, + highlight_full_fields: params.highlight_full_fields, + highlight_start_tag: params.highlight_start_tag, + include_fields: params.include_fields, + infix: params.infix, + limit: params.limit, + max_extra_prefix: params.max_extra_prefix, + max_extra_suffix: params.max_extra_suffix, + max_facet_values: params.max_facet_values, + min_len_1typo: params.min_len_1typo, + min_len_2typo: params.min_len_2typo, + num_typos: params.num_typos, + offset: params.offset, + override_tags: params.override_tags, + page: params.page, + per_page: params.per_page, + pinned_hits: params.pinned_hits, + pre_segmented_query: params.pre_segmented_query, + prefix: params.prefix, + preset: params.preset, + prioritize_exact_match: params.prioritize_exact_match, + prioritize_num_matching_fields: params.prioritize_num_matching_fields, + prioritize_token_position: params.prioritize_token_position, + q: params.q, + query_by: params.query_by, + query_by_weights: params.query_by_weights, + remote_embedding_num_tries: params.remote_embedding_num_tries, + remote_embedding_timeout_ms: params.remote_embedding_timeout_ms, + search_cutoff_ms: params.search_cutoff_ms, + snippet_threshold: params.snippet_threshold, + sort_by: params.sort_by, + stopwords: params.stopwords, + synonym_num_typos: params.synonym_num_typos, + synonym_prefix: params.synonym_prefix, + text_match_type: params.text_match_type, + typo_tokens_threshold: params.typo_tokens_threshold, + use_cache: params.use_cache, + vector_query: params.vector_query, + voice_query: params.voice_query, + }; + self.client + .execute(|config: Arc| { + let params_for_move = multi_search_params.clone(); + async move { documents_api::multi_search(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/operations.rs b/typesense/src/client/operations.rs new file mode 100644 index 0000000..152022c --- /dev/null +++ b/typesense/src/client/operations.rs @@ -0,0 +1,52 @@ +//! Provides access to top-level, non-namespaced API endpoints. +//! +//! An `Operations` instance is created via the main `Client::operations()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{ + configuration, + debug_api, + health_api, // Add this line + }, + models, +}; + +/// Provides methods for top-level, non-namespaced Typesense operations. +/// +/// This struct is created by calling `client.operations()`. +pub struct Operations<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Operations<'a> { + /// Creates a new `Operations` instance + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + /// Retrieves debugging information from a Typesense node. + /// + /// This method will try nodes in sequence according to the health policy + /// until it gets a successful response. The returned information pertains + /// to the specific node that responded successfully. + pub async fn debug(&self) -> Result> { + self.client + .execute(|config: Arc| async move { + debug_api::debug(&config).await + }) + .await + } + + /// Checks if a Typesense node is healthy and ready to accept requests. + /// + /// This method will try nodes in sequence according to the health policy + /// until it gets a successful response (`{"ok": true}`). + pub async fn health(&self) -> Result> { + self.client + .execute(|config: Arc| async move { + health_api::health(&config).await + }) + .await + } +} diff --git a/typesense/src/client/preset.rs b/typesense/src/client/preset.rs new file mode 100644 index 0000000..652f632 --- /dev/null +++ b/typesense/src/client/preset.rs @@ -0,0 +1,55 @@ +//! Provides access to the API endpoints for managing a single preset. +//! +//! A `Preset` instance is created via the main `Client::preset(id)` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, presets_api}, + models, +}; + +/// Provides methods for managing a single Typesense preset. +/// +/// This struct is created by calling `client.preset(id)`. +pub struct Preset<'a> { + pub(super) client: &'a Client, + pub(super) preset_id: &'a str, +} + +impl<'a> Preset<'a> { + /// Creates a new `Preset` instance. + pub(super) fn new(client: &'a Client, preset_id: &'a str) -> Self { + Self { client, preset_id } + } + + /// Retrieves the details of a preset, given its ID. + pub async fn retrieve( + &self, + ) -> Result> { + let params = presets_api::RetrievePresetParams { + preset_id: self.preset_id.to_string(), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { presets_api::retrieve_preset(&config, params_for_move).await } + }) + .await + } + + /// Permanently deletes a preset, given its ID. + pub async fn delete( + &self, + ) -> Result> { + let params = presets_api::DeletePresetParams { + preset_id: self.preset_id.to_string(), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { presets_api::delete_preset(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/presets.rs b/typesense/src/client/presets.rs new file mode 100644 index 0000000..ee82ed0 --- /dev/null +++ b/typesense/src/client/presets.rs @@ -0,0 +1,59 @@ +//! Provides access to the API endpoints for managing presets. +//! +//! Presets are a set of search parameters that can be applied to a search query by using the `preset` search parameter. +//! +//! A `Presets` instance is created via the main `Client::presets()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, presets_api}, + models, +}; + +/// Provides methods for managing all of your Typesense presets. +/// +/// This struct is created by calling `client.presets()`. +pub struct Presets<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Presets<'a> { + /// Creates a new `Presets` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Retrieves the details of all presets. + pub async fn retrieve( + &self, + ) -> Result> { + self.client + .execute(|config: Arc| async move { + presets_api::retrieve_all_presets(&config).await + }) + .await + } + + /// Creates or updates an existing preset. + /// + /// # Arguments + /// * `preset_id` - The ID of the preset to create or update. + /// * `schema` - A `PresetUpsertSchema` object with the preset's value. + pub async fn upsert( + &self, + preset_id: &str, + schema: models::PresetUpsertSchema, + ) -> Result> { + let params = presets_api::UpsertPresetParams { + preset_id: preset_id.to_string(), + preset_upsert_schema: schema, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { presets_api::upsert_preset(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/stemming/dictionaries.rs b/typesense/src/client/stemming/dictionaries.rs new file mode 100644 index 0000000..480e252 --- /dev/null +++ b/typesense/src/client/stemming/dictionaries.rs @@ -0,0 +1,62 @@ +//! Provides access to the API endpoints for managing the collection of stemming dictionaries. +//! +//! A `Dictionaries` instance is created via the `Client::stemming().dictionaries()` method. + +use crate::client::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, stemming_api}, + models, +}; + +/// Provides methods for interacting with the collection of stemming dictionaries. +/// +/// This struct is created by calling `client.stemming().dictionaries()`. +pub struct Dictionaries<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Dictionaries<'a> { + /// Creates a new `Dictionaries` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Imports a stemming dictionary from a JSONL file content. + /// + /// This creates or updates a dictionary with the given ID. + /// + /// # Arguments + /// * `dictionary_id` - The ID to assign to the dictionary. + /// * `dictionary_jsonl` - A string containing the word mappings in JSONL format. + pub async fn import( + &self, + dictionary_id: &str, + dictionary_jsonl: String, + ) -> Result> { + let params = stemming_api::ImportStemmingDictionaryParams { + id: dictionary_id.to_string(), + body: dictionary_jsonl, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { stemming_api::import_stemming_dictionary(&config, params_for_move).await } + }) + .await + } + + /// Retrieves a list of all available stemming dictionaries. + pub async fn retrieve( + &self, + ) -> Result< + models::ListStemmingDictionaries200Response, + Error, + > { + self.client + .execute(|config: Arc| async move { + stemming_api::list_stemming_dictionaries(&config).await + }) + .await + } +} diff --git a/typesense/src/client/stemming/dictionary.rs b/typesense/src/client/stemming/dictionary.rs new file mode 100644 index 0000000..223c029 --- /dev/null +++ b/typesense/src/client/stemming/dictionary.rs @@ -0,0 +1,43 @@ +//! Provides access to the API endpoints for managing a single stemming dictionary. +//! +//! An instance of `Dictionary` is created via the `Client::stemming().dictionary()` method. + +use crate::client::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, stemming_api}, + models, +}; + +/// Provides methods for interacting with a specific stemming dictionary. +/// +/// This struct is created by calling `client.stemming().dictionary("dictionary_id")`. +pub struct Dictionary<'a> { + pub(super) client: &'a Client, + pub(super) dictionary_id: &'a str, +} + +impl<'a> Dictionary<'a> { + /// Creates a new `Dictionary` instance for a specific dictionary ID. + pub(super) fn new(client: &'a Client, dictionary_id: &'a str) -> Self { + Self { + client, + dictionary_id, + } + } + + /// Retrieves the details of this specific stemming dictionary. + pub async fn retrieve( + &self, + ) -> Result> { + let params = stemming_api::GetStemmingDictionaryParams { + dictionary_id: self.dictionary_id.to_string(), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { stemming_api::get_stemming_dictionary(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/stemming/mod.rs b/typesense/src/client/stemming/mod.rs new file mode 100644 index 0000000..997d27c --- /dev/null +++ b/typesense/src/client/stemming/mod.rs @@ -0,0 +1,37 @@ +//! Provides access to the API endpoints for managing stemming. +//! +//! An instance of `Stemming` is created via the `Client::stemming()` method. + +pub mod dictionaries; +pub mod dictionary; + +use super::Client; +use dictionaries::Dictionaries; +use dictionary::Dictionary; + +/// Provides methods for managing Typesense stemming. +/// +/// This struct is created by calling `client.stemming()`. +pub struct Stemming<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Stemming<'a> { + /// Creates a new `Stemming` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Provides access to endpoints for managing the collection of dictionaries. + pub fn dictionaries(&self) -> Dictionaries<'a> { + Dictionaries::new(self.client) + } + + /// Provides access to endpoints for managing a single dictionary. + /// + /// # Arguments + /// * `dictionary_id` - The ID of the dictionary to manage. + pub fn dictionary(&self, dictionary_id: &'a str) -> Dictionary<'a> { + Dictionary::new(self.client, dictionary_id) + } +} diff --git a/typesense/src/client/stopword.rs b/typesense/src/client/stopword.rs new file mode 100644 index 0000000..6917238 --- /dev/null +++ b/typesense/src/client/stopword.rs @@ -0,0 +1,57 @@ +//! Provides access to the API endpoints for managing a single stopwords set. +//! +//! An instance of `Stopword` is created via the `Client::stopword()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, stopwords_api}, + models, +}; + +/// Provides methods for interacting with a specific stopwords set. +/// +/// This struct is created by calling `client.stopword("set_id")`. +pub struct Stopword<'a> { + pub(super) client: &'a Client, + pub(super) set_id: &'a str, +} + +impl<'a> Stopword<'a> { + /// Creates a new `Stopword` instance for a specific set ID. + pub(super) fn new(client: &'a Client, set_id: &'a str) -> Self { + Self { client, set_id } + } + + /// Retrieves the details of this specific stopwords set. + pub async fn retrieve( + &self, + ) -> Result> + { + let params = stopwords_api::RetrieveStopwordsSetParams { + set_id: self.set_id.to_string(), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { stopwords_api::retrieve_stopwords_set(&config, params_for_move).await } + }) + .await + } + + /// Permanently deletes this specific stopwords set. + pub async fn delete( + &self, + ) -> Result> + { + let params = stopwords_api::DeleteStopwordsSetParams { + set_id: self.set_id.to_string(), + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { stopwords_api::delete_stopwords_set(&config, params_for_move).await } + }) + .await + } +} diff --git a/typesense/src/client/stopwords.rs b/typesense/src/client/stopwords.rs new file mode 100644 index 0000000..dbbb9b0 --- /dev/null +++ b/typesense/src/client/stopwords.rs @@ -0,0 +1,60 @@ +//! Provides access to the API endpoints for managing stopwords sets. +//! +//! A `Stopwords` instance is created via the main `Client::stopwords()` method. + +use super::{Client, Error}; +use std::sync::Arc; +use typesense_codegen::{ + apis::{configuration, stopwords_api}, + models, +}; + +/// Provides methods for managing Typesense stopwords sets. +/// +/// This struct is created by calling `client.stopwords()`. +pub struct Stopwords<'a> { + pub(super) client: &'a Client, +} + +impl<'a> Stopwords<'a> { + /// Creates a new `Stopwords` instance. + pub(super) fn new(client: &'a Client) -> Self { + Self { client } + } + + /// Creates or updates an existing stopwords set. + /// + /// # Arguments + /// * `set_id` - The ID of the stopwords set to create or update. + /// * `schema` - A `StopwordsSetUpsertSchema` object with the stopwords to upsert. + pub async fn upsert( + &self, + set_id: &str, + schema: models::StopwordsSetUpsertSchema, + ) -> Result> { + let params = stopwords_api::UpsertStopwordsSetParams { + set_id: set_id.to_string(), + stopwords_set_upsert_schema: schema, + }; + self.client + .execute(|config: Arc| { + let params_for_move = params.clone(); + async move { stopwords_api::upsert_stopwords_set(&config, params_for_move).await } + }) + .await + } + + /// Retrieves the details of all stopwords sets. + pub async fn retrieve( + &self, + ) -> Result< + models::StopwordsSetsRetrieveAllSchema, + Error, + > { + self.client + .execute(|config: Arc| async move { + stopwords_api::retrieve_stopwords_sets(&config).await + }) + .await + } +} diff --git a/typesense/src/collection_schema.rs b/typesense/src/collection_schema.rs index c28207a..0951e76 100644 --- a/typesense/src/collection_schema.rs +++ b/typesense/src/collection_schema.rs @@ -82,6 +82,7 @@ impl CollectionSchemaBuilder { token_separators: self.token_separators, enable_nested_fields: self.enable_nested_fields, symbols_to_index: self.symbols_to_index, + ..Default::default() } } } diff --git a/typesense/src/field/mod.rs b/typesense/src/field/mod.rs index 934abed..4cd98b6 100644 --- a/typesense/src/field/mod.rs +++ b/typesense/src/field/mod.rs @@ -105,6 +105,7 @@ impl FieldBuilder { num_dim: self.num_dim, drop: self.drop, embed: self.embed, + ..Default::default() } } } diff --git a/typesense/src/lib.rs b/typesense/src/lib.rs index 286c959..b0a85fa 100644 --- a/typesense/src/lib.rs +++ b/typesense/src/lib.rs @@ -43,6 +43,7 @@ //! } //! ``` +pub mod client; pub mod collection_schema; pub mod document; pub mod field; diff --git a/typesense/tests/api/collection.rs b/typesense/tests/api/collection.rs index d11bfb0..ecb4b2f 100644 --- a/typesense/tests/api/collection.rs +++ b/typesense/tests/api/collection.rs @@ -1,136 +1,136 @@ -#![allow(dead_code)] - -use super::Config; -use serde::{Deserialize, Serialize}; -use typesense::document::Document; -use typesense::Typesense; -use typesense_codegen::apis::collections_api; -use typesense_codegen::models::{CollectionResponse, CollectionSchema}; - -#[derive(Typesense, Serialize, Deserialize)] -#[typesense(collection_name = "companies", default_sorting_field = "num_employees")] -struct Company { - company_name: String, - num_employees: i32, - #[typesense(facet)] - country: String, -} - -fn schema_to_resp(schema: CollectionSchema, resp: &CollectionResponse) -> CollectionResponse { - CollectionResponse { - name: schema.name, - fields: schema.fields, - default_sorting_field: schema.default_sorting_field, - token_separators: schema.token_separators, - enable_nested_fields: schema.enable_nested_fields, - symbols_to_index: schema.symbols_to_index, - num_documents: resp.num_documents, - created_at: resp.created_at, - } -} - -async fn create_collection() { - let collection_schema_response = - collections_api::create_collection(Config::get(), Company::collection_schema()) - .await - .unwrap(); - - assert_eq!(collection_schema_response.num_documents, 0); - assert_eq!( - schema_to_resp(Company::collection_schema(), &collection_schema_response), - collection_schema_response - ); -} - -async fn get_collection() { - let collection_schema_response = collections_api::get_collection(Config::get(), "companies") - .await - .unwrap(); - - assert_eq!(collection_schema_response.num_documents, 1250); - assert_eq!( - schema_to_resp(Company::collection_schema(), &collection_schema_response), - collection_schema_response - ); -} - -async fn delete_collection() { - let collection_schema_response = collections_api::delete_collection(Config::get(), "companies") - .await - .unwrap(); - - assert_eq!(collection_schema_response.num_documents, 1200); - assert_eq!( - schema_to_resp(Company::collection_schema(), &collection_schema_response), - collection_schema_response - ); -} - -async fn get_collections() { - let collection_schema_response = collections_api::get_collections(Config::get()) - .await - .unwrap(); - - assert_eq!(collection_schema_response.len(), 2); -} - -#[cfg(all(feature = "tokio_test", not(target_arch = "wasm32")))] -mod tokio_test { - use super::*; - - #[tokio::test] - async fn create_collection_tokio() { - create_collection().await - } - - #[tokio::test] - async fn get_collection_tokio() { - get_collection().await - } - - #[tokio::test] - async fn delete_collection_tokio() { - delete_collection().await - } - - #[tokio::test] - async fn get_collections_tokio() { - get_collections().await - } -} - -#[cfg(target_arch = "wasm32")] -mod wasm_test { - use super::*; - use wasm_bindgen_test::wasm_bindgen_test; - - wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); - - #[wasm_bindgen_test] - async fn create_collection_wasm() { - console_error_panic_hook::set_once(); - - create_collection().await - } - - #[wasm_bindgen_test] - async fn get_collection_wasm() { - console_error_panic_hook::set_once(); - - get_collection().await - } - - #[wasm_bindgen_test] - async fn delete_collection_wasm() { - console_error_panic_hook::set_once(); - - delete_collection().await - } - - #[wasm_bindgen_test] - async fn get_collections_wasm() { - console_error_panic_hook::set_once(); - - get_collections().await - } -} +// #![allow(dead_code)] + +// use super::Config; +// use serde::{Deserialize, Serialize}; +// use typesense::document::Document; +// use typesense::Typesense; +// use typesense_codegen::apis::collections_api; +// use typesense_codegen::models::{CollectionResponse, CollectionSchema}; + +// #[derive(Typesense, Serialize, Deserialize)] +// #[typesense(collection_name = "companies", default_sorting_field = "num_employees")] +// struct Company { +// company_name: String, +// num_employees: i32, +// #[typesense(facet)] +// country: String, +// } + +// fn schema_to_resp(schema: CollectionSchema, resp: &CollectionResponse) -> CollectionResponse { +// CollectionResponse { +// name: schema.name, +// fields: schema.fields, +// default_sorting_field: schema.default_sorting_field, +// token_separators: schema.token_separators, +// enable_nested_fields: schema.enable_nested_fields, +// symbols_to_index: schema.symbols_to_index, +// num_documents: resp.num_documents, +// created_at: resp.created_at, +// } +// } + +// async fn create_collection() { +// let collection_schema_response = +// collections_api::create_collection(Config::get(), Company::collection_schema()) +// .await +// .unwrap(); + +// assert_eq!(collection_schema_response.num_documents, 0); +// assert_eq!( +// schema_to_resp(Company::collection_schema(), &collection_schema_response), +// collection_schema_response +// ); +// } + +// async fn get_collection() { +// let collection_schema_response = collections_api::get_collection(Config::get(), "companies") +// .await +// .unwrap(); + +// assert_eq!(collection_schema_response.num_documents, 1250); +// assert_eq!( +// schema_to_resp(Company::collection_schema(), &collection_schema_response), +// collection_schema_response +// ); +// } + +// async fn delete_collection() { +// let collection_schema_response = collections_api::delete_collection(Config::get(), "companies") +// .await +// .unwrap(); + +// assert_eq!(collection_schema_response.num_documents, 1200); +// assert_eq!( +// schema_to_resp(Company::collection_schema(), &collection_schema_response), +// collection_schema_response +// ); +// } + +// async fn get_collections() { +// let collection_schema_response = collections_api::get_collections(Config::get()) +// .await +// .unwrap(); + +// assert_eq!(collection_schema_response.len(), 2); +// } + +// #[cfg(all(feature = "tokio_test", not(target_arch = "wasm32")))] +// mod tokio_test { +// use super::*; + +// #[tokio::test] +// async fn create_collection_tokio() { +// create_collection().await +// } + +// #[tokio::test] +// async fn get_collection_tokio() { +// get_collection().await +// } + +// #[tokio::test] +// async fn delete_collection_tokio() { +// delete_collection().await +// } + +// #[tokio::test] +// async fn get_collections_tokio() { +// get_collections().await +// } +// } + +// #[cfg(target_arch = "wasm32")] +// mod wasm_test { +// use super::*; +// use wasm_bindgen_test::wasm_bindgen_test; + +// wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); + +// #[wasm_bindgen_test] +// async fn create_collection_wasm() { +// console_error_panic_hook::set_once(); + +// create_collection().await +// } + +// #[wasm_bindgen_test] +// async fn get_collection_wasm() { +// console_error_panic_hook::set_once(); + +// get_collection().await +// } + +// #[wasm_bindgen_test] +// async fn delete_collection_wasm() { +// console_error_panic_hook::set_once(); + +// delete_collection().await +// } + +// #[wasm_bindgen_test] +// async fn get_collections_wasm() { +// console_error_panic_hook::set_once(); + +// get_collections().await +// } +// } diff --git a/typesense/tests/api/documents.rs b/typesense/tests/api/documents.rs index 885d56d..c8e8f5b 100644 --- a/typesense/tests/api/documents.rs +++ b/typesense/tests/api/documents.rs @@ -1,111 +1,111 @@ -#![allow(dead_code)] - -use super::Config; -use serde::{Deserialize, Serialize}; -use typesense::document::Document; -use typesense::models::SearchParameters; -use typesense::Typesense; -use typesense_codegen::apis::documents_api; - -#[derive(Typesense, Serialize, Deserialize)] -#[typesense(collection_name = "companies", default_sorting_field = "num_employees")] -struct Company { - company_name: String, - num_employees: i32, - #[typesense(facet)] - country: String, -} - -async fn import_documents() { - let documents = [ - Company { - company_name: "test".to_owned(), - num_employees: 1, - country: "c1".to_owned(), - }, - Company { - company_name: "test2".to_owned(), - num_employees: 2, - country: "c2".to_owned(), - }, - ] - .map(|c| serde_json::to_string(&c).unwrap()) - .join("\n"); - - let resp = documents_api::import_documents( - Config::get(), - &Company::collection_schema().name, - documents, - None, - ) - .await - .unwrap(); - - assert_eq!(&resp, "{\"success\":true}\n{\"success\":true}"); -} - -async fn search_collection() { - let search = SearchParameters { - q: "test".to_owned(), - query_by: "company_name".to_owned(), - ..Default::default() - }; - - let resp = documents_api::search_collection::( - Config::get(), - &Company::collection_schema().name, - search, - ) - .await - .unwrap(); - - assert_eq!(resp.found, Some(2)); - assert_eq!( - resp.hits - .unwrap() - .first() - .unwrap() - .document - .as_ref() - .unwrap() - .company_name, - "test".to_owned() - ); -} - -#[cfg(all(feature = "tokio_test", not(target_arch = "wasm32")))] -mod tokio_test { - use super::*; - - #[tokio::test] - async fn import_documents_tokio() { - import_documents().await - } - - #[tokio::test] - async fn search_collection_tokio() { - search_collection().await - } -} - -#[cfg(target_arch = "wasm32")] -mod wasm_test { - use super::*; - use wasm_bindgen_test::wasm_bindgen_test; - - wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); - - #[wasm_bindgen_test] - async fn import_documents_wasm() { - console_error_panic_hook::set_once(); - - import_documents().await - } - - #[wasm_bindgen_test] - async fn search_collection_wasm() { - console_error_panic_hook::set_once(); - - search_collection().await - } -} +// #![allow(dead_code)] + +// use super::Config; +// use serde::{Deserialize, Serialize}; +// use typesense::document::Document; +// use typesense::models::SearchParameters; +// use typesense::Typesense; +// use typesense_codegen::apis::documents_api; + +// #[derive(Typesense, Serialize, Deserialize)] +// #[typesense(collection_name = "companies", default_sorting_field = "num_employees")] +// struct Company { +// company_name: String, +// num_employees: i32, +// #[typesense(facet)] +// country: String, +// } + +// async fn import_documents() { +// let documents = [ +// Company { +// company_name: "test".to_owned(), +// num_employees: 1, +// country: "c1".to_owned(), +// }, +// Company { +// company_name: "test2".to_owned(), +// num_employees: 2, +// country: "c2".to_owned(), +// }, +// ] +// .map(|c| serde_json::to_string(&c).unwrap()) +// .join("\n"); + +// let resp = documents_api::import_documents( +// Config::get(), +// &Company::collection_schema().name, +// documents, +// None, +// ) +// .await +// .unwrap(); + +// assert_eq!(&resp, "{\"success\":true}\n{\"success\":true}"); +// } + +// async fn search_collection() { +// let search = SearchParameters { +// q: "test".to_owned(), +// query_by: "company_name".to_owned(), +// ..Default::default() +// }; + +// let resp = documents_api::search_collection::( +// Config::get(), +// &Company::collection_schema().name, +// search, +// ) +// .await +// .unwrap(); + +// assert_eq!(resp.found, Some(2)); +// assert_eq!( +// resp.hits +// .unwrap() +// .first() +// .unwrap() +// .document +// .as_ref() +// .unwrap() +// .company_name, +// "test".to_owned() +// ); +// } + +// #[cfg(all(feature = "tokio_test", not(target_arch = "wasm32")))] +// mod tokio_test { +// use super::*; + +// #[tokio::test] +// async fn import_documents_tokio() { +// import_documents().await +// } + +// #[tokio::test] +// async fn search_collection_tokio() { +// search_collection().await +// } +// } + +// #[cfg(target_arch = "wasm32")] +// mod wasm_test { +// use super::*; +// use wasm_bindgen_test::wasm_bindgen_test; + +// wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); + +// #[wasm_bindgen_test] +// async fn import_documents_wasm() { +// console_error_panic_hook::set_once(); + +// import_documents().await +// } + +// #[wasm_bindgen_test] +// async fn search_collection_wasm() { +// console_error_panic_hook::set_once(); + +// search_collection().await +// } +// } diff --git a/typesense/tests/api/lib.rs b/typesense/tests/api/lib.rs index 94a3985..b36f5a3 100644 --- a/typesense/tests/api/lib.rs +++ b/typesense/tests/api/lib.rs @@ -1,41 +1,41 @@ -use std::sync::OnceLock; -use typesense_codegen::apis::configuration::{ApiKey, Configuration}; - -mod collection; -mod documents; - -static CONFIG: OnceLock = OnceLock::new(); - -#[cfg(not(target_arch = "wasm32"))] -fn init() -> Configuration { - let _ = dotenvy::dotenv(); - - let base_path = std::env::var("URL").expect("URL must be present in .env"); - let key = std::env::var("API_KEY").expect("API_KEY must be present in .env"); - - Configuration { - base_path, - api_key: Some(ApiKey { prefix: None, key }), - ..Default::default() - } -} - -#[cfg(target_arch = "wasm32")] -fn init() -> Configuration { - let base_path = "http://localhost:5000".to_owned(); - let key = "VerySecretKey".to_owned(); - - Configuration { - base_path, - api_key: Some(ApiKey { prefix: None, key }), - ..Default::default() - } -} - -pub struct Config; - -impl Config { - pub fn get() -> &'static Configuration { - CONFIG.get_or_init(init) - } -} +// use std::sync::OnceLock; +// use typesense_codegen::apis::configuration::{ApiKey, Configuration}; + +// mod collection; +// mod documents; + +// static CONFIG: OnceLock = OnceLock::new(); + +// #[cfg(not(target_arch = "wasm32"))] +// fn init() -> Configuration { +// let _ = dotenvy::dotenv(); + +// let base_path = std::env::var("URL").expect("URL must be present in .env"); +// let key = std::env::var("API_KEY").expect("API_KEY must be present in .env"); + +// Configuration { +// base_path, +// api_key: Some(ApiKey { prefix: None, key }), +// ..Default::default() +// } +// } + +// #[cfg(target_arch = "wasm32")] +// fn init() -> Configuration { +// let base_path = "http://localhost:5000".to_owned(); +// let key = "VerySecretKey".to_owned(); + +// Configuration { +// base_path, +// api_key: Some(ApiKey { prefix: None, key }), +// ..Default::default() +// } +// } + +// pub struct Config; + +// impl Config { +// pub fn get() -> &'static Configuration { +// CONFIG.get_or_init(init) +// } +// } diff --git a/typesense/tests/client/aliases_test.rs b/typesense/tests/client/aliases_test.rs new file mode 100644 index 0000000..4a3c6b9 --- /dev/null +++ b/typesense/tests/client/aliases_test.rs @@ -0,0 +1,92 @@ +use typesense_codegen::models::{CollectionAliasSchema, CollectionSchema, Field}; + +use super::{get_client, new_id}; + +#[tokio::test] +async fn test_aliases_and_alias_lifecycle() { + let client = get_client(); + let collection_name = new_id("products"); + let alias_name = new_id("products_alias"); + + // --- 1. Create a collection to alias to --- + let collection_schema = CollectionSchema { + name: collection_name.clone(), + fields: vec![Field { + name: "name".to_string(), + r#type: "string".to_string(), + ..Default::default() + }], + ..Default::default() + }; + + let create_collection_result = client.collections().create(collection_schema).await; + assert!( + create_collection_result.is_ok(), + "Failed to create collection for alias test" + ); + + // --- 2. Create (Upsert) an alias --- + let alias_schema = CollectionAliasSchema { + collection_name: collection_name.clone(), + }; + + let upsert_result = client.aliases().upsert(&alias_name, alias_schema).await; + assert!(upsert_result.is_ok(), "Failed to create alias"); + let created_alias = upsert_result.unwrap(); + assert_eq!(created_alias.name, alias_name); + assert_eq!(created_alias.collection_name, collection_name); + + // --- 3. Retrieve the specific alias by name --- + let retrieve_one_result = client.alias(&alias_name).retrieve().await; + assert!( + retrieve_one_result.is_ok(), + "Failed to retrieve the specific alias." + ); + let retrieved_alias = retrieve_one_result.unwrap(); + assert_eq!(retrieved_alias.name, alias_name); + assert_eq!(retrieved_alias.collection_name, collection_name); + + // --- 4. Retrieve all aliases --- + let retrieve_all_result = client.aliases().retrieve().await; + assert!( + retrieve_all_result.is_ok(), + "Failed to retrieve the list of aliases." + ); + let all_aliases_response = retrieve_all_result.unwrap(); + + // --- 5. Find our specific alias within the list --- + let our_alias = all_aliases_response + .aliases + .iter() + .find(|a| a.name == alias_name); + + assert!( + our_alias.is_some(), + "The newly created alias was not found in the list." + ); + + if let Some(alias) = our_alias { + assert_eq!(alias.name, alias_name); + assert_eq!(alias.collection_name, collection_name); + } + + // --- 6. Delete the alias --- + let delete_result = client.alias(&alias_name).delete().await; + assert!(delete_result.is_ok(), "Failed to delete alias"); + let deleted_alias = delete_result.unwrap(); + assert_eq!(deleted_alias.name, alias_name); + + // --- 7. Verify Deletion --- + let get_after_delete_result = client.alias(&alias_name).retrieve().await; + assert!( + get_after_delete_result.is_err(), + "Alias should not exist after deletion" + ); + + // --- 8. Clean up the collection --- + let delete_collection_result = client.collection(&collection_name).delete().await; + assert!( + delete_collection_result.is_ok(), + "Failed to delete collection after alias test" + ); +} diff --git a/typesense/tests/client/analytics_test.rs b/typesense/tests/client/analytics_test.rs new file mode 100644 index 0000000..4d14fdd --- /dev/null +++ b/typesense/tests/client/analytics_test.rs @@ -0,0 +1,123 @@ +use super::{get_client, new_id}; +use serde_json::json; +use typesense::models::analytics_rule_schema::Type::Counter; +use typesense::models::{ + self, AnalyticsEventCreateSchema, AnalyticsRuleParametersDestination, + AnalyticsRuleParametersSource, AnalyticsRuleParametersSourceEventsInner, AnalyticsRuleSchema, +}; +use typesense_codegen::models::{CollectionSchema, Field}; + +#[tokio::test] +async fn test_analytics_rules_and_events_lifecycle() { + let client = get_client(); + let rule_name_1 = new_id("product_clicks"); + let collection_name = new_id("products"); + let event_name = "products_click_event"; + + // --- 1. Create a Collection (via `collections`) --- + let schema = CollectionSchema { + name: collection_name.clone(), + fields: vec![ + Field { + name: "title".to_string(), + r#type: "string".to_string(), + ..Default::default() + }, + Field { + name: "popularity".to_string(), + r#type: "int32".to_string(), + optional: Some(true), + ..Default::default() + }, + ], + ..Default::default() + }; + + let create_result = client.collections().create(schema).await; + assert!(create_result.is_ok(), "Failed to create collection"); + let created_collection = create_result.unwrap(); + assert_eq!(created_collection.name, collection_name); + + // --- 2. Create a Rule (via `rules.create`) --- + let create_schema = AnalyticsRuleSchema { + name: rule_name_1.clone(), + r#type: Counter, + params: Box::new(models::AnalyticsRuleParameters { + source: Box::new(AnalyticsRuleParametersSource { + collections: vec!["products".to_string()], + events: Some(vec![AnalyticsRuleParametersSourceEventsInner { + r#type: "click".to_string(), + weight: 1.0, + name: event_name.to_owned(), + }]), + }), + destination: Box::new(AnalyticsRuleParametersDestination { + collection: "products".to_string(), + counter_field: Some("popularity".to_string()), + }), + ..Default::default() + }), + }; + + let create_result = client.analytics().rules().create(create_schema).await; + assert!(create_result.is_ok(), "Failed to create analytics rule"); + let created_rule = create_result.unwrap(); + assert_eq!(created_rule.name, rule_name_1); + assert_eq!(created_rule.r#type, Counter); + + // --- 3. Retrieve the specific Rule (via `rule`) --- + let retrieve_one_result = client.analytics().rule(&rule_name_1).retrieve().await; + assert!( + retrieve_one_result.is_ok(), + "Failed to retrieve the newly created rule." + ); + let retrieved_rule = retrieve_one_result.unwrap(); + assert_eq!(retrieved_rule.name, rule_name_1); + + // --- 4. Retrieve all Rules (via `rules`) --- + let retrieve_all_result = client.analytics().rules().retrieve().await; + assert!( + retrieve_all_result.is_ok(), + "Failed to retrieve the list of rules." + ); + let all_rules_response = retrieve_all_result.unwrap(); + assert!( + all_rules_response.rules.as_ref().unwrap().len() >= 1, + "Expected at least one rule to be present." + ); + assert!(all_rules_response + .rules + .unwrap() + .iter() + .any(|r| r.name == rule_name_1)); + + // --- 5. Sending click events (via `events`) --- + let event_result = client + .analytics() + .events() + .create(AnalyticsEventCreateSchema { + r#type: "click".to_string(), + name: event_name.to_owned(), + data: json!({ + "doc_id": "1024", + "user_id": "111112" + }), + }) + .await; + + assert!(event_result.is_ok(), "Failed to send the click event."); + assert!(event_result.unwrap().ok, "Unsuccessful click event."); + + // --- 6. Delete a Rule (via `rule`) --- + let delete_result = client.analytics().rule(&rule_name_1).delete().await; + assert!(delete_result.is_ok(), "Failed to delete rule"); + let deleted_response = delete_result.unwrap(); + assert_eq!(deleted_response.name, rule_name_1); + + // --- 7. Verify Deletion --- + let get_after_delete_result = client.analytics().rule(&rule_name_1).retrieve().await; + assert!( + get_after_delete_result.is_err(), + "Rule should not exist after deletion" + ); +} diff --git a/typesense/tests/client/client_test.rs b/typesense/tests/client/client_test.rs new file mode 100644 index 0000000..626d22c --- /dev/null +++ b/typesense/tests/client/client_test.rs @@ -0,0 +1,326 @@ +use reqwest::Url; +use reqwest_retry::policies::ExponentialBackoff; +use std::time::Duration; +use typesense::client::*; +use typesense::models::CollectionResponse; +use wiremock::matchers::{header, method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +// Helper to create a mock Typesense server for a successful collection retrieval. +async fn setup_mock_server_ok(server: &MockServer, collection_name: &str) { + let response_body = CollectionResponse { + name: collection_name.to_string(), + ..Default::default() + }; + + Mock::given(method("GET")) + .and(path(format!("/collections/{}", collection_name))) + .and(header("X-TYPESENSE-API-KEY", "test-key")) + .respond_with(ResponseTemplate::new(200).set_body_json(response_body)) + .mount(server) + .await; +} + +// Helper to create a mock Typesense server that returns a server error. +async fn setup_mock_server_503(server: &MockServer, collection_name: &str) { + Mock::given(method("GET")) + .and(path(format!("/collections/{}", collection_name))) + .respond_with(ResponseTemplate::new(503)) + .mount(server) + .await; +} + +// Helper to create a mock Typesense server that returns a 404 Not Found error. +async fn setup_mock_server_404(server: &MockServer, collection_name: &str) { + Mock::given(method("GET")) + .and(path(format!("/collections/{}", collection_name))) + .respond_with(ResponseTemplate::new(404)) + .mount(server) + .await; +} + +// Helper function to create a client configuration for tests. +fn get_test_config(nodes: Vec, nearest_node: Option) -> MultiNodeConfiguration { + MultiNodeConfiguration { + nodes, + nearest_node, + api_key: "test-key".to_string(), + healthcheck_interval: Duration::from_secs(60), + retry_policy: ExponentialBackoff::builder().build_with_max_retries(0), + connection_timeout: Duration::from_secs(1), + } +} + +#[tokio::test] +async fn test_success_on_first_node() { + let server1 = MockServer::start().await; + setup_mock_server_ok(&server1, "products").await; + + let config = get_test_config(vec![Url::parse(&server1.uri()).unwrap()], None); + let client = Client::new(config).unwrap(); + + let result = client.collection("products").retrieve().await; + + assert!(result.is_ok()); + assert_eq!(result.unwrap().name, "products"); + // Check that the server received exactly one request. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); +} + +#[tokio::test] +async fn test_failover_to_second_node() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + setup_mock_server_503(&server1, "products").await; + setup_mock_server_ok(&server2, "products").await; + + let config = get_test_config( + vec![ + Url::parse(&server1.uri()).unwrap(), + Url::parse(&server2.uri()).unwrap(), + ], + None, + ); + let client = Client::new(config).unwrap(); + + let result = client.collection("products").retrieve().await; + assert!(result.is_ok()); + + // The first server should have been tried and failed. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + // The second server should have been tried and succeeded. + assert_eq!(server2.received_requests().await.unwrap().len(), 1); +} + +#[tokio::test] +async fn test_nearest_node_is_prioritized() { + let nearest_server = MockServer::start().await; + let regular_server = MockServer::start().await; + setup_mock_server_ok(&nearest_server, "products").await; + setup_mock_server_ok(®ular_server, "products").await; + + let config = get_test_config( + vec![Url::parse(®ular_server.uri()).unwrap()], + Some(Url::parse(&nearest_server.uri()).unwrap()), + ); + let client = Client::new(config).unwrap(); + + let result = client.collection("products").retrieve().await; + assert!(result.is_ok()); + + // Only the nearest node should have received a request. + assert_eq!(nearest_server.received_requests().await.unwrap().len(), 1); + assert_eq!(regular_server.received_requests().await.unwrap().len(), 0); +} + +#[tokio::test] +async fn test_failover_from_nearest_to_regular_node() { + let nearest_server = MockServer::start().await; + let regular_server = MockServer::start().await; + setup_mock_server_503(&nearest_server, "products").await; + setup_mock_server_ok(®ular_server, "products").await; + + let config = get_test_config( + vec![Url::parse(®ular_server.uri()).unwrap()], + Some(Url::parse(&nearest_server.uri()).unwrap()), + ); + let client = Client::new(config).unwrap(); + + let result = client.collection("products").retrieve().await; + assert!(result.is_ok()); + + // Nearest node should have failed. + assert_eq!(nearest_server.received_requests().await.unwrap().len(), 1); + // Regular node should have succeeded. + assert_eq!(regular_server.received_requests().await.unwrap().len(), 1); +} + +#[tokio::test] +async fn test_round_robin_failover() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + let server3 = MockServer::start().await; + setup_mock_server_503(&server1, "products").await; + setup_mock_server_503(&server2, "products").await; + setup_mock_server_ok(&server3, "products").await; + + let config = get_test_config( + vec![ + Url::parse(&server1.uri()).unwrap(), + Url::parse(&server2.uri()).unwrap(), + Url::parse(&server3.uri()).unwrap(), + ], + None, + ); + let client = Client::new(config).unwrap(); + + // First request should fail over to the third node + let result = client.collection("products").retrieve().await; + assert!(result.is_ok()); + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + assert_eq!(server2.received_requests().await.unwrap().len(), 1); + assert_eq!(server3.received_requests().await.unwrap().len(), 1); + + // The next request should start from the now-healthy 3rd node, but round-robin + // logic will have advanced the internal counter. Let's see it wrap around. + // We expect the next attempt to be on server 3 again, then 1 (if 3 fails). + + // Reset server 3 to also fail + server3.reset().await; + setup_mock_server_503(&server3, "products").await; + // Make server 1 healthy again + server1.reset().await; + setup_mock_server_ok(&server1, "products").await; + + let result2 = client.collection("products").retrieve().await; + assert!(result2.is_ok()); + + // Server 3 was tried first and failed. + assert_eq!(server3.received_requests().await.unwrap().len(), 1); + // Server 1 was tried next and succeeded. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + // Server 2 was not touched this time. + assert_eq!(server2.received_requests().await.unwrap().len(), 1); // Remains 1 from first call +} + +#[tokio::test] +async fn test_health_check_and_node_recovery() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + + setup_mock_server_503(&server1, "products").await; + setup_mock_server_ok(&server2, "products").await; + + let mut config = get_test_config( + vec![ + Url::parse(&server1.uri()).unwrap(), + Url::parse(&server2.uri()).unwrap(), + ], + None, + ); + // Use a very short healthcheck interval for the test + config.healthcheck_interval = Duration::from_millis(500); + let client = Client::new(config).unwrap(); + + // 1. First request fails over to server2, marking server1 as unhealthy. + assert!(client.collection("products").retrieve().await.is_ok()); + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + assert_eq!(server2.received_requests().await.unwrap().len(), 1); + + // 2. Immediate second request should go directly to server2. + assert!(client.collection("products").retrieve().await.is_ok()); + assert_eq!(server1.received_requests().await.unwrap().len(), 1); // No new request + assert_eq!(server2.received_requests().await.unwrap().len(), 2); // Got another request + + // 3. Wait for the healthcheck interval to pass. + tokio::time::sleep(Duration::from_millis(600)).await; + + // 4. Make server1 healthy again. + server1.reset().await; + setup_mock_server_ok(&server1, "products").await; + + // 5. The next request should try server1 again (due to healthcheck expiry) and succeed. + assert!(client.collection("products").retrieve().await.is_ok()); + assert_eq!(server1.received_requests().await.unwrap().len(), 1); // Server 1 received its first successful req + assert_eq!(server2.received_requests().await.unwrap().len(), 2); // No new request for server 2 +} + +#[tokio::test] +async fn test_all_nodes_fail() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + setup_mock_server_503(&server1, "products").await; + setup_mock_server_503(&server2, "products").await; + + let config = get_test_config( + vec![ + Url::parse(&server1.uri()).unwrap(), + Url::parse(&server2.uri()).unwrap(), + ], + None, + ); + let client = Client::new(config).unwrap(); + + let result = client.collection("products").retrieve().await; + assert!(result.is_err()); + + match result.err().unwrap() { + Error::AllNodesFailed { .. } => { /* This is the expected outcome */ } + _ => panic!("Expected AllNodesFailed error"), + } + + // Both servers should have been tried. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + assert_eq!(server2.received_requests().await.unwrap().len(), 1); +} + +#[tokio::test] +async fn test_fail_fast_on_non_retriable_error() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + + setup_mock_server_404(&server1, "products").await; + setup_mock_server_ok(&server2, "products").await; + + let config = get_test_config( + vec![ + Url::parse(&server1.uri()).unwrap(), + Url::parse(&server2.uri()).unwrap(), + ], + None, + ); + let client = Client::new(config).unwrap(); + + let result = client.collection("products").retrieve().await; + assert!(result.is_err()); + + // Check that the error is the non-retriable API error. + match result.err().unwrap() { + Error::Api(typesense_codegen::apis::Error::ResponseError(content)) => { + assert_eq!(content.status, reqwest::StatusCode::NOT_FOUND); + } + e => panic!("Expected an API error, but got {:?}", e), + } + + // The first server should have been tried. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + // The second server should NOT have been tried. + assert_eq!(server2.received_requests().await.unwrap().len(), 0); +} + +#[tokio::test] +async fn test_load_balancing_with_healthy_nodes() { + // 1. Setup three healthy mock servers + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + let server3 = MockServer::start().await; + setup_mock_server_ok(&server1, "products").await; + setup_mock_server_ok(&server2, "products").await; + setup_mock_server_ok(&server3, "products").await; + + // 2. Setup client with the three nodes + let config = get_test_config( + vec![ + Url::parse(&server1.uri()).unwrap(), + Url::parse(&server2.uri()).unwrap(), + Url::parse(&server3.uri()).unwrap(), + ], + None, + ); + let client = Client::new(config).unwrap(); + + // 3. Make three consecutive requests + let result1 = client.collection("products").retrieve().await; + let result2 = client.collection("products").retrieve().await; + let result3 = client.collection("products").retrieve().await; + + // 4. Assert all requests were successful + assert!(result1.is_ok()); + assert!(result2.is_ok()); + assert!(result3.is_ok()); + + // 5. Assert that each server received exactly one request, proving round-robin distribution + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + assert_eq!(server2.received_requests().await.unwrap().len(), 1); + assert_eq!(server3.received_requests().await.unwrap().len(), 1); +} diff --git a/typesense/tests/client/collections_test.rs b/typesense/tests/client/collections_test.rs new file mode 100644 index 0000000..f327233 --- /dev/null +++ b/typesense/tests/client/collections_test.rs @@ -0,0 +1,133 @@ +use typesense_codegen::models::{CollectionSchema, CollectionUpdateSchema, Field}; + +use super::{get_client, new_id}; + +#[tokio::test] +async fn test_collections_and_collection_lifecycle() { + let client = get_client(); + let collection_name = new_id("products"); + + // --- 1. Create a Collection (via `collections`) --- + let schema = CollectionSchema { + name: collection_name.clone(), + fields: vec![ + Field { + name: "name".to_string(), + r#type: "string".to_string(), + ..Default::default() + }, + Field { + name: "price".to_string(), + r#type: "int32".to_string(), + ..Default::default() + }, + ], + ..Default::default() + }; + + let create_result = client.collections().create(schema).await; + assert!(create_result.is_ok(), "Failed to create collection"); + let created_collection = create_result.unwrap(); + assert_eq!(created_collection.name, collection_name); + + // --- 2. Retrieve the specific Collection (via `collection`) --- + let retrieve_one_result = client.collection(&collection_name).retrieve().await; + assert!( + retrieve_one_result.is_ok(), + "Failed to retrieve the newly created collection." + ); + let retrieved_collection = retrieve_one_result.unwrap(); + assert_eq!(retrieved_collection.name, collection_name); + assert_eq!(retrieved_collection.fields.len(), 2); + + // --- 3. Retrieve all collections (via `collections`) --- + let retrieve_all_result = client.collections().retrieve().await; + assert!( + retrieve_all_result.is_ok(), + "Failed to retrieve the list of collections." + ); + let all_collections = retrieve_all_result.unwrap(); + + // --- 4. Find our specific collection within the list --- + let our_collection = all_collections.iter().find(|c| c.name == collection_name); + assert!( + our_collection.is_some(), + "The newly created collection was not found in the list." + ); + + // --- 5. Update the Collection to add and drop a field (via `collection`) --- + let update_schema = CollectionUpdateSchema { + fields: vec![ + // Add a new field + Field { + name: "description".to_string(), + r#type: "string".to_string(), + optional: Some(true), + ..Default::default() + }, + // Drop an existing field + Field { + name: "price".to_string(), + drop: Some(true), + ..Default::default() + }, + ], + }; + + let update_result = client + .collection(&collection_name) + .update(update_schema) + .await; + assert!(update_result.is_ok(), "Failed to update collection"); + + // The update response contains the fields that were modified + let updated_fields_response = update_result.unwrap(); + assert_eq!( + updated_fields_response.fields.len(), + 2, + "The update response should contain the two modified fields." + ); + + // --- 6. Verify the update by retrieving the full schema again --- + let retrieve_after_update_result = client.collection(&collection_name).retrieve().await; + let retrieved_after_update = retrieve_after_update_result.unwrap(); + + // Initial fields: name, price. Update: +description, -price. Final fields: name, description. + assert_eq!( + retrieved_after_update.fields.len(), + 2, + "The number of fields should be 2 after the update." + ); + assert!( + retrieved_after_update + .fields + .iter() + .any(|f| f.name == "name"), + "The 'name' field should still exist." + ); + assert!( + retrieved_after_update + .fields + .iter() + .any(|f| f.name == "description"), + "The 'description' field should have been added." + ); + assert!( + !retrieved_after_update + .fields + .iter() + .any(|f| f.name == "price"), + "The 'price' field should have been dropped." + ); + + // --- 7. Delete the Collection (via `collection`) --- + let delete_result = client.collection(&collection_name).delete().await; + assert!(delete_result.is_ok(), "Failed to delete collection"); + + // --- 8. Verify Deletion --- + let get_after_delete_result = client.collection(&collection_name).retrieve().await; + assert!( + get_after_delete_result.is_err(), + "Collection should not exist after deletion" + ); +} diff --git a/typesense/tests/client/conversation_models_test.rs b/typesense/tests/client/conversation_models_test.rs new file mode 100644 index 0000000..b2d63af --- /dev/null +++ b/typesense/tests/client/conversation_models_test.rs @@ -0,0 +1,353 @@ +use std::time::Duration; + +use reqwest_retry::policies::ExponentialBackoff; +use typesense::{ + client::{Error as TypesenseError, MultiNodeConfiguration}, + models::ConversationModelUpdateSchema, +}; +use typesense_codegen::models::{CollectionSchema, ConversationModelCreateSchema, Field}; + +use super::{get_client, new_id}; + +#[tokio::test] +async fn test_create_model_with_invalid_key_fails_as_expected() { + let client = get_client(); + let model_id = new_id("gpt-4-invalid-key-test"); + let collection_name = new_id("conversation_store_invalid"); + + // --- 1. Setup: Create the prerequisite collection for history --- + let schema = CollectionSchema { + name: collection_name.clone(), + fields: vec![ + Field { + name: "conversation_id".to_string(), + r#type: "string".to_string(), + ..Default::default() + }, + Field { + name: "model_id".to_string(), + r#type: "string".to_string(), + ..Default::default() + }, + Field { + name: "timestamp".to_string(), + r#type: "int32".to_string(), + ..Default::default() + }, + Field { + name: "role".to_string(), + r#type: "string".to_string(), + index: Some(false), + ..Default::default() + }, + Field { + name: "message".to_string(), + r#type: "string".to_string(), + index: Some(false), + ..Default::default() + }, + ], + ..Default::default() + }; + let create_collection_result = client.collections().create(schema).await; + assert!( + create_collection_result.is_ok(), + "Setup failed: Could not create the collection needed for the test." + ); + + // --- 2. Action: Attempt to create a model with a deliberately invalid API key --- + let create_schema = ConversationModelCreateSchema { + id: Some(model_id.clone()), + model_name: "openai/gpt-4".to_string(), + api_key: Some("THIS_IS_AN_INVALID_KEY".to_string()), + history_collection: collection_name.clone(), + max_bytes: 10000, + ..Default::default() + }; + let create_result = client.conversations().models().create(create_schema).await; + + // --- 3. Assertion: Verify that the creation failed with the correct error --- + assert!( + create_result.is_err(), + "Model creation should have failed due to an invalid API key, but it succeeded." + ); + match create_result.err() { + Some(TypesenseError::Api(response_content)) => match response_content { + typesense::apis::Error::ResponseError(api_error) => { + assert_eq!( + api_error.status.as_u16(), + 400, + "Expected HTTP status code 400 for an invalid key." + ); + assert!( + api_error.content.contains("Incorrect API key provided"), + "The error message did not match the expected content. Got: {}", + api_error.content + ); + } + other_entity => { + panic!( + "Expected a Status400 error entity but got something else: {:?}", + other_entity + ); + } + }, + other_error => { + panic!( + "Expected a Typesense ResponseError, but got a different kind of error: {:?}", + other_error + ); + } + } + + // --- 4. Teardown: Clean up the collection created during setup --- + let delete_collection_result = client.collection(&collection_name).delete().await; + assert!( + delete_collection_result.is_ok(), + "Teardown failed: Could not delete the test collection." + ); +} + +use typesense::client::Client; +use wiremock::{ + matchers::{body_json, method, path}, + Mock, MockServer, ResponseTemplate, +}; + +// Helper to create a Typesense client configured for a mock server. +fn get_test_client(uri: &str) -> Client { + let config = MultiNodeConfiguration { + nodes: vec![uri.parse().unwrap()], + nearest_node: None, // Not needed for single-node tests + api_key: "TEST_API_KEY".to_string(), + // Keep other settings minimal for testing + healthcheck_interval: Duration::from_secs(60), + retry_policy: ExponentialBackoff::builder().build_with_max_retries(0), + connection_timeout: Duration::from_secs(1), + }; + Client::new(config).unwrap() +} + +#[tokio::test] +async fn test_create_model_with_wiremock() { + // --- 1. Setup: Start a mock server --- + let mock_server = MockServer::start().await; + + // --- 2. Setup: Configure the Typesense client to use the mock server's URI --- + let client = get_test_client(&mock_server.uri()); + + // --- 3. Setup: Define the request and the expected successful response --- + let model_id = new_id("conv-model-test"); + let collection_name = new_id("history-collection"); + + let create_schema = ConversationModelCreateSchema { + id: Some(model_id.clone()), + model_name: "openai/gpt-4".to_string(), + api_key: Some("A-FAKE-BUT-VALID-LOOKING-KEY".to_string()), + history_collection: collection_name.clone(), + system_prompt: Some("You are a helpful assistant.".to_string()), + ..Default::default() + }; + + // This is the successful JSON body we expect the mock server to return. + // It should match the structure of `ConversationModelSchema`. + let mock_response_body = serde_json::json!({ + "id": model_id, + "model_name": "openai/gpt-4", + "history_collection": collection_name, + "api_key": "sk-FA**********************************KEY", // Masked key + "system_prompt": "You are a helpful assistant.", + "max_bytes": 16384, + "ttl": 86400 + }); + + // --- 4. Setup: Define the mock server's behavior --- + Mock::given(method("POST")) + .and(path("/conversations/models")) + .and(body_json(&create_schema)) // Ensure the client sends the correct body + .respond_with(ResponseTemplate::new(200).set_body_json(mock_response_body.clone())) + .expect(1) // Expect this mock to be called exactly once + .mount(&mock_server) + .await; + + // --- 5. Action: Call the client method --- + let create_result = client.conversations().models().create(create_schema).await; + + // --- 6. Assertion: Verify the result --- + assert!( + create_result.is_ok(), + "The client should have successfully parsed the 200 response from the mock server. Error: {:?}", + create_result.err() + ); + + // Unwrap the successful result and check if its fields match the mocked response + let created_model = create_result.unwrap(); + assert_eq!(created_model.id, model_id); + assert_eq!(created_model.model_name, "openai/gpt-4"); + assert_eq!(created_model.history_collection, collection_name); + assert_eq!( + created_model.system_prompt, + Some("You are a helpful assistant.".to_string()) + ); +} + +#[tokio::test] +async fn test_retrieve_all_models_with_wiremock() { + // --- 1. Setup --- + let mock_server = MockServer::start().await; + let client = get_test_client(&mock_server.uri()); + + // The response body should be a Vec + let mock_response_body = serde_json::json!([ + { + "id": "model-1", + "model_name": "openai/gpt-3.5-turbo", + "history_collection": "conversation_store", + "api_key": "OPENAI_API_KEY", + "system_prompt": "Hey, you are an **intelligent** assistant for question-answering. You can only make conversations based on the provided context. If a response cannot be formed strictly using the provided context, politely say you do not have knowledge about that topic.", + "max_bytes": 16384 + }, + { + "id": "model-2", + "model_name": "openai/gpt-3.5-turbo", + "history_collection": "conversation_store", + "api_key": "OPENAI_API_KEY", + "system_prompt": "Hey, you are an **intelligent** assistant for question-answering. You can only make conversations based on the provided context. If a response cannot be formed strictly using the provided context, politely say you do not have knowledge about that topic.", + "max_bytes": 16384 + } + ]); + + // --- 2. Mocking --- + Mock::given(method("GET")) + .and(path("/conversations/models")) + .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response_body)) + .expect(1) + .mount(&mock_server) + .await; + + // --- 3. Action --- + let retrieve_result = client.conversations().models().retrieve().await; + + // --- 4. Assertion --- + assert!(retrieve_result.is_ok(), "Retrieving all models failed"); + let models = retrieve_result.unwrap(); + assert_eq!(models.len(), 2); + assert_eq!(models[0].id, "model-1"); + assert_eq!(models[1].id, "model-2"); +} + +#[tokio::test] +async fn test_retrieve_single_model_with_wiremock() { + // --- 1. Setup --- + let mock_server = MockServer::start().await; + let client = get_test_client(&mock_server.uri()); + + let model_id = new_id("conv-model"); + let mock_response_body = serde_json::json!({ + "id": model_id, + "model_name": "openai/gpt-3.5-turbo", + "history_collection": "conversation_store", + "api_key": "OPENAI_API_KEY", + "system_prompt": "Hey, you are an **intelligent** assistant for question-answering. You can only make conversations based on the provided context. If a response cannot be formed strictly using the provided context, politely say you do not have knowledge about that topic.", + "max_bytes": 16384 + }); + + // --- 2. Mocking --- + Mock::given(method("GET")) + .and(path(format!("/conversations/models/{}", model_id))) + .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response_body)) + .expect(1) + .mount(&mock_server) + .await; + + // --- 3. Action --- + let retrieve_result = client.conversations().model(&model_id).retrieve().await; + + // --- 4. Assertion --- + assert!(retrieve_result.is_ok()); + assert_eq!(retrieve_result.unwrap().id, model_id); +} + +#[tokio::test] +async fn test_update_single_model_with_wiremock() { + // --- 1. Setup --- + let mock_server = MockServer::start().await; + let client = get_test_client(&mock_server.uri()); + + let model_id = new_id("conv-model"); + + let update_schema = ConversationModelUpdateSchema { + system_prompt: Some("A new, updated prompt.".to_string()), + ..Default::default() + }; + + // The response body reflects the updated state of the resource + let mock_response_body = serde_json::json!({ + "id": model_id, + "model_name": "openai/gpt-3.5-turbo", + "history_collection": "conversation_store", + "api_key": "OPENAI_API_KEY", + "system_prompt": "A new, updated prompt.", + "max_bytes": 16384 + }); + + // --- 2. Mocking --- + Mock::given(method("PUT")) // As per docs, update uses PUT + .and(path(format!("/conversations/models/{}", model_id))) + .and(body_json(&update_schema)) // Verify the client sends the correct update payload + .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response_body)) + .expect(1) + .mount(&mock_server) + .await; + + // --- 3. Action --- + let update_result = client + .conversations() + .model(&model_id) + .update(update_schema) + .await; + + // --- 4. Assertion --- + assert!(update_result.is_ok()); + let updated_model = update_result.unwrap(); + assert_eq!(updated_model.id, model_id); + assert_eq!( + updated_model.system_prompt.unwrap(), + "A new, updated prompt." + ); +} + +#[tokio::test] +async fn test_delete_single_model_with_wiremock() { + // --- 1. Setup --- + let mock_server = MockServer::start().await; + let client = get_test_client(&mock_server.uri()); + + let model_id = new_id("conv-model-to-delete"); + + // The API returns the object that was just deleted + let mock_response_body = serde_json::json!({ + "id": model_id, + "model_name": "openai/gpt-3.5-turbo", + "history_collection": "conversation_store", + "api_key": "OPENAI_API_KEY", + "system_prompt": "Hey, you are an **intelligent** assistant for question-answering. You can only make conversations based on the provided context. If a response cannot be formed strictly using the provided context, politely say you do not have knowledge about that topic.", + "max_bytes": 16384 + }); + + // --- 2. Mocking --- + Mock::given(method("DELETE")) + .and(path(format!("/conversations/models/{}", model_id))) + .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response_body)) + .expect(1) + .mount(&mock_server) + .await; + + // --- 3. Action --- + let delete_result = client.conversations().model(&model_id).delete().await; + + // --- 4. Assertion --- + assert!(delete_result.is_ok()); + let deleted_model = delete_result.unwrap(); + assert_eq!(deleted_model.id, model_id); +} diff --git a/typesense/tests/client/documents_test.rs b/typesense/tests/client/documents_test.rs new file mode 100644 index 0000000..1f9c57e --- /dev/null +++ b/typesense/tests/client/documents_test.rs @@ -0,0 +1,205 @@ +use serde_json::json; +use typesense::models::IndexAction; +use typesense_codegen::models::{ + CollectionSchema, DeleteDocumentsParameters, ExportDocumentsParameters, Field, + ImportDocumentsParameters, SearchParameters, UpdateDocumentsParameters, +}; + +use super::{get_client, new_id}; + +#[tokio::test] +async fn test_document_lifecycle() { + let client = get_client(); + let collection_name = new_id("books"); + + // --- 1. Setup: Create a Collection --- + let schema = CollectionSchema { + name: collection_name.clone(), + fields: vec![ + Field { + name: "title".to_string(), + r#type: "string".to_string(), + ..Default::default() + }, + Field { + name: "author".to_string(), + r#type: "string".to_string(), + facet: Some(true), + ..Default::default() + }, + Field { + name: "publication_year".to_string(), + r#type: "int32".to_string(), + ..Default::default() + }, + ], + ..Default::default() + }; + + let create_collection_result = client.collections().create(schema).await; + assert!( + create_collection_result.is_ok(), + "Failed to create collection" + ); + + let book_1_id = &new_id("document_1"); + let book_1 = json!({ + "id": book_1_id, + "title": "The Hitchhiker's Guide to the Galaxy", + "author": "Douglas Adams", + "publication_year": 1979 + }); + + let book_2 = json!({ + "title": "The Lord of the Rings", + "author": "J.R.R. Tolkien", + "publication_year": 1954 + }); + let collection_client = client.collection(&collection_name); + let documents_client = collection_client.documents(); + + // --- 2. Create a document (via `documents().create()`) --- + let create_res = documents_client.create(book_1.clone()).await; + assert!(create_res.is_ok(), "Failed to create document 1"); + + // --- 3. Upsert a document (via `documents().upsert()`) --- + let upsert_res = documents_client.upsert(book_2.clone()).await; + assert!(upsert_res.is_ok(), "Failed to upsert document 2"); + + // --- 4. Retrieve a single document (via `document(id).retrieve()`) --- + let retrieve_res = client + .collection(&collection_name) + .document(book_1_id) + .retrieve() + .await; + assert!(retrieve_res.is_ok(), "Failed to retrieve document 1"); + assert_eq!(retrieve_res.unwrap(), book_1); + + // --- 5. Search for documents --- + let search_params = SearchParameters { + q: Some("the".to_string()), + query_by: Some("title".to_string()), + ..Default::default() + }; + let search_res = documents_client.search(search_params).await; + assert!(search_res.is_ok(), "Search failed"); + assert_eq!(search_res.unwrap().found, Some(2)); + + // --- 6. Update a single document --- + let partial_update = json!({ "publication_year": 1980 }); + let update_res = client + .collection(&collection_name) + .document(book_1_id) + .update(partial_update) + .await; + assert!(update_res.is_ok(), "Failed to update document 1"); + + // --- 7. Verify the single update --- + let retrieve_after_update_res = client + .collection(&collection_name) + .document(book_1_id) + .retrieve() + .await; + let updated_doc = retrieve_after_update_res.unwrap(); + assert_eq!( + updated_doc.get("publication_year").unwrap().as_i64(), + Some(1980) + ); + + // --- 8. Delete a single document --- + let delete_res = client + .collection(&collection_name) + .document(book_1_id) + .delete() + .await; + assert!(delete_res.is_ok(), "Failed to delete document 1"); + + // --- 9. Verify single deletion --- + let retrieve_after_delete_res = client + .collection(&collection_name) + .document(book_1_id) + .retrieve() + .await; + assert!( + retrieve_after_delete_res.is_err(), + "Document should not exist after deletion" + ); + + // --- 10. Bulk Import --- + let new_books_jsonl = format!( + "{}\n{}", + json!({"title": "Foundation", "author": "Isaac Asimov", "publication_year": 1951}), + json!({"title": "Dune", "author": "Frank Herbert", "publication_year": 1965}) + ); + + let import_params = ImportDocumentsParameters { + action: Some(IndexAction::Create), + ..Default::default() + }; + let import_res = documents_client + .import(new_books_jsonl, import_params) + .await; + assert!(import_res.is_ok(), "Bulk import failed"); + + // Give Typesense a moment to index + tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; + + // --- 11. Verify Import via Search --- + let search_after_import_params = SearchParameters { + q: Some("*".to_string()), + query_by: Some("title".to_string()), + ..Default::default() + }; + let search_after_import_res = documents_client.search(search_after_import_params).await; + let search_results = search_after_import_res.unwrap(); + // 1 remaining (book_2) + 2 new imports = 3 + assert_eq!(search_results.found, Some(3)); + + // --- 12. Bulk Update (via `documents().update()`) --- + let bulk_update_params = UpdateDocumentsParameters { + filter_by: Some("publication_year:<1960".to_string()), + }; + let bulk_update_payload = json!({ "author": "Sci-Fi Pioneer" }); + let bulk_update_res = documents_client + .update(bulk_update_payload, bulk_update_params) + .await; + assert!(bulk_update_res.is_ok(), "Bulk update failed"); + // Should update Lord of the Rings (1954) and Foundation (1951) + assert_eq!(bulk_update_res.unwrap().num_updated, 2); + + // Give Typesense a moment to index + tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; + + // --- 13. Export documents (via `documents().export()`) --- + let export_params = ExportDocumentsParameters { + filter_by: Some("author:\"Sci-Fi Pioneer\"".to_string()), + ..Default::default() + }; + let export_res = documents_client.export(export_params).await; + + assert!(export_res.is_ok(), "Export failed"); + let exported_jsonl = export_res.unwrap(); + + // Verify the exported content is a JSONL string with 2 lines. + let lines: Vec<&str> = exported_jsonl.trim().split('\n').collect(); + assert_eq!(lines.len(), 2, "Exported JSONL should have 2 lines"); + let exported_doc_1: serde_json::Value = serde_json::from_str(lines[0]).unwrap(); + assert_eq!(exported_doc_1["author"], "Sci-Fi Pioneer"); + + // --- 14. Bulk Delete --- + let delete_params = DeleteDocumentsParameters { + filter_by: "publication_year:>1960".to_string(), + ..Default::default() + }; + let bulk_delete_res = documents_client.delete(delete_params).await; + assert!(bulk_delete_res.is_ok(), "Bulk delete failed"); + // Only "Dune" (1965) should be deleted + assert_eq!(bulk_delete_res.unwrap().num_deleted, 1); + + // --- 15. Teardown: Delete the collection --- + let delete_collection_result = client.collection(&collection_name).delete().await; + assert!( + delete_collection_result.is_ok(), + "Failed to delete collection" + ); +} diff --git a/typesense/tests/client/keys_test.rs b/typesense/tests/client/keys_test.rs new file mode 100644 index 0000000..1e40569 --- /dev/null +++ b/typesense/tests/client/keys_test.rs @@ -0,0 +1,82 @@ +use super::get_client; +use typesense_codegen::models::ApiKeySchema; + +#[tokio::test] +async fn test_keys_lifecycle() { + let client = get_client(); + let key_description = "A test search-only key."; + + // --- 1. Create a new API Key (via `keys`) --- + let key_schema = ApiKeySchema { + description: key_description.to_string(), + actions: vec!["documents:search".to_string()], // Grant only search permissions + collections: vec!["*".to_string()], // For all collections + ..Default::default() + }; + + let create_result = client.keys().create(key_schema).await; + assert!(create_result.is_ok(), "Failed to create the API key."); + let created_key = create_result.unwrap(); + + // The full key value is only returned on creation + assert!( + created_key.value.is_some(), + "The full API key value should be present upon creation." + ); + assert_eq!(created_key.description, key_description.to_string()); + + let key_id = created_key.id.unwrap(); + + // --- 2. Retrieve the specific key (via `key`) --- + let retrieve_one_result = client.key(key_id).retrieve().await; + assert!( + retrieve_one_result.is_ok(), + "Failed to retrieve the specific API key." + ); + let retrieved_key = retrieve_one_result.unwrap(); + + // On retrieval, the value should be None and the prefix should be present + assert_eq!(retrieved_key.id.unwrap(), key_id); + assert!( + retrieved_key.value.is_none(), + "The retrieved key should not contain the full value." + ); + assert!( + retrieved_key.value_prefix.is_some(), + "The retrieved key should have a value prefix." + ); + + // --- 3. Retrieve all keys (via `keys`) --- + let retrieve_all_result = client.keys().retrieve().await; + assert!( + retrieve_all_result.is_ok(), + "Failed to retrieve the list of keys." + ); + let all_keys_response = retrieve_all_result.unwrap(); + + // --- 4. Find our specific key within the list --- + let our_key = all_keys_response + .keys + .iter() + .find(|k| k.id.unwrap() == (key_id)); + assert!( + our_key.is_some(), + "The newly created key was not found in the list." + ); + + // --- 5. Delete the key (via `key`) --- + let delete_result = client.key(key_id).delete().await; + assert!(delete_result.is_ok(), "Failed to delete the API key."); + let delete_response = delete_result.unwrap(); + assert_eq!( + delete_response.id, key_id, + "The response from delete should contain the correct key ID." + ); + + // --- 6. Verify Deletion --- + let get_after_delete_result = client.key(key_id).retrieve().await; + assert!( + get_after_delete_result.is_err(), + "API key should not exist after deletion." + ); +} diff --git a/typesense/tests/client/mod.rs b/typesense/tests/client/mod.rs new file mode 100644 index 0000000..0e77bda --- /dev/null +++ b/typesense/tests/client/mod.rs @@ -0,0 +1,50 @@ +pub mod aliases_test; +pub mod analytics_test; +pub mod client_test; +pub mod collections_test; +pub mod conversation_models_test; +pub mod documents_test; +pub mod keys_test; +pub mod multi_search_test; +pub mod presets_test; +pub mod search_overrides_test; +pub mod stemming_dictionaries_test; +pub mod stopwords_test; +pub mod synonyms_test; + +use reqwest::Url; +use reqwest_retry::policies::ExponentialBackoff; +use std::time::Duration; +use std::time::{SystemTime, UNIX_EPOCH}; +use typesense::client::{Client, MultiNodeConfiguration}; + +/// Helper function to create a new client for all tests in this suite. +pub fn get_client() -> Client { + let config = MultiNodeConfiguration { + nodes: vec![Url::parse("http://localhost:8108").unwrap()], + nearest_node: None, + api_key: "xyz".to_string(), + healthcheck_interval: Duration::from_secs(60), + retry_policy: ExponentialBackoff::builder().build_with_max_retries(3), + connection_timeout: Duration::from_secs(10), + }; + Client::new(config).unwrap() +} + +/// Generates a unique name for a test resource by combining a prefix, +/// a nanoid, and an optional suffix. +/// e.g., "test_collection_aB1cD2eF_create" +pub fn new_id(suffix: &str) -> String { + // Using nanoid for a short, URL-friendly, and collision-resistant random ID. + // The default length of 21 is more than enough. We use 8 for conciseness. + let random_part = nanoid::nanoid!(8); // e.g., "fX3a-b_1" + + // The timestamp helps ensure IDs are unique even across test runs that happen close together, + // although nanoid is likely sufficient on its own. + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis(); + + format!("test_{}_{}_{}", suffix, timestamp, random_part) +} diff --git a/typesense/tests/client/multi_search_test.rs b/typesense/tests/client/multi_search_test.rs new file mode 100644 index 0000000..ce5e2b1 --- /dev/null +++ b/typesense/tests/client/multi_search_test.rs @@ -0,0 +1,248 @@ +use typesense_codegen::models::{ + CollectionSchema, Field, ImportDocumentsParameters, MultiSearchCollectionParameters, + MultiSearchParameters, MultiSearchSearchesParameter, +}; + +use super::{get_client, new_id}; + +async fn setup_multi_search_tests( + client: &typesense::client::Client, + products_collection_name: &str, + brands_collection_name: &str, +) { + // --- Create collections --- + let products_schema = CollectionSchema { + name: products_collection_name.to_string(), + fields: vec![ + Field::new("name".to_string(), "string".to_string()), + Field::new("price".to_string(), "int32".to_string()), + ], + ..Default::default() + }; + client.collections().create(products_schema).await.unwrap(); + + let brands_schema = CollectionSchema { + name: brands_collection_name.to_string(), + fields: vec![ + Field::new("company_name".to_string(), "string".to_string()), + Field::new("country".to_string(), "string".to_string()), + ], + ..Default::default() + }; + client.collections().create(brands_schema).await.unwrap(); + + // --- Index documents --- + let product_docs = r#" + {"id": "p1", "name": "iPhone 15", "price": 999} + {"id": "p2", "name": "MacBook Pro", "price": 1999} + "# + .trim() + .lines() + .map(|s| s.trim()) + .collect::>() + .join("\n"); + + client + .collection(products_collection_name) + .documents() + .import( + product_docs, + ImportDocumentsParameters { + action: Some(typesense::models::IndexAction::Create), + ..Default::default() + }, + ) + .await + .unwrap(); + + let brand_docs = r#" + {"id": "b1", "company_name": "Apple Inc.", "country": "USA"} + {"id": "b2", "company_name": "Samsung", "country": "South Korea"} + "# + .trim() + .lines() + .map(|s| s.trim()) + .collect::>() + .join("\n"); + + client + .collection(brands_collection_name) + .documents() + .import( + brand_docs, + ImportDocumentsParameters { + action: Some(typesense::models::IndexAction::Create), + ..Default::default() + }, + ) + .await + .unwrap(); +} + +#[tokio::test] +async fn test_multi_search_federated() { + let client = get_client(); + let products_collection_name = new_id("products"); + let brands_collection_name = new_id("brands"); + setup_multi_search_tests(&client, &products_collection_name, &brands_collection_name).await; + + let search_requests = MultiSearchSearchesParameter { + union: Some(false), + searches: vec![ + MultiSearchCollectionParameters { + q: Some("pro".into()), + query_by: Some("name".into()), + collection: Some(products_collection_name.clone()), + ..Default::default() + }, + MultiSearchCollectionParameters { + q: Some("USA".into()), + query_by: Some("country".into()), + collection: Some(brands_collection_name.clone()), + ..Default::default() + }, + ], + }; + + let common_params = MultiSearchParameters::default(); + + let result = client + .multi_search() + .perform(search_requests, common_params) + .await; + + assert!(result.is_ok(), "Multi-search request failed"); + let response = result.unwrap(); + + assert_eq!( + response.results.len(), + 2, + "Expected 2 sets of search results" + ); + + // --- Assert products result --- + let products_result = &response.results[0]; + assert!( + products_result.error.is_none(), + "First search returned an error" + ); + assert_eq!(products_result.found, Some(1)); + let product_hit = &products_result.hits.as_ref().unwrap()[0]; + let product_doc = product_hit.document.as_ref().unwrap().as_object().unwrap(); + assert_eq!( + product_doc.get("name").unwrap().as_str(), + Some("MacBook Pro") + ); + + // --- Assert brands result --- + let brands_result = &response.results[1]; + assert!( + brands_result.error.is_none(), + "Second search returned an error" + ); + assert_eq!(brands_result.found, Some(1)); + let brand_hit = &brands_result.hits.as_ref().unwrap()[0]; + let brand_doc = brand_hit.document.as_ref().unwrap().as_object().unwrap(); + assert_eq!( + brand_doc.get("company_name").unwrap().as_str(), + Some("Apple Inc.") + ); + + // --- Cleanup --- + client + .collection(&products_collection_name) + .delete() + .await + .unwrap(); + client + .collection(&brands_collection_name) + .delete() + .await + .unwrap(); +} + +#[tokio::test] +async fn test_multi_search_with_common_params() { + let client = get_client(); + let products_collection_name = new_id("products_common"); + let brands_collection_name = new_id("brands_common"); + setup_multi_search_tests(&client, &products_collection_name, &brands_collection_name).await; + + // Define individual searches, each with the correct `query_by` for its schema. + let search_requests = MultiSearchSearchesParameter { + union: Some(false), + searches: vec![ + MultiSearchCollectionParameters { + collection: Some(products_collection_name.clone()), + q: Some("pro".into()), // This should find "Macbook Pro" + query_by: Some("name".into()), // Specific to the products schema + ..Default::default() + }, + MultiSearchCollectionParameters { + collection: Some(brands_collection_name.clone()), + q: Some("inc".into()), // This should find "Apple Inc." + query_by: Some("company_name".into()), // Specific to the brands schema + ..Default::default() + }, + ], + }; + + let common_params = MultiSearchParameters { + limit: Some(1), + ..Default::default() + }; + + let result = client + .multi_search() + .perform(search_requests, common_params) + .await; + + assert!( + result.is_ok(), + "Multi-search request failed: {:?}", + result.err() + ); + let response = result.unwrap(); + + assert_eq!(response.results.len(), 2); + + // --- Assert products result --- + let products_result = &response.results[0]; + assert!( + products_result.error.is_none(), + "Products search returned an error: {:?}", + products_result.error + ); + assert_eq!(products_result.found, Some(1)); + let product_hit = &products_result.hits.as_ref().unwrap()[0]; + assert_eq!( + product_hit.document.as_ref().unwrap()["name"], + "MacBook Pro" + ); + + // --- Assert brands result --- + let brands_result = &response.results[1]; + assert!( + brands_result.error.is_none(), + "Brands search returned an error: {:?}", + brands_result.error + ); + assert_eq!(brands_result.found, Some(1)); + let brand_hit = &brands_result.hits.as_ref().unwrap()[0]; + assert_eq!( + brand_hit.document.as_ref().unwrap()["company_name"], + "Apple Inc." + ); + + // --- Cleanup --- + client + .collection(&products_collection_name) + .delete() + .await + .unwrap(); + client + .collection(&brands_collection_name) + .delete() + .await + .unwrap(); +} diff --git a/typesense/tests/client/presets_test.rs b/typesense/tests/client/presets_test.rs new file mode 100644 index 0000000..39bc67f --- /dev/null +++ b/typesense/tests/client/presets_test.rs @@ -0,0 +1,86 @@ +use typesense_codegen::models::{ + PresetSchema, PresetUpsertSchema, PresetUpsertSchemaValue, SearchParameters, +}; + +use super::{get_client, new_id}; + +#[tokio::test] +async fn test_presets_lifecycle() { + let client = get_client(); + let preset_id = new_id("search-preset"); + + // --- 1. Define the Preset's value using the strong types --- + // This will be the expected value in the response as well. + let search_params = SearchParameters { + query_by: Some("title,authors".to_string()), + sort_by: Some("_text_match:desc,publication_year:desc".to_string()), + ..Default::default() + }; + let expected_preset_value = PresetUpsertSchemaValue::SearchParameters(Box::new(search_params)); + + // This is the schema to be sent in the request body. + let upsert_schema = PresetUpsertSchema { + value: Box::new(expected_preset_value.clone()), + }; + + // --- 2. Create (Upsert) a Preset (via `presets`) --- + let upsert_result = client.presets().upsert(&preset_id, upsert_schema).await; + assert!( + upsert_result.is_ok(), + "Failed to create preset: {:?}", + upsert_result.err() + ); + + // The API returns a full PresetSchema object. + let created_preset: PresetSchema = upsert_result.unwrap(); + assert_eq!(created_preset.name, preset_id); + // Compare the strongly-typed value field directly. + assert_eq!(*created_preset.value, expected_preset_value); + + // --- 3. Retrieve the specific preset (via `preset`) --- + let retrieve_one_result = client.preset(&preset_id).retrieve().await; + assert!( + retrieve_one_result.is_ok(), + "Failed to retrieve the specific preset." + ); + let retrieved_preset: PresetSchema = retrieve_one_result.unwrap(); + assert_eq!(retrieved_preset.name, preset_id); + assert_eq!(*retrieved_preset.value, expected_preset_value); + + // --- 4. Retrieve all presets (via `presets`) --- + let retrieve_all_result = client.presets().retrieve().await; + assert!( + retrieve_all_result.is_ok(), + "Failed to retrieve all presets." + ); + let all_presets_response = retrieve_all_result.unwrap(); + + // --- 5. Find our preset in the list --- + let our_preset = all_presets_response + .presets + .iter() + .find(|p| p.name == preset_id); + + assert!( + our_preset.is_some(), + "The created preset was not found in the list." + ); + + if let Some(preset) = our_preset { + assert_eq!(preset.name, preset_id); + assert_eq!(*preset.value, expected_preset_value); + } + + // --- 6. Delete the preset (via `preset`) --- + let delete_result = client.preset(&preset_id).delete().await; + assert!(delete_result.is_ok(), "Failed to delete preset."); + let deleted_preset = delete_result.unwrap(); + assert_eq!(deleted_preset.name, preset_id); + + // --- 7. Verify Deletion --- + let get_after_delete_result = client.preset(&preset_id).retrieve().await; + assert!( + get_after_delete_result.is_err(), + "Preset should not exist after deletion." + ); +} diff --git a/typesense/tests/client/search_overrides_test.rs b/typesense/tests/client/search_overrides_test.rs new file mode 100644 index 0000000..e67376f --- /dev/null +++ b/typesense/tests/client/search_overrides_test.rs @@ -0,0 +1,120 @@ +use typesense_codegen::models::{ + CollectionSchema, Field, SearchOverrideInclude, SearchOverrideRule, SearchOverrideSchema, +}; + +use super::{get_client, new_id}; + +#[tokio::test] +async fn test_search_overrides_lifecycle() { + let client = get_client(); + let collection_name = new_id("products"); + let override_id = new_id("promo_products"); + + // --- 1. Setup: Create a collection and add some documents --- + let schema = CollectionSchema { + name: collection_name.clone(), + fields: vec![ + Field { + name: "name".to_string(), + r#type: "string".to_string(), + ..Default::default() + }, + Field { + name: "category".to_string(), + r#type: "string".to_string(), + facet: Some(true), + ..Default::default() + }, + ], + ..Default::default() + }; + client.collections().create(schema).await.unwrap(); + + // --- 2. Create (Upsert) a Search Override (via `search_overrides`) --- + let override_schema = SearchOverrideSchema { + rule: Box::new(SearchOverrideRule { + query: Some("products".to_string()), + r#match: Some(typesense::models::search_override_rule::Match::Exact), + ..Default::default() + }), + includes: Some(vec![SearchOverrideInclude { + id: "3".to_string(), + position: 1, + }]), + ..Default::default() + }; + + let upsert_result = client + .collection(&collection_name) + .search_overrides() + .upsert(&override_id, override_schema) + .await; + + assert!(upsert_result.is_ok(), "Failed to create search override"); + let created_override = upsert_result.unwrap(); + assert_eq!(created_override.id, override_id); + assert_eq!(created_override.rule.query.unwrap(), "products"); + + // --- 3. Retrieve the specific override (via `search_override`) --- + let retrieve_one_result = client + .collection(&collection_name) + .search_override(&override_id) + .retrieve() + .await; + + assert!( + retrieve_one_result.is_ok(), + "Failed to retrieve the specific search override." + ); + let retrieved_override = retrieve_one_result.unwrap(); + assert_eq!(retrieved_override.id, override_id); + assert_eq!(retrieved_override.includes.unwrap()[0].id, "3"); + + // --- 4. List all overrides (via `search_overrides`) --- + let list_result = client + .collection(&collection_name) + .search_overrides() + .list() + .await; + + assert!(list_result.is_ok(), "Failed to list search overrides."); + let list_response = list_result.unwrap(); + assert_eq!(list_response.overrides.len(), 1); + assert!( + list_response + .overrides + .iter() + .find(|o| o.id == override_id) + .is_some(), + "The newly created override was not found in the list." + ); + + // --- 5. Delete the override (via `search_override`) --- + let delete_result = client + .collection(&collection_name) + .search_override(&override_id) + .delete() + .await; + + assert!(delete_result.is_ok(), "Failed to delete search override."); + let delete_response = delete_result.unwrap(); + assert_eq!(delete_response.id, override_id); + + // --- 6. Verify Deletion --- + let get_after_delete_result = client + .collection(&collection_name) + .search_override(&override_id) + .retrieve() + .await; + assert!( + get_after_delete_result.is_err(), + "Search override should not exist after deletion." + ); + + // --- 7. Teardown: Delete the collection --- + let delete_collection_result = client.collection(&collection_name).delete().await; + assert!( + delete_collection_result.is_ok(), + "Failed to delete collection after test." + ); +} diff --git a/typesense/tests/client/stemming_dictionaries_test.rs b/typesense/tests/client/stemming_dictionaries_test.rs new file mode 100644 index 0000000..60b0d91 --- /dev/null +++ b/typesense/tests/client/stemming_dictionaries_test.rs @@ -0,0 +1,73 @@ +use crate::{get_client, new_id}; + +#[tokio::test] +async fn test_stemming_dictionary_import_and_retrieve() { + let client = get_client(); + let dictionary_id = new_id("verb_stems_v2"); + + // --- 1. Define and Import the Dictionary --- + // The JSONL payload uses "word" and "root" keys. + let dictionary_data = r#"{"word": "running", "root": "run"} +{"word": "flies", "root": "fly"}"# + .to_string(); + let import_result = client + .stemming() + .dictionaries() + .import(&dictionary_id, dictionary_data) + .await; + assert!( + import_result.is_ok(), + "Failed to import stemming dictionary. Error: {:?}", + import_result.err() + ); + + // --- 2. Retrieve the specific dictionary by its ID to verify contents --- + // This is necessary because the list operation only returns IDs. + let get_result = client + .stemming() + .dictionary(&dictionary_id) + .retrieve() + .await; + assert!( + get_result.is_ok(), + "Failed to retrieve the specific stemming dictionary. Error: {:?}", + get_result.err() + ); + + let dictionary = get_result.unwrap(); + assert_eq!(dictionary.id, dictionary_id); + assert_eq!( + dictionary.words.len(), + 2, + "The number of words in the retrieved dictionary is incorrect." + ); + assert!( + dictionary + .words + .iter() + .any(|w| w.word == "running" && w.root == "run"), + "The mapping for 'running' -> 'run' was not found." + ); + + // --- 3. Retrieve all dictionary IDs and find ours --- + let list_result = client.stemming().dictionaries().retrieve().await; + assert!( + list_result.is_ok(), + "Failed to retrieve the list of stemming dictionaries. Error: {:?}", + list_result.err() + ); + + let list_response = list_result.unwrap(); + let dictionary_ids = list_response.dictionaries; + + assert!( + dictionary_ids.is_some(), + "The list of dictionary IDs should not be None." + ); + + let ids_vec = dictionary_ids.unwrap(); + assert!( + ids_vec.iter().any(|id| id == &dictionary_id), + "The newly imported dictionary's ID was not found in the master list." + ); +} diff --git a/typesense/tests/client/stopwords_test.rs b/typesense/tests/client/stopwords_test.rs new file mode 100644 index 0000000..f4d5580 --- /dev/null +++ b/typesense/tests/client/stopwords_test.rs @@ -0,0 +1,59 @@ +use typesense_codegen::models::StopwordsSetUpsertSchema; + +use super::{get_client, new_id}; + +#[tokio::test] +async fn test_stopwords_and_stopword_lifecycle() { + let client = get_client(); + let set_id = new_id("custom_stopwords"); + + // --- 1. Upsert a Stopwords Set (via `stopwords`) --- + let schema = StopwordsSetUpsertSchema { + stopwords: vec!["a".to_string(), "the".to_string(), "an".to_string()], + ..Default::default() + }; + + let upsert_result = client.stopwords().upsert(&set_id, schema).await; + assert!(upsert_result.is_ok(), "Failed to upsert stopwords set"); + let upserted_set = upsert_result.unwrap(); + assert_eq!(upserted_set.id, set_id); + assert_eq!(upserted_set.stopwords, vec!["a", "the", "an"]); + + // --- 2. Retrieve the specific Stopword set (via `stopword`) --- + let retrieve_one_result = client.stopword(&set_id).retrieve().await; + assert!( + retrieve_one_result.is_ok(), + "Failed to retrieve the newly created stopwords set." + ); + let retrieved_set = retrieve_one_result.unwrap(); + assert_eq!(retrieved_set.stopwords.id, set_id); + assert_eq!(retrieved_set.stopwords.stopwords, vec!["a", "the", "an"]); + + // --- 3. Retrieve all stopwords sets (via `stopwords`) --- + let retrieve_all_result = client.stopwords().retrieve().await; + assert!( + retrieve_all_result.is_ok(), + "Failed to retrieve the list of stopwords sets." + ); + let all_sets = retrieve_all_result.unwrap(); + + // --- 4. Find our specific set within the list --- + let our_set = all_sets.stopwords.iter().find(|s| s.id == set_id); + assert!( + our_set.is_some(), + "The newly created stopwords set was not found in the list." + ); + + // --- 5. Delete the Stopword set (via `stopword`) --- + let delete_result = client.stopword(&set_id).delete().await; + assert!(delete_result.is_ok(), "Failed to delete stopwords set"); + let deleted_response = delete_result.unwrap(); + assert_eq!(deleted_response.id, set_id); + + // --- 6. Verify Deletion --- + let get_after_delete_result = client.stopword(&set_id).retrieve().await; + assert!( + get_after_delete_result.is_err(), + "Stopwords set should not exist after deletion" + ); +} diff --git a/typesense/tests/client/synonyms_test.rs b/typesense/tests/client/synonyms_test.rs new file mode 100644 index 0000000..a6141d5 --- /dev/null +++ b/typesense/tests/client/synonyms_test.rs @@ -0,0 +1,112 @@ +use typesense_codegen::models::{CollectionSchema, Field, SearchSynonymSchema}; + +use super::{get_client, new_id}; + +#[tokio::test] +async fn test_synonyms_lifecycle() { + let client = get_client(); + let collection_name = new_id("products"); + let synonym_id = new_id("synonym-123"); + + // --- 1. Create a collection to house the synonyms --- + let collection_schema = CollectionSchema { + name: collection_name.clone(), + fields: vec![Field { + name: "name".to_string(), + r#type: "string".to_string(), + ..Default::default() + }], + ..Default::default() + }; + let create_collection_result = client.collections().create(collection_schema).await; + assert!( + create_collection_result.is_ok(), + "Failed to create collection for synonym test" + ); + + // --- 2. Create (Upsert) a Synonym (via `synonyms`) --- + let synonym_schema = SearchSynonymSchema { + synonyms: vec![ + "blazer".to_string(), + "jacket".to_string(), + "coat".to_string(), + ], + ..Default::default() + }; + + let upsert_result = client + .collection(&collection_name) + .synonyms() + .upsert(&synonym_id, synonym_schema) + .await; + + assert!(upsert_result.is_ok(), "Failed to create synonym"); + let created_synonym = upsert_result.unwrap(); + assert_eq!(created_synonym.id, synonym_id); + + // --- 3. Retrieve the specific synonym (via `synonym`) --- + let retrieve_one_result = client + .collection(&collection_name) + .synonym(&synonym_id) + .get() + .await; + + assert!( + retrieve_one_result.is_ok(), + "Failed to retrieve the specific synonym." + ); + let retrieved_synonym = retrieve_one_result.unwrap(); + assert_eq!(retrieved_synonym.id, synonym_id); + assert_eq!(retrieved_synonym.synonyms.len(), 3); + + // --- 4. Retrieve all synonyms for the collection (via `synonyms`) --- + let retrieve_all_result = client + .collection(&collection_name) + .synonyms() + .retrieve() + .await; + assert!( + retrieve_all_result.is_ok(), + "Failed to retrieve the list of synonyms." + ); + let all_synonyms_response = retrieve_all_result.unwrap(); + + // --- 5. Find our specific synonym within the list --- + let our_synonym = all_synonyms_response + .synonyms + .iter() + .find(|s| s.id == synonym_id); + + assert!( + our_synonym.is_some(), + "The newly created synonym was not found in the list." + ); + + // --- 6. Delete the synonym (via `synonym`) --- + let delete_result = client + .collection(&collection_name) + .synonym(&synonym_id) + .delete() + .await; + assert!(delete_result.is_ok(), "Failed to delete synonym"); + let delete_response = delete_result.unwrap(); + assert_eq!(delete_response.id, synonym_id); + + // --- 7. Verify Deletion --- + let get_after_delete_result = client + .collection(&collection_name) + .synonym(&synonym_id) + .get() + .await; + assert!( + get_after_delete_result.is_err(), + "Synonym should not exist after deletion" + ); + + // --- 8. Clean up the collection --- + let delete_collection_result = client.collection(&collection_name).delete().await; + assert!( + delete_collection_result.is_ok(), + "Failed to delete collection after synonym test" + ); +} diff --git a/typesense_codegen/.openapi-generator-ignore b/typesense_codegen/.openapi-generator-ignore index 7484ee5..0161386 100644 --- a/typesense_codegen/.openapi-generator-ignore +++ b/typesense_codegen/.openapi-generator-ignore @@ -21,3 +21,5 @@ #docs/*.md # Then explicitly reverse the ignore rule for a single file: #!docs/README.md + +Cargo.toml \ No newline at end of file diff --git a/typesense_codegen/.openapi-generator/FILES b/typesense_codegen/.openapi-generator/FILES index 2e9cc88..58b2ca8 100644 --- a/typesense_codegen/.openapi-generator/FILES +++ b/typesense_codegen/.openapi-generator/FILES @@ -1,18 +1,23 @@ .gitignore -.openapi-generator-ignore .travis.yml -Cargo.toml README.md docs/AnalyticsApi.md +docs/AnalyticsEventCreateResponse.md +docs/AnalyticsEventCreateSchema.md +docs/AnalyticsRuleDeleteResponse.md docs/AnalyticsRuleParameters.md docs/AnalyticsRuleParametersDestination.md docs/AnalyticsRuleParametersSource.md +docs/AnalyticsRuleParametersSourceEventsInner.md docs/AnalyticsRuleSchema.md +docs/AnalyticsRuleUpsertSchema.md docs/AnalyticsRulesRetrieveSchema.md docs/ApiKey.md +docs/ApiKeyDeleteResponse.md docs/ApiKeySchema.md docs/ApiKeysResponse.md docs/ApiResponse.md +docs/ApiStatsResponse.md docs/CollectionAlias.md docs/CollectionAliasSchema.md docs/CollectionAliasesResponse.md @@ -20,13 +25,22 @@ docs/CollectionResponse.md docs/CollectionSchema.md docs/CollectionUpdateSchema.md docs/CollectionsApi.md +docs/ConversationModelCreateSchema.md +docs/ConversationModelSchema.md +docs/ConversationModelUpdateSchema.md +docs/ConversationsApi.md +docs/CurationApi.md docs/Debug200Response.md docs/DebugApi.md docs/DeleteDocuments200Response.md -docs/DeleteDocumentsDeleteDocumentsParametersParameter.md +docs/DeleteDocumentsParameters.md +docs/DeleteStopwordsSet200Response.md +docs/DirtyValues.md +docs/DocumentIndexParameters.md docs/DocumentsApi.md +docs/DropTokensMode.md docs/ErrorResponse.md -docs/ExportDocumentsExportDocumentsParametersParameter.md +docs/ExportDocumentsParameters.md docs/FacetCounts.md docs/FacetCountsCountsInner.md docs/FacetCountsStats.md @@ -35,19 +49,34 @@ docs/FieldEmbed.md docs/FieldEmbedModelConfig.md docs/HealthApi.md docs/HealthStatus.md -docs/ImportDocumentsImportDocumentsParametersParameter.md +docs/ImportDocumentsParameters.md +docs/IndexAction.md docs/KeysApi.md +docs/ListStemmingDictionaries200Response.md docs/MultiSearchCollectionParameters.md docs/MultiSearchParameters.md docs/MultiSearchResult.md +docs/MultiSearchResultItem.md docs/MultiSearchSearchesParameter.md +docs/NlSearchModelBase.md +docs/NlSearchModelCreateSchema.md +docs/NlSearchModelDeleteSchema.md +docs/NlSearchModelSchema.md +docs/NlSearchModelsApi.md docs/OperationsApi.md docs/OverrideApi.md -docs/PromoteApi.md +docs/PresetDeleteSchema.md +docs/PresetSchema.md +docs/PresetUpsertSchema.md +docs/PresetUpsertSchemaValue.md +docs/PresetsApi.md +docs/PresetsRetrieveSchema.md +docs/SchemaChangeStatus.md docs/ScopedKeyParameters.md docs/SearchGroupedHit.md docs/SearchHighlight.md docs/SearchOverride.md +docs/SearchOverrideDeleteResponse.md docs/SearchOverrideExclude.md docs/SearchOverrideInclude.md docs/SearchOverrideRule.md @@ -55,48 +84,82 @@ docs/SearchOverrideSchema.md docs/SearchOverridesResponse.md docs/SearchParameters.md docs/SearchResult.md +docs/SearchResultConversation.md docs/SearchResultHit.md +docs/SearchResultHitTextMatchInfo.md docs/SearchResultRequestParams.md +docs/SearchResultRequestParamsVoiceQuery.md docs/SearchSynonym.md +docs/SearchSynonymDeleteResponse.md docs/SearchSynonymSchema.md docs/SearchSynonymsResponse.md docs/SnapshotParameters.md +docs/StemmingApi.md +docs/StemmingDictionary.md +docs/StemmingDictionaryWordsInner.md +docs/StopwordsApi.md +docs/StopwordsSetRetrieveSchema.md +docs/StopwordsSetSchema.md +docs/StopwordsSetUpsertSchema.md +docs/StopwordsSetsRetrieveAllSchema.md docs/SuccessStatus.md +docs/SynonymsApi.md docs/UpdateDocuments200Response.md -docs/UpdateDocumentsUpdateDocumentsParametersParameter.md +docs/UpdateDocumentsParameters.md +docs/VoiceQueryModelCollectionConfig.md git_push.sh src/apis/analytics_api.rs src/apis/collections_api.rs src/apis/configuration.rs +src/apis/conversations_api.rs +src/apis/curation_api.rs src/apis/debug_api.rs src/apis/documents_api.rs src/apis/health_api.rs src/apis/keys_api.rs src/apis/mod.rs +src/apis/nl_search_models_api.rs src/apis/operations_api.rs src/apis/override_api.rs -src/apis/promote_api.rs +src/apis/presets_api.rs +src/apis/stemming_api.rs +src/apis/stopwords_api.rs +src/apis/synonyms_api.rs src/lib.rs +src/models/analytics_event_create_response.rs +src/models/analytics_event_create_schema.rs +src/models/analytics_rule_delete_response.rs src/models/analytics_rule_parameters.rs src/models/analytics_rule_parameters_destination.rs src/models/analytics_rule_parameters_source.rs +src/models/analytics_rule_parameters_source_events_inner.rs src/models/analytics_rule_schema.rs +src/models/analytics_rule_upsert_schema.rs src/models/analytics_rules_retrieve_schema.rs src/models/api_key.rs +src/models/api_key_delete_response.rs src/models/api_key_schema.rs src/models/api_keys_response.rs src/models/api_response.rs +src/models/api_stats_response.rs src/models/collection_alias.rs src/models/collection_alias_schema.rs src/models/collection_aliases_response.rs src/models/collection_response.rs src/models/collection_schema.rs src/models/collection_update_schema.rs +src/models/conversation_model_create_schema.rs +src/models/conversation_model_schema.rs +src/models/conversation_model_update_schema.rs src/models/debug_200_response.rs src/models/delete_documents_200_response.rs -src/models/delete_documents_delete_documents_parameters_parameter.rs +src/models/delete_documents_parameters.rs +src/models/delete_stopwords_set_200_response.rs +src/models/dirty_values.rs +src/models/document_index_parameters.rs +src/models/drop_tokens_mode.rs src/models/error_response.rs -src/models/export_documents_export_documents_parameters_parameter.rs +src/models/export_documents_parameters.rs src/models/facet_counts.rs src/models/facet_counts_counts_inner.rs src/models/facet_counts_stats.rs @@ -104,16 +167,30 @@ src/models/field.rs src/models/field_embed.rs src/models/field_embed_model_config.rs src/models/health_status.rs -src/models/import_documents_import_documents_parameters_parameter.rs +src/models/import_documents_parameters.rs +src/models/index_action.rs +src/models/list_stemming_dictionaries_200_response.rs src/models/mod.rs src/models/multi_search_collection_parameters.rs src/models/multi_search_parameters.rs src/models/multi_search_result.rs +src/models/multi_search_result_item.rs src/models/multi_search_searches_parameter.rs +src/models/nl_search_model_base.rs +src/models/nl_search_model_create_schema.rs +src/models/nl_search_model_delete_schema.rs +src/models/nl_search_model_schema.rs +src/models/preset_delete_schema.rs +src/models/preset_schema.rs +src/models/preset_upsert_schema.rs +src/models/preset_upsert_schema_value.rs +src/models/presets_retrieve_schema.rs +src/models/schema_change_status.rs src/models/scoped_key_parameters.rs src/models/search_grouped_hit.rs src/models/search_highlight.rs src/models/search_override.rs +src/models/search_override_delete_response.rs src/models/search_override_exclude.rs src/models/search_override_include.rs src/models/search_override_rule.rs @@ -121,12 +198,23 @@ src/models/search_override_schema.rs src/models/search_overrides_response.rs src/models/search_parameters.rs src/models/search_result.rs +src/models/search_result_conversation.rs src/models/search_result_hit.rs +src/models/search_result_hit_text_match_info.rs src/models/search_result_request_params.rs +src/models/search_result_request_params_voice_query.rs src/models/search_synonym.rs +src/models/search_synonym_delete_response.rs src/models/search_synonym_schema.rs src/models/search_synonyms_response.rs src/models/snapshot_parameters.rs +src/models/stemming_dictionary.rs +src/models/stemming_dictionary_words_inner.rs +src/models/stopwords_set_retrieve_schema.rs +src/models/stopwords_set_schema.rs +src/models/stopwords_set_upsert_schema.rs +src/models/stopwords_sets_retrieve_all_schema.rs src/models/success_status.rs src/models/update_documents_200_response.rs -src/models/update_documents_update_documents_parameters_parameter.rs +src/models/update_documents_parameters.rs +src/models/voice_query_model_collection_config.rs diff --git a/typesense_codegen/.openapi-generator/VERSION b/typesense_codegen/.openapi-generator/VERSION index c9e125b..e465da4 100644 --- a/typesense_codegen/.openapi-generator/VERSION +++ b/typesense_codegen/.openapi-generator/VERSION @@ -1 +1 @@ -7.4.0-SNAPSHOT +7.14.0 diff --git a/typesense_codegen/Cargo.toml b/typesense_codegen/Cargo.toml index e899bf1..8984424 100644 --- a/typesense_codegen/Cargo.toml +++ b/typesense_codegen/Cargo.toml @@ -3,16 +3,17 @@ name = "typesense_codegen" version = "0.25.0" authors = ["OpenAPI Generator team and contributors"] description = "client for typesense generated with openapi spec" -edition = "2018" +edition = "2021" license = "Apache-2.0" [dependencies] -serde = "^1.0" -serde_derive = "^1.0" +serde = { version = "^1.0", features = ["derive"] } serde_json = "^1.0" -url = "^2.2" -uuid = { version = "^1.0", features = ["serde", "v4", "js"] } - -[dependencies.reqwest] -version = "^0.12" -features = ["json", "multipart"] +serde_repr = "^0.1" +url = "^2.5" +reqwest = { version = "^0.12", default-features = false, features = ["json", "multipart"] } +reqwest-middleware = { version = "^0.4", features = ["json", "multipart"] } +[features] +default = ["native-tls"] +native-tls = ["reqwest/native-tls"] +rustls = ["reqwest/rustls-tls"] diff --git a/typesense_codegen/README.md b/typesense_codegen/README.md index c634c1d..160a217 100644 --- a/typesense_codegen/README.md +++ b/typesense_codegen/README.md @@ -7,8 +7,9 @@ An open source search engine for building delightful search experiences. This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client. -- API version: 0.25.0 -- Package version: 0.25.0 +- API version: 28.0 +- Package version: 28.0 +- Generator version: 7.14.0 - Build package: `org.openapitools.codegen.languages.RustClientCodegen` ## Installation @@ -25,10 +26,12 @@ All URIs are relative to *http://localhost* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*AnalyticsApi* | [**create_analytics_event**](docs/AnalyticsApi.md#create_analytics_event) | **POST** /analytics/events | Create an analytics event *AnalyticsApi* | [**create_analytics_rule**](docs/AnalyticsApi.md#create_analytics_rule) | **POST** /analytics/rules | Creates an analytics rule *AnalyticsApi* | [**delete_analytics_rule**](docs/AnalyticsApi.md#delete_analytics_rule) | **DELETE** /analytics/rules/{ruleName} | Delete an analytics rule *AnalyticsApi* | [**retrieve_analytics_rule**](docs/AnalyticsApi.md#retrieve_analytics_rule) | **GET** /analytics/rules/{ruleName} | Retrieves an analytics rule *AnalyticsApi* | [**retrieve_analytics_rules**](docs/AnalyticsApi.md#retrieve_analytics_rules) | **GET** /analytics/rules | Retrieves all analytics rules +*AnalyticsApi* | [**upsert_analytics_rule**](docs/AnalyticsApi.md#upsert_analytics_rule) | **PUT** /analytics/rules/{ruleName} | Upserts an analytics rule *CollectionsApi* | [**create_collection**](docs/CollectionsApi.md#create_collection) | **POST** /collections | Create a new collection *CollectionsApi* | [**delete_alias**](docs/CollectionsApi.md#delete_alias) | **DELETE** /aliases/{aliasName} | Delete an alias *CollectionsApi* | [**delete_collection**](docs/CollectionsApi.md#delete_collection) | **DELETE** /collections/{collectionName} | Delete a collection @@ -38,17 +41,22 @@ Class | Method | HTTP request | Description *CollectionsApi* | [**get_collections**](docs/CollectionsApi.md#get_collections) | **GET** /collections | List all collections *CollectionsApi* | [**update_collection**](docs/CollectionsApi.md#update_collection) | **PATCH** /collections/{collectionName} | Update a collection *CollectionsApi* | [**upsert_alias**](docs/CollectionsApi.md#upsert_alias) | **PUT** /aliases/{aliasName} | Create or update a collection alias +*ConversationsApi* | [**create_conversation_model**](docs/ConversationsApi.md#create_conversation_model) | **POST** /conversations/models | +*ConversationsApi* | [**delete_conversation_model**](docs/ConversationsApi.md#delete_conversation_model) | **DELETE** /conversations/models/{modelId} | Delete a conversation model +*ConversationsApi* | [**retrieve_all_conversation_models**](docs/ConversationsApi.md#retrieve_all_conversation_models) | **GET** /conversations/models | List all conversation models +*ConversationsApi* | [**retrieve_conversation_model**](docs/ConversationsApi.md#retrieve_conversation_model) | **GET** /conversations/models/{modelId} | Retrieve a conversation model +*ConversationsApi* | [**update_conversation_model**](docs/ConversationsApi.md#update_conversation_model) | **PUT** /conversations/models/{modelId} | Update a conversation model +*CurationApi* | [**delete_search_override**](docs/CurationApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection +*CurationApi* | [**get_search_overrides**](docs/CurationApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides +*CurationApi* | [**upsert_search_override**](docs/CurationApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others *DebugApi* | [**debug**](docs/DebugApi.md#debug) | **GET** /debug | Print debugging information *DocumentsApi* | [**delete_document**](docs/DocumentsApi.md#delete_document) | **DELETE** /collections/{collectionName}/documents/{documentId} | Delete a document *DocumentsApi* | [**delete_documents**](docs/DocumentsApi.md#delete_documents) | **DELETE** /collections/{collectionName}/documents | Delete a bunch of documents *DocumentsApi* | [**delete_search_override**](docs/DocumentsApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection -*DocumentsApi* | [**delete_search_synonym**](docs/DocumentsApi.md#delete_search_synonym) | **DELETE** /collections/{collectionName}/synonyms/{synonymId} | Delete a synonym associated with a collection *DocumentsApi* | [**export_documents**](docs/DocumentsApi.md#export_documents) | **GET** /collections/{collectionName}/documents/export | Export all documents in a collection *DocumentsApi* | [**get_document**](docs/DocumentsApi.md#get_document) | **GET** /collections/{collectionName}/documents/{documentId} | Retreive a document *DocumentsApi* | [**get_search_override**](docs/DocumentsApi.md#get_search_override) | **GET** /collections/{collectionName}/overrides/{overrideId} | Retrieve a single search override *DocumentsApi* | [**get_search_overrides**](docs/DocumentsApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides -*DocumentsApi* | [**get_search_synonym**](docs/DocumentsApi.md#get_search_synonym) | **GET** /collections/{collectionName}/synonyms/{synonymId} | Retrieve a single search synonym -*DocumentsApi* | [**get_search_synonyms**](docs/DocumentsApi.md#get_search_synonyms) | **GET** /collections/{collectionName}/synonyms | List all collection synonyms *DocumentsApi* | [**import_documents**](docs/DocumentsApi.md#import_documents) | **POST** /collections/{collectionName}/documents/import | Import documents into a collection *DocumentsApi* | [**index_document**](docs/DocumentsApi.md#index_document) | **POST** /collections/{collectionName}/documents | Index a document *DocumentsApi* | [**multi_search**](docs/DocumentsApi.md#multi_search) | **POST** /multi_search | send multiple search requests in a single HTTP request @@ -56,42 +64,75 @@ Class | Method | HTTP request | Description *DocumentsApi* | [**update_document**](docs/DocumentsApi.md#update_document) | **PATCH** /collections/{collectionName}/documents/{documentId} | Update a document *DocumentsApi* | [**update_documents**](docs/DocumentsApi.md#update_documents) | **PATCH** /collections/{collectionName}/documents | Update documents with conditional query *DocumentsApi* | [**upsert_search_override**](docs/DocumentsApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others -*DocumentsApi* | [**upsert_search_synonym**](docs/DocumentsApi.md#upsert_search_synonym) | **PUT** /collections/{collectionName}/synonyms/{synonymId} | Create or update a synonym *HealthApi* | [**health**](docs/HealthApi.md#health) | **GET** /health | Checks if Typesense server is ready to accept requests. *KeysApi* | [**create_key**](docs/KeysApi.md#create_key) | **POST** /keys | Create an API Key *KeysApi* | [**delete_key**](docs/KeysApi.md#delete_key) | **DELETE** /keys/{keyId} | Delete an API key given its ID. *KeysApi* | [**get_key**](docs/KeysApi.md#get_key) | **GET** /keys/{keyId} | Retrieve (metadata about) a key *KeysApi* | [**get_keys**](docs/KeysApi.md#get_keys) | **GET** /keys | Retrieve (metadata about) all keys. +*NlSearchModelsApi* | [**create_nl_search_model**](docs/NlSearchModelsApi.md#create_nl_search_model) | **POST** /nl_search_models | Create a NL search model +*NlSearchModelsApi* | [**delete_nl_search_model**](docs/NlSearchModelsApi.md#delete_nl_search_model) | **DELETE** /nl_search_models/{modelId} | Delete a NL search model +*NlSearchModelsApi* | [**retrieve_all_nl_search_models**](docs/NlSearchModelsApi.md#retrieve_all_nl_search_models) | **GET** /nl_search_models | List all NL search models +*NlSearchModelsApi* | [**retrieve_nl_search_model**](docs/NlSearchModelsApi.md#retrieve_nl_search_model) | **GET** /nl_search_models/{modelId} | Retrieve a NL search model +*NlSearchModelsApi* | [**update_nl_search_model**](docs/NlSearchModelsApi.md#update_nl_search_model) | **PUT** /nl_search_models/{modelId} | Update a NL search model +*OperationsApi* | [**get_schema_changes**](docs/OperationsApi.md#get_schema_changes) | **GET** /operations/schema_changes | Get the status of in-progress schema change operations +*OperationsApi* | [**retrieve_api_stats**](docs/OperationsApi.md#retrieve_api_stats) | **GET** /stats.json | Get stats about API endpoints. +*OperationsApi* | [**retrieve_metrics**](docs/OperationsApi.md#retrieve_metrics) | **GET** /metrics.json | Get current RAM, CPU, Disk & Network usage metrics. *OperationsApi* | [**take_snapshot**](docs/OperationsApi.md#take_snapshot) | **POST** /operations/snapshot | Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. *OperationsApi* | [**vote**](docs/OperationsApi.md#vote) | **POST** /operations/vote | Triggers a follower node to initiate the raft voting process, which triggers leader re-election. *OverrideApi* | [**get_search_override**](docs/OverrideApi.md#get_search_override) | **GET** /collections/{collectionName}/overrides/{overrideId} | Retrieve a single search override -*PromoteApi* | [**delete_search_override**](docs/PromoteApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection -*PromoteApi* | [**get_search_overrides**](docs/PromoteApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides -*PromoteApi* | [**upsert_search_override**](docs/PromoteApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others +*PresetsApi* | [**delete_preset**](docs/PresetsApi.md#delete_preset) | **DELETE** /presets/{presetId} | Delete a preset. +*PresetsApi* | [**retrieve_all_presets**](docs/PresetsApi.md#retrieve_all_presets) | **GET** /presets | Retrieves all presets. +*PresetsApi* | [**retrieve_preset**](docs/PresetsApi.md#retrieve_preset) | **GET** /presets/{presetId} | Retrieves a preset. +*PresetsApi* | [**upsert_preset**](docs/PresetsApi.md#upsert_preset) | **PUT** /presets/{presetId} | Upserts a preset. +*StemmingApi* | [**get_stemming_dictionary**](docs/StemmingApi.md#get_stemming_dictionary) | **GET** /stemming/dictionaries/{dictionaryId} | Retrieve a stemming dictionary +*StemmingApi* | [**import_stemming_dictionary**](docs/StemmingApi.md#import_stemming_dictionary) | **POST** /stemming/dictionaries/import | Import a stemming dictionary +*StemmingApi* | [**list_stemming_dictionaries**](docs/StemmingApi.md#list_stemming_dictionaries) | **GET** /stemming/dictionaries | List all stemming dictionaries +*StopwordsApi* | [**delete_stopwords_set**](docs/StopwordsApi.md#delete_stopwords_set) | **DELETE** /stopwords/{setId} | Delete a stopwords set. +*StopwordsApi* | [**retrieve_stopwords_set**](docs/StopwordsApi.md#retrieve_stopwords_set) | **GET** /stopwords/{setId} | Retrieves a stopwords set. +*StopwordsApi* | [**retrieve_stopwords_sets**](docs/StopwordsApi.md#retrieve_stopwords_sets) | **GET** /stopwords | Retrieves all stopwords sets. +*StopwordsApi* | [**upsert_stopwords_set**](docs/StopwordsApi.md#upsert_stopwords_set) | **PUT** /stopwords/{setId} | Upserts a stopwords set. +*SynonymsApi* | [**delete_search_synonym**](docs/SynonymsApi.md#delete_search_synonym) | **DELETE** /collections/{collectionName}/synonyms/{synonymId} | Delete a synonym associated with a collection +*SynonymsApi* | [**get_search_synonym**](docs/SynonymsApi.md#get_search_synonym) | **GET** /collections/{collectionName}/synonyms/{synonymId} | Retrieve a single search synonym +*SynonymsApi* | [**get_search_synonyms**](docs/SynonymsApi.md#get_search_synonyms) | **GET** /collections/{collectionName}/synonyms | List all collection synonyms +*SynonymsApi* | [**upsert_search_synonym**](docs/SynonymsApi.md#upsert_search_synonym) | **PUT** /collections/{collectionName}/synonyms/{synonymId} | Create or update a synonym ## Documentation For Models + - [AnalyticsEventCreateResponse](docs/AnalyticsEventCreateResponse.md) + - [AnalyticsEventCreateSchema](docs/AnalyticsEventCreateSchema.md) + - [AnalyticsRuleDeleteResponse](docs/AnalyticsRuleDeleteResponse.md) - [AnalyticsRuleParameters](docs/AnalyticsRuleParameters.md) - [AnalyticsRuleParametersDestination](docs/AnalyticsRuleParametersDestination.md) - [AnalyticsRuleParametersSource](docs/AnalyticsRuleParametersSource.md) + - [AnalyticsRuleParametersSourceEventsInner](docs/AnalyticsRuleParametersSourceEventsInner.md) - [AnalyticsRuleSchema](docs/AnalyticsRuleSchema.md) + - [AnalyticsRuleUpsertSchema](docs/AnalyticsRuleUpsertSchema.md) - [AnalyticsRulesRetrieveSchema](docs/AnalyticsRulesRetrieveSchema.md) - [ApiKey](docs/ApiKey.md) + - [ApiKeyDeleteResponse](docs/ApiKeyDeleteResponse.md) - [ApiKeySchema](docs/ApiKeySchema.md) - [ApiKeysResponse](docs/ApiKeysResponse.md) - [ApiResponse](docs/ApiResponse.md) + - [ApiStatsResponse](docs/ApiStatsResponse.md) - [CollectionAlias](docs/CollectionAlias.md) - [CollectionAliasSchema](docs/CollectionAliasSchema.md) - [CollectionAliasesResponse](docs/CollectionAliasesResponse.md) - [CollectionResponse](docs/CollectionResponse.md) - [CollectionSchema](docs/CollectionSchema.md) - [CollectionUpdateSchema](docs/CollectionUpdateSchema.md) + - [ConversationModelCreateSchema](docs/ConversationModelCreateSchema.md) + - [ConversationModelSchema](docs/ConversationModelSchema.md) + - [ConversationModelUpdateSchema](docs/ConversationModelUpdateSchema.md) - [Debug200Response](docs/Debug200Response.md) - [DeleteDocuments200Response](docs/DeleteDocuments200Response.md) - - [DeleteDocumentsDeleteDocumentsParametersParameter](docs/DeleteDocumentsDeleteDocumentsParametersParameter.md) + - [DeleteDocumentsParameters](docs/DeleteDocumentsParameters.md) + - [DeleteStopwordsSet200Response](docs/DeleteStopwordsSet200Response.md) + - [DirtyValues](docs/DirtyValues.md) + - [DocumentIndexParameters](docs/DocumentIndexParameters.md) + - [DropTokensMode](docs/DropTokensMode.md) - [ErrorResponse](docs/ErrorResponse.md) - - [ExportDocumentsExportDocumentsParametersParameter](docs/ExportDocumentsExportDocumentsParametersParameter.md) + - [ExportDocumentsParameters](docs/ExportDocumentsParameters.md) - [FacetCounts](docs/FacetCounts.md) - [FacetCountsCountsInner](docs/FacetCountsCountsInner.md) - [FacetCountsStats](docs/FacetCountsStats.md) @@ -99,15 +140,29 @@ Class | Method | HTTP request | Description - [FieldEmbed](docs/FieldEmbed.md) - [FieldEmbedModelConfig](docs/FieldEmbedModelConfig.md) - [HealthStatus](docs/HealthStatus.md) - - [ImportDocumentsImportDocumentsParametersParameter](docs/ImportDocumentsImportDocumentsParametersParameter.md) + - [ImportDocumentsParameters](docs/ImportDocumentsParameters.md) + - [IndexAction](docs/IndexAction.md) + - [ListStemmingDictionaries200Response](docs/ListStemmingDictionaries200Response.md) - [MultiSearchCollectionParameters](docs/MultiSearchCollectionParameters.md) - [MultiSearchParameters](docs/MultiSearchParameters.md) - [MultiSearchResult](docs/MultiSearchResult.md) + - [MultiSearchResultItem](docs/MultiSearchResultItem.md) - [MultiSearchSearchesParameter](docs/MultiSearchSearchesParameter.md) + - [NlSearchModelBase](docs/NlSearchModelBase.md) + - [NlSearchModelCreateSchema](docs/NlSearchModelCreateSchema.md) + - [NlSearchModelDeleteSchema](docs/NlSearchModelDeleteSchema.md) + - [NlSearchModelSchema](docs/NlSearchModelSchema.md) + - [PresetDeleteSchema](docs/PresetDeleteSchema.md) + - [PresetSchema](docs/PresetSchema.md) + - [PresetUpsertSchema](docs/PresetUpsertSchema.md) + - [PresetUpsertSchemaValue](docs/PresetUpsertSchemaValue.md) + - [PresetsRetrieveSchema](docs/PresetsRetrieveSchema.md) + - [SchemaChangeStatus](docs/SchemaChangeStatus.md) - [ScopedKeyParameters](docs/ScopedKeyParameters.md) - [SearchGroupedHit](docs/SearchGroupedHit.md) - [SearchHighlight](docs/SearchHighlight.md) - [SearchOverride](docs/SearchOverride.md) + - [SearchOverrideDeleteResponse](docs/SearchOverrideDeleteResponse.md) - [SearchOverrideExclude](docs/SearchOverrideExclude.md) - [SearchOverrideInclude](docs/SearchOverrideInclude.md) - [SearchOverrideRule](docs/SearchOverrideRule.md) @@ -115,15 +170,26 @@ Class | Method | HTTP request | Description - [SearchOverridesResponse](docs/SearchOverridesResponse.md) - [SearchParameters](docs/SearchParameters.md) - [SearchResult](docs/SearchResult.md) + - [SearchResultConversation](docs/SearchResultConversation.md) - [SearchResultHit](docs/SearchResultHit.md) + - [SearchResultHitTextMatchInfo](docs/SearchResultHitTextMatchInfo.md) - [SearchResultRequestParams](docs/SearchResultRequestParams.md) + - [SearchResultRequestParamsVoiceQuery](docs/SearchResultRequestParamsVoiceQuery.md) - [SearchSynonym](docs/SearchSynonym.md) + - [SearchSynonymDeleteResponse](docs/SearchSynonymDeleteResponse.md) - [SearchSynonymSchema](docs/SearchSynonymSchema.md) - [SearchSynonymsResponse](docs/SearchSynonymsResponse.md) - [SnapshotParameters](docs/SnapshotParameters.md) + - [StemmingDictionary](docs/StemmingDictionary.md) + - [StemmingDictionaryWordsInner](docs/StemmingDictionaryWordsInner.md) + - [StopwordsSetRetrieveSchema](docs/StopwordsSetRetrieveSchema.md) + - [StopwordsSetSchema](docs/StopwordsSetSchema.md) + - [StopwordsSetUpsertSchema](docs/StopwordsSetUpsertSchema.md) + - [StopwordsSetsRetrieveAllSchema](docs/StopwordsSetsRetrieveAllSchema.md) - [SuccessStatus](docs/SuccessStatus.md) - [UpdateDocuments200Response](docs/UpdateDocuments200Response.md) - - [UpdateDocumentsUpdateDocumentsParametersParameter](docs/UpdateDocumentsUpdateDocumentsParametersParameter.md) + - [UpdateDocumentsParameters](docs/UpdateDocumentsParameters.md) + - [VoiceQueryModelCollectionConfig](docs/VoiceQueryModelCollectionConfig.md) To get access to the crate's generated documentation, use: diff --git a/typesense_codegen/docs/AnalyticsApi.md b/typesense_codegen/docs/AnalyticsApi.md index 7b6b7d0..f9ba22c 100644 --- a/typesense_codegen/docs/AnalyticsApi.md +++ b/typesense_codegen/docs/AnalyticsApi.md @@ -4,16 +4,48 @@ All URIs are relative to *http://localhost* Method | HTTP request | Description ------------- | ------------- | ------------- +[**create_analytics_event**](AnalyticsApi.md#create_analytics_event) | **POST** /analytics/events | Create an analytics event [**create_analytics_rule**](AnalyticsApi.md#create_analytics_rule) | **POST** /analytics/rules | Creates an analytics rule [**delete_analytics_rule**](AnalyticsApi.md#delete_analytics_rule) | **DELETE** /analytics/rules/{ruleName} | Delete an analytics rule [**retrieve_analytics_rule**](AnalyticsApi.md#retrieve_analytics_rule) | **GET** /analytics/rules/{ruleName} | Retrieves an analytics rule [**retrieve_analytics_rules**](AnalyticsApi.md#retrieve_analytics_rules) | **GET** /analytics/rules | Retrieves all analytics rules +[**upsert_analytics_rule**](AnalyticsApi.md#upsert_analytics_rule) | **PUT** /analytics/rules/{ruleName} | Upserts an analytics rule +## create_analytics_event + +> models::AnalyticsEventCreateResponse create_analytics_event(analytics_event_create_schema) +Create an analytics event + +Sending events for analytics e.g rank search results based on popularity. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**analytics_event_create_schema** | [**AnalyticsEventCreateSchema**](AnalyticsEventCreateSchema.md) | The Analytics event to be created | [required] | + +### Return type + +[**models::AnalyticsEventCreateResponse**](AnalyticsEventCreateResponse.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + ## create_analytics_rule -> crate::models::AnalyticsRuleSchema create_analytics_rule(analytics_rule_schema) +> models::AnalyticsRuleSchema create_analytics_rule(analytics_rule_schema) Creates an analytics rule When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. @@ -27,7 +59,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::AnalyticsRuleSchema**](AnalyticsRuleSchema.md) +[**models::AnalyticsRuleSchema**](AnalyticsRuleSchema.md) ### Authorization @@ -43,7 +75,7 @@ Name | Type | Description | Required | Notes ## delete_analytics_rule -> crate::models::AnalyticsRuleSchema delete_analytics_rule(rule_name) +> models::AnalyticsRuleDeleteResponse delete_analytics_rule(rule_name) Delete an analytics rule Permanently deletes an analytics rule, given it's name @@ -57,7 +89,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::AnalyticsRuleSchema**](AnalyticsRuleSchema.md) +[**models::AnalyticsRuleDeleteResponse**](AnalyticsRuleDeleteResponse.md) ### Authorization @@ -73,7 +105,7 @@ Name | Type | Description | Required | Notes ## retrieve_analytics_rule -> crate::models::AnalyticsRuleSchema retrieve_analytics_rule(rule_name) +> models::AnalyticsRuleSchema retrieve_analytics_rule(rule_name) Retrieves an analytics rule Retrieve the details of an analytics rule, given it's name @@ -87,7 +119,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::AnalyticsRuleSchema**](AnalyticsRuleSchema.md) +[**models::AnalyticsRuleSchema**](AnalyticsRuleSchema.md) ### Authorization @@ -103,7 +135,7 @@ Name | Type | Description | Required | Notes ## retrieve_analytics_rules -> crate::models::AnalyticsRulesRetrieveSchema retrieve_analytics_rules() +> models::AnalyticsRulesRetrieveSchema retrieve_analytics_rules() Retrieves all analytics rules Retrieve the details of all analytics rules @@ -114,7 +146,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::AnalyticsRulesRetrieveSchema**](AnalyticsRulesRetrieveSchema.md) +[**models::AnalyticsRulesRetrieveSchema**](AnalyticsRulesRetrieveSchema.md) ### Authorization @@ -127,3 +159,34 @@ This endpoint does not need any parameter. [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +## upsert_analytics_rule + +> models::AnalyticsRuleSchema upsert_analytics_rule(rule_name, analytics_rule_upsert_schema) +Upserts an analytics rule + +Upserts an analytics rule with the given name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**rule_name** | **String** | The name of the analytics rule to upsert | [required] | +**analytics_rule_upsert_schema** | [**AnalyticsRuleUpsertSchema**](AnalyticsRuleUpsertSchema.md) | The Analytics rule to be upserted | [required] | + +### Return type + +[**models::AnalyticsRuleSchema**](AnalyticsRuleSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/AnalyticsEventCreateResponse.md b/typesense_codegen/docs/AnalyticsEventCreateResponse.md new file mode 100644 index 0000000..321be7b --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEventCreateResponse.md @@ -0,0 +1,11 @@ +# AnalyticsEventCreateResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ok** | **bool** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsEventCreateSchema.md b/typesense_codegen/docs/AnalyticsEventCreateSchema.md new file mode 100644 index 0000000..97c07cc --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEventCreateSchema.md @@ -0,0 +1,13 @@ +# AnalyticsEventCreateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | **String** | | +**name** | **String** | | +**data** | [**serde_json::Value**](.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleDeleteResponse.md b/typesense_codegen/docs/AnalyticsRuleDeleteResponse.md new file mode 100644 index 0000000..bd7512f --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleDeleteResponse.md @@ -0,0 +1,11 @@ +# AnalyticsRuleDeleteResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleParameters.md b/typesense_codegen/docs/AnalyticsRuleParameters.md index 31b4ac4..9be9eeb 100644 --- a/typesense_codegen/docs/AnalyticsRuleParameters.md +++ b/typesense_codegen/docs/AnalyticsRuleParameters.md @@ -4,9 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**source** | [**crate::models::AnalyticsRuleParametersSource**](AnalyticsRuleParameters_source.md) | | -**destination** | [**crate::models::AnalyticsRuleParametersDestination**](AnalyticsRuleParameters_destination.md) | | -**limit** | **i32** | | +**source** | [**models::AnalyticsRuleParametersSource**](AnalyticsRuleParametersSource.md) | | +**destination** | [**models::AnalyticsRuleParametersDestination**](AnalyticsRuleParametersDestination.md) | | +**limit** | Option<**i32**> | | [optional] +**expand_query** | Option<**bool**> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsRuleParametersDestination.md b/typesense_codegen/docs/AnalyticsRuleParametersDestination.md index 6bf99e5..e5efc9b 100644 --- a/typesense_codegen/docs/AnalyticsRuleParametersDestination.md +++ b/typesense_codegen/docs/AnalyticsRuleParametersDestination.md @@ -4,7 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**collection** | Option<**String**> | | [optional] +**collection** | **String** | | +**counter_field** | Option<**String**> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsRuleParametersSource.md b/typesense_codegen/docs/AnalyticsRuleParametersSource.md index b6a042b..05ab04d 100644 --- a/typesense_codegen/docs/AnalyticsRuleParametersSource.md +++ b/typesense_codegen/docs/AnalyticsRuleParametersSource.md @@ -4,7 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**collections** | Option<**Vec**> | | [optional] +**collections** | **Vec** | | +**events** | Option<[**Vec**](AnalyticsRuleParametersSource_events_inner.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsRuleParametersSourceEventsInner.md b/typesense_codegen/docs/AnalyticsRuleParametersSourceEventsInner.md new file mode 100644 index 0000000..31264d2 --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleParametersSourceEventsInner.md @@ -0,0 +1,13 @@ +# AnalyticsRuleParametersSourceEventsInner + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | **String** | | +**weight** | **f32** | | +**name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleSchema.md b/typesense_codegen/docs/AnalyticsRuleSchema.md index 359d489..4afdcd4 100644 --- a/typesense_codegen/docs/AnalyticsRuleSchema.md +++ b/typesense_codegen/docs/AnalyticsRuleSchema.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**name** | **String** | | **r#type** | **String** | | -**params** | [**crate::models::AnalyticsRuleParameters**](AnalyticsRuleParameters.md) | | +**params** | [**models::AnalyticsRuleParameters**](AnalyticsRuleParameters.md) | | +**name** | **String** | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsRuleUpsertSchema.md b/typesense_codegen/docs/AnalyticsRuleUpsertSchema.md new file mode 100644 index 0000000..fa21e43 --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleUpsertSchema.md @@ -0,0 +1,12 @@ +# AnalyticsRuleUpsertSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | **String** | | +**params** | [**models::AnalyticsRuleParameters**](AnalyticsRuleParameters.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRulesRetrieveSchema.md b/typesense_codegen/docs/AnalyticsRulesRetrieveSchema.md index f20cf77..c310473 100644 --- a/typesense_codegen/docs/AnalyticsRulesRetrieveSchema.md +++ b/typesense_codegen/docs/AnalyticsRulesRetrieveSchema.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**rules** | Option<[**Vec**](AnalyticsRuleSchema.md)> | | [optional] +**rules** | Option<[**Vec**](AnalyticsRuleSchema.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/ApiKeyDeleteResponse.md b/typesense_codegen/docs/ApiKeyDeleteResponse.md new file mode 100644 index 0000000..8c38f9e --- /dev/null +++ b/typesense_codegen/docs/ApiKeyDeleteResponse.md @@ -0,0 +1,11 @@ +# ApiKeyDeleteResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **i64** | The id of the API key that was deleted | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ApiKeysResponse.md b/typesense_codegen/docs/ApiKeysResponse.md index 1eac36f..c3e6c3d 100644 --- a/typesense_codegen/docs/ApiKeysResponse.md +++ b/typesense_codegen/docs/ApiKeysResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**keys** | [**Vec**](ApiKey.md) | | +**keys** | [**Vec**](ApiKey.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/ApiStatsResponse.md b/typesense_codegen/docs/ApiStatsResponse.md new file mode 100644 index 0000000..c2569e7 --- /dev/null +++ b/typesense_codegen/docs/ApiStatsResponse.md @@ -0,0 +1,23 @@ +# ApiStatsResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**delete_latency_ms** | Option<**f64**> | | [optional] +**delete_requests_per_second** | Option<**f64**> | | [optional] +**import_latency_ms** | Option<**f64**> | | [optional] +**import_requests_per_second** | Option<**f64**> | | [optional] +**latency_ms** | Option<[**serde_json::Value**](.md)> | | [optional] +**overloaded_requests_per_second** | Option<**f64**> | | [optional] +**pending_write_batches** | Option<**f64**> | | [optional] +**requests_per_second** | Option<[**serde_json::Value**](.md)> | | [optional] +**search_latency_ms** | Option<**f64**> | | [optional] +**search_requests_per_second** | Option<**f64**> | | [optional] +**total_requests_per_second** | Option<**f64**> | | [optional] +**write_latency_ms** | Option<**f64**> | | [optional] +**write_requests_per_second** | Option<**f64**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/CollectionAliasesResponse.md b/typesense_codegen/docs/CollectionAliasesResponse.md index b8a0399..285708c 100644 --- a/typesense_codegen/docs/CollectionAliasesResponse.md +++ b/typesense_codegen/docs/CollectionAliasesResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**aliases** | [**Vec**](CollectionAlias.md) | | +**aliases** | [**Vec**](CollectionAlias.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/CollectionResponse.md b/typesense_codegen/docs/CollectionResponse.md index aeb74a4..f67f018 100644 --- a/typesense_codegen/docs/CollectionResponse.md +++ b/typesense_codegen/docs/CollectionResponse.md @@ -5,11 +5,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **String** | Name of the collection | -**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | +**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | **default_sorting_field** | Option<**String**> | The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. | [optional][default to ] -**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] +**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] **enable_nested_fields** | Option<**bool**> | Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. | [optional][default to false] **symbols_to_index** | Option<**Vec**> | List of symbols or special characters to be indexed. | [optional][default to []] +**voice_query_model** | Option<[**models::VoiceQueryModelCollectionConfig**](VoiceQueryModelCollectionConfig.md)> | | [optional] **num_documents** | **i64** | Number of documents in the collection | [readonly] **created_at** | **i64** | Timestamp of when the collection was created (Unix epoch in seconds) | [readonly] diff --git a/typesense_codegen/docs/CollectionSchema.md b/typesense_codegen/docs/CollectionSchema.md index 1f78262..00d94cc 100644 --- a/typesense_codegen/docs/CollectionSchema.md +++ b/typesense_codegen/docs/CollectionSchema.md @@ -5,11 +5,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **String** | Name of the collection | -**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | +**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | **default_sorting_field** | Option<**String**> | The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. | [optional][default to ] -**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] +**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] **enable_nested_fields** | Option<**bool**> | Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. | [optional][default to false] **symbols_to_index** | Option<**Vec**> | List of symbols or special characters to be indexed. | [optional][default to []] +**voice_query_model** | Option<[**models::VoiceQueryModelCollectionConfig**](VoiceQueryModelCollectionConfig.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/CollectionUpdateSchema.md b/typesense_codegen/docs/CollectionUpdateSchema.md index d40d070..8fd57bc 100644 --- a/typesense_codegen/docs/CollectionUpdateSchema.md +++ b/typesense_codegen/docs/CollectionUpdateSchema.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | +**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/CollectionsApi.md b/typesense_codegen/docs/CollectionsApi.md index 14cb336..9dd1408 100644 --- a/typesense_codegen/docs/CollectionsApi.md +++ b/typesense_codegen/docs/CollectionsApi.md @@ -18,7 +18,7 @@ Method | HTTP request | Description ## create_collection -> crate::models::CollectionResponse create_collection(collection_schema) +> models::CollectionResponse create_collection(collection_schema) Create a new collection When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. @@ -32,7 +32,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionResponse**](CollectionResponse.md) +[**models::CollectionResponse**](CollectionResponse.md) ### Authorization @@ -48,7 +48,7 @@ Name | Type | Description | Required | Notes ## delete_alias -> crate::models::CollectionAlias delete_alias(alias_name) +> models::CollectionAlias delete_alias(alias_name) Delete an alias ### Parameters @@ -60,7 +60,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionAlias**](CollectionAlias.md) +[**models::CollectionAlias**](CollectionAlias.md) ### Authorization @@ -76,7 +76,7 @@ Name | Type | Description | Required | Notes ## delete_collection -> crate::models::CollectionResponse delete_collection(collection_name) +> models::CollectionResponse delete_collection(collection_name) Delete a collection Permanently drops a collection. This action cannot be undone. For large collections, this might have an impact on read latencies. @@ -90,7 +90,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionResponse**](CollectionResponse.md) +[**models::CollectionResponse**](CollectionResponse.md) ### Authorization @@ -106,7 +106,7 @@ Name | Type | Description | Required | Notes ## get_alias -> crate::models::CollectionAlias get_alias(alias_name) +> models::CollectionAlias get_alias(alias_name) Retrieve an alias Find out which collection an alias points to by fetching it @@ -120,7 +120,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionAlias**](CollectionAlias.md) +[**models::CollectionAlias**](CollectionAlias.md) ### Authorization @@ -136,7 +136,7 @@ Name | Type | Description | Required | Notes ## get_aliases -> crate::models::CollectionAliasesResponse get_aliases() +> models::CollectionAliasesResponse get_aliases() List all aliases List all aliases and the corresponding collections that they map to. @@ -147,7 +147,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::CollectionAliasesResponse**](CollectionAliasesResponse.md) +[**models::CollectionAliasesResponse**](CollectionAliasesResponse.md) ### Authorization @@ -163,7 +163,7 @@ This endpoint does not need any parameter. ## get_collection -> crate::models::CollectionResponse get_collection(collection_name) +> models::CollectionResponse get_collection(collection_name) Retrieve a single collection Retrieve the details of a collection, given its name. @@ -177,7 +177,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionResponse**](CollectionResponse.md) +[**models::CollectionResponse**](CollectionResponse.md) ### Authorization @@ -193,7 +193,7 @@ Name | Type | Description | Required | Notes ## get_collections -> Vec get_collections() +> Vec get_collections() List all collections Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first. @@ -204,7 +204,7 @@ This endpoint does not need any parameter. ### Return type -[**Vec**](CollectionResponse.md) +[**Vec**](CollectionResponse.md) ### Authorization @@ -220,7 +220,7 @@ This endpoint does not need any parameter. ## update_collection -> crate::models::CollectionUpdateSchema update_collection(collection_name, collection_update_schema) +> models::CollectionUpdateSchema update_collection(collection_name, collection_update_schema) Update a collection Update a collection's schema to modify the fields and their types. @@ -235,7 +235,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionUpdateSchema**](CollectionUpdateSchema.md) +[**models::CollectionUpdateSchema**](CollectionUpdateSchema.md) ### Authorization @@ -251,7 +251,7 @@ Name | Type | Description | Required | Notes ## upsert_alias -> crate::models::CollectionAlias upsert_alias(alias_name, collection_alias_schema) +> models::CollectionAlias upsert_alias(alias_name, collection_alias_schema) Create or update a collection alias Create or update a collection alias. An alias is a virtual collection name that points to a real collection. If you're familiar with symbolic links on Linux, it's very similar to that. Aliases are useful when you want to reindex your data in the background on a new collection and switch your application to it without any changes to your code. @@ -266,7 +266,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionAlias**](CollectionAlias.md) +[**models::CollectionAlias**](CollectionAlias.md) ### Authorization diff --git a/typesense_codegen/docs/ConversationModelCreateSchema.md b/typesense_codegen/docs/ConversationModelCreateSchema.md new file mode 100644 index 0000000..a8d70c5 --- /dev/null +++ b/typesense_codegen/docs/ConversationModelCreateSchema.md @@ -0,0 +1,19 @@ +# ConversationModelCreateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | Option<**String**> | An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. | [optional] +**model_name** | **String** | Name of the LLM model offered by OpenAI, Cloudflare or vLLM | +**api_key** | Option<**String**> | The LLM service's API Key | [optional] +**history_collection** | **String** | Typesense collection that stores the historical conversations | +**account_id** | Option<**String**> | LLM service's account ID (only applicable for Cloudflare) | [optional] +**system_prompt** | Option<**String**> | The system prompt that contains special instructions to the LLM | [optional] +**ttl** | Option<**i32**> | Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) | [optional] +**max_bytes** | **i32** | The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. | +**vllm_url** | Option<**String**> | URL of vLLM service | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ConversationModelSchema.md b/typesense_codegen/docs/ConversationModelSchema.md new file mode 100644 index 0000000..f9fe0d2 --- /dev/null +++ b/typesense_codegen/docs/ConversationModelSchema.md @@ -0,0 +1,19 @@ +# ConversationModelSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. | +**model_name** | **String** | Name of the LLM model offered by OpenAI, Cloudflare or vLLM | +**api_key** | Option<**String**> | The LLM service's API Key | [optional] +**history_collection** | **String** | Typesense collection that stores the historical conversations | +**account_id** | Option<**String**> | LLM service's account ID (only applicable for Cloudflare) | [optional] +**system_prompt** | Option<**String**> | The system prompt that contains special instructions to the LLM | [optional] +**ttl** | Option<**i32**> | Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) | [optional] +**max_bytes** | **i32** | The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. | +**vllm_url** | Option<**String**> | URL of vLLM service | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ConversationModelUpdateSchema.md b/typesense_codegen/docs/ConversationModelUpdateSchema.md new file mode 100644 index 0000000..a9471ce --- /dev/null +++ b/typesense_codegen/docs/ConversationModelUpdateSchema.md @@ -0,0 +1,19 @@ +# ConversationModelUpdateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | Option<**String**> | An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. | [optional] +**model_name** | Option<**String**> | Name of the LLM model offered by OpenAI, Cloudflare or vLLM | [optional] +**api_key** | Option<**String**> | The LLM service's API Key | [optional] +**history_collection** | Option<**String**> | Typesense collection that stores the historical conversations | [optional] +**account_id** | Option<**String**> | LLM service's account ID (only applicable for Cloudflare) | [optional] +**system_prompt** | Option<**String**> | The system prompt that contains special instructions to the LLM | [optional] +**ttl** | Option<**i32**> | Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) | [optional] +**max_bytes** | Option<**i32**> | The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. | [optional] +**vllm_url** | Option<**String**> | URL of vLLM service | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ConversationsApi.md b/typesense_codegen/docs/ConversationsApi.md new file mode 100644 index 0000000..f61018c --- /dev/null +++ b/typesense_codegen/docs/ConversationsApi.md @@ -0,0 +1,161 @@ +# \ConversationsApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_conversation_model**](ConversationsApi.md#create_conversation_model) | **POST** /conversations/models | +[**delete_conversation_model**](ConversationsApi.md#delete_conversation_model) | **DELETE** /conversations/models/{modelId} | Delete a conversation model +[**retrieve_all_conversation_models**](ConversationsApi.md#retrieve_all_conversation_models) | **GET** /conversations/models | List all conversation models +[**retrieve_conversation_model**](ConversationsApi.md#retrieve_conversation_model) | **GET** /conversations/models/{modelId} | Retrieve a conversation model +[**update_conversation_model**](ConversationsApi.md#update_conversation_model) | **PUT** /conversations/models/{modelId} | Update a conversation model + + + +## create_conversation_model + +> models::ConversationModelSchema create_conversation_model(conversation_model_create_schema) + + +Create a Conversation Model + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**conversation_model_create_schema** | [**ConversationModelCreateSchema**](ConversationModelCreateSchema.md) | | [required] | + +### Return type + +[**models::ConversationModelSchema**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## delete_conversation_model + +> models::ConversationModelSchema delete_conversation_model(model_id) +Delete a conversation model + +Delete a conversation model + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The id of the conversation model to delete | [required] | + +### Return type + +[**models::ConversationModelSchema**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_all_conversation_models + +> Vec retrieve_all_conversation_models() +List all conversation models + +Retrieve all conversation models + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**Vec**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_conversation_model + +> models::ConversationModelSchema retrieve_conversation_model(model_id) +Retrieve a conversation model + +Retrieve a conversation model + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The id of the conversation model to retrieve | [required] | + +### Return type + +[**models::ConversationModelSchema**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## update_conversation_model + +> models::ConversationModelSchema update_conversation_model(model_id, conversation_model_update_schema) +Update a conversation model + +Update a conversation model + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The id of the conversation model to update | [required] | +**conversation_model_update_schema** | [**ConversationModelUpdateSchema**](ConversationModelUpdateSchema.md) | | [required] | + +### Return type + +[**models::ConversationModelSchema**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/PromoteApi.md b/typesense_codegen/docs/CurationApi.md similarity index 71% rename from typesense_codegen/docs/PromoteApi.md rename to typesense_codegen/docs/CurationApi.md index 948b093..13a43fa 100644 --- a/typesense_codegen/docs/PromoteApi.md +++ b/typesense_codegen/docs/CurationApi.md @@ -1,18 +1,18 @@ -# \PromoteApi +# \CurationApi All URIs are relative to *http://localhost* Method | HTTP request | Description ------------- | ------------- | ------------- -[**delete_search_override**](PromoteApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection -[**get_search_overrides**](PromoteApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides -[**upsert_search_override**](PromoteApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others +[**delete_search_override**](CurationApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection +[**get_search_overrides**](CurationApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides +[**upsert_search_override**](CurationApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others ## delete_search_override -> crate::models::SearchOverride delete_search_override(collection_name, override_id) +> models::SearchOverrideDeleteResponse delete_search_override(collection_name, override_id) Delete an override associated with a collection ### Parameters @@ -25,7 +25,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) +[**models::SearchOverrideDeleteResponse**](SearchOverrideDeleteResponse.md) ### Authorization @@ -41,7 +41,7 @@ Name | Type | Description | Required | Notes ## get_search_overrides -> crate::models::SearchOverridesResponse get_search_overrides(collection_name) +> models::SearchOverridesResponse get_search_overrides(collection_name) List all collection overrides ### Parameters @@ -53,7 +53,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverridesResponse**](SearchOverridesResponse.md) +[**models::SearchOverridesResponse**](SearchOverridesResponse.md) ### Authorization @@ -69,7 +69,7 @@ Name | Type | Description | Required | Notes ## upsert_search_override -> crate::models::SearchOverride upsert_search_override(collection_name, override_id, search_override_schema) +> models::SearchOverride upsert_search_override(collection_name, override_id, search_override_schema) Create or update an override to promote certain documents over others Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. @@ -85,7 +85,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) +[**models::SearchOverride**](SearchOverride.md) ### Authorization diff --git a/typesense_codegen/docs/DebugApi.md b/typesense_codegen/docs/DebugApi.md index a1f8c0f..9acf06e 100644 --- a/typesense_codegen/docs/DebugApi.md +++ b/typesense_codegen/docs/DebugApi.md @@ -10,7 +10,7 @@ Method | HTTP request | Description ## debug -> crate::models::Debug200Response debug() +> models::Debug200Response debug() Print debugging information Print debugging information @@ -21,7 +21,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::Debug200Response**](debug_200_response.md) +[**models::Debug200Response**](debug_200_response.md) ### Authorization diff --git a/typesense_codegen/docs/DeleteDocumentsDeleteDocumentsParametersParameter.md b/typesense_codegen/docs/DeleteDocumentsDeleteDocumentsParametersParameter.md index 433c2be..ca66c4a 100644 --- a/typesense_codegen/docs/DeleteDocumentsDeleteDocumentsParametersParameter.md +++ b/typesense_codegen/docs/DeleteDocumentsDeleteDocumentsParametersParameter.md @@ -4,8 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**filter_by** | Option<**String**> | | [optional] +**filter_by** | **String** | | **batch_size** | Option<**i32**> | Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. | [optional] +**ignore_not_found** | Option<**bool**> | | [optional] +**truncate** | Option<**bool**> | When true, removes all documents from the collection while preserving the collection and its schema. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/DeleteDocumentsParameters.md b/typesense_codegen/docs/DeleteDocumentsParameters.md new file mode 100644 index 0000000..f960189 --- /dev/null +++ b/typesense_codegen/docs/DeleteDocumentsParameters.md @@ -0,0 +1,14 @@ +# DeleteDocumentsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**filter_by** | **String** | | +**batch_size** | Option<**i32**> | Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. | [optional] +**ignore_not_found** | Option<**bool**> | | [optional] +**truncate** | Option<**bool**> | When true, removes all documents from the collection while preserving the collection and its schema. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/DeleteStopwordsSet200Response.md b/typesense_codegen/docs/DeleteStopwordsSet200Response.md new file mode 100644 index 0000000..919a663 --- /dev/null +++ b/typesense_codegen/docs/DeleteStopwordsSet200Response.md @@ -0,0 +1,11 @@ +# DeleteStopwordsSet200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/DirtyValues.md b/typesense_codegen/docs/DirtyValues.md new file mode 100644 index 0000000..50492e1 --- /dev/null +++ b/typesense_codegen/docs/DirtyValues.md @@ -0,0 +1,15 @@ +# DirtyValues + +## Enum Variants + +| Name | Value | +|---- | -----| +| CoerceOrReject | coerce_or_reject | +| CoerceOrDrop | coerce_or_drop | +| Drop | drop | +| Reject | reject | + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/DocumentIndexParameters.md b/typesense_codegen/docs/DocumentIndexParameters.md new file mode 100644 index 0000000..08f8e95 --- /dev/null +++ b/typesense_codegen/docs/DocumentIndexParameters.md @@ -0,0 +1,11 @@ +# DocumentIndexParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**dirty_values** | Option<[**models::DirtyValues**](DirtyValues.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/DocumentsApi.md b/typesense_codegen/docs/DocumentsApi.md index eebec19..696c752 100644 --- a/typesense_codegen/docs/DocumentsApi.md +++ b/typesense_codegen/docs/DocumentsApi.md @@ -7,13 +7,10 @@ Method | HTTP request | Description [**delete_document**](DocumentsApi.md#delete_document) | **DELETE** /collections/{collectionName}/documents/{documentId} | Delete a document [**delete_documents**](DocumentsApi.md#delete_documents) | **DELETE** /collections/{collectionName}/documents | Delete a bunch of documents [**delete_search_override**](DocumentsApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection -[**delete_search_synonym**](DocumentsApi.md#delete_search_synonym) | **DELETE** /collections/{collectionName}/synonyms/{synonymId} | Delete a synonym associated with a collection [**export_documents**](DocumentsApi.md#export_documents) | **GET** /collections/{collectionName}/documents/export | Export all documents in a collection [**get_document**](DocumentsApi.md#get_document) | **GET** /collections/{collectionName}/documents/{documentId} | Retreive a document [**get_search_override**](DocumentsApi.md#get_search_override) | **GET** /collections/{collectionName}/overrides/{overrideId} | Retrieve a single search override [**get_search_overrides**](DocumentsApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides -[**get_search_synonym**](DocumentsApi.md#get_search_synonym) | **GET** /collections/{collectionName}/synonyms/{synonymId} | Retrieve a single search synonym -[**get_search_synonyms**](DocumentsApi.md#get_search_synonyms) | **GET** /collections/{collectionName}/synonyms | List all collection synonyms [**import_documents**](DocumentsApi.md#import_documents) | **POST** /collections/{collectionName}/documents/import | Import documents into a collection [**index_document**](DocumentsApi.md#index_document) | **POST** /collections/{collectionName}/documents | Index a document [**multi_search**](DocumentsApi.md#multi_search) | **POST** /multi_search | send multiple search requests in a single HTTP request @@ -21,7 +18,6 @@ Method | HTTP request | Description [**update_document**](DocumentsApi.md#update_document) | **PATCH** /collections/{collectionName}/documents/{documentId} | Update a document [**update_documents**](DocumentsApi.md#update_documents) | **PATCH** /collections/{collectionName}/documents | Update documents with conditional query [**upsert_search_override**](DocumentsApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others -[**upsert_search_synonym**](DocumentsApi.md#upsert_search_synonym) | **PUT** /collections/{collectionName}/synonyms/{synonymId} | Create or update a synonym @@ -58,7 +54,7 @@ Name | Type | Description | Required | Notes ## delete_documents -> crate::models::DeleteDocuments200Response delete_documents(collection_name, delete_documents_parameters) +> models::DeleteDocuments200Response delete_documents(collection_name, filter_by, batch_size, ignore_not_found, truncate) Delete a bunch of documents Delete a bunch of documents that match a specific filter condition. Use the `batch_size` parameter to control the number of documents that should deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. @@ -69,11 +65,14 @@ Delete a bunch of documents that match a specific filter condition. Use the `bat Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection to delete documents from | [required] | -**delete_documents_parameters** | Option<[**DeleteDocumentsDeleteDocumentsParametersParameter**](.md)> | | | +**filter_by** | Option<**String**> | | | +**batch_size** | Option<**i32**> | | | +**ignore_not_found** | Option<**bool**> | | | +**truncate** | Option<**bool**> | | | ### Return type -[**crate::models::DeleteDocuments200Response**](deleteDocuments_200_response.md) +[**models::DeleteDocuments200Response**](deleteDocuments_200_response.md) ### Authorization @@ -89,7 +88,7 @@ Name | Type | Description | Required | Notes ## delete_search_override -> crate::models::SearchOverride delete_search_override(collection_name, override_id) +> models::SearchOverrideDeleteResponse delete_search_override(collection_name, override_id) Delete an override associated with a collection ### Parameters @@ -102,36 +101,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) - -### Authorization - -[api_key_header](../README.md#api_key_header) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -## delete_search_synonym - -> crate::models::SearchSynonym delete_search_synonym(collection_name, synonym_id) -Delete a synonym associated with a collection - -### Parameters - - -Name | Type | Description | Required | Notes -------------- | ------------- | ------------- | ------------- | ------------- -**collection_name** | **String** | The name of the collection | [required] | -**synonym_id** | **String** | The ID of the search synonym to delete | [required] | - -### Return type - -[**crate::models::SearchSynonym**](SearchSynonym.md) +[**models::SearchOverrideDeleteResponse**](SearchOverrideDeleteResponse.md) ### Authorization @@ -147,7 +117,7 @@ Name | Type | Description | Required | Notes ## export_documents -> String export_documents(collection_name, export_documents_parameters) +> String export_documents(collection_name, filter_by, include_fields, exclude_fields) Export all documents in a collection Export all documents in a collection in JSON lines format. @@ -158,7 +128,9 @@ Export all documents in a collection in JSON lines format. Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection | [required] | -**export_documents_parameters** | Option<[**ExportDocumentsExportDocumentsParametersParameter**](.md)> | | | +**filter_by** | Option<**String**> | | | +**include_fields** | Option<**String**> | | | +**exclude_fields** | Option<**String**> | | | ### Return type @@ -209,7 +181,7 @@ Name | Type | Description | Required | Notes ## get_search_override -> crate::models::SearchOverride get_search_override(collection_name, override_id) +> models::SearchOverride get_search_override(collection_name, override_id) Retrieve a single search override Retrieve the details of a search override, given its id. @@ -224,7 +196,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) +[**models::SearchOverride**](SearchOverride.md) ### Authorization @@ -240,7 +212,7 @@ Name | Type | Description | Required | Notes ## get_search_overrides -> crate::models::SearchOverridesResponse get_search_overrides(collection_name) +> models::SearchOverridesResponse get_search_overrides(collection_name) List all collection overrides ### Parameters @@ -252,66 +224,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverridesResponse**](SearchOverridesResponse.md) - -### Authorization - -[api_key_header](../README.md#api_key_header) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -## get_search_synonym - -> crate::models::SearchSynonym get_search_synonym(collection_name, synonym_id) -Retrieve a single search synonym - -Retrieve the details of a search synonym, given its id. - -### Parameters - - -Name | Type | Description | Required | Notes -------------- | ------------- | ------------- | ------------- | ------------- -**collection_name** | **String** | The name of the collection | [required] | -**synonym_id** | **String** | The id of the search synonym | [required] | - -### Return type - -[**crate::models::SearchSynonym**](SearchSynonym.md) - -### Authorization - -[api_key_header](../README.md#api_key_header) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -## get_search_synonyms - -> crate::models::SearchSynonymsResponse get_search_synonyms(collection_name) -List all collection synonyms - -### Parameters - - -Name | Type | Description | Required | Notes -------------- | ------------- | ------------- | ------------- | ------------- -**collection_name** | **String** | The name of the collection | [required] | - -### Return type - -[**crate::models::SearchSynonymsResponse**](SearchSynonymsResponse.md) +[**models::SearchOverridesResponse**](SearchOverridesResponse.md) ### Authorization @@ -327,7 +240,7 @@ Name | Type | Description | Required | Notes ## import_documents -> String import_documents(collection_name, body, import_documents_parameters) +> String import_documents(collection_name, body, batch_size, return_id, remote_embedding_batch_size, return_doc, action, dirty_values) Import documents into a collection The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. @@ -339,7 +252,12 @@ Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection | [required] | **body** | **String** | The json array of documents or the JSONL file to import | [required] | -**import_documents_parameters** | Option<[**ImportDocumentsImportDocumentsParametersParameter**](.md)> | | | +**batch_size** | Option<**i32**> | | | +**return_id** | Option<**bool**> | | | +**remote_embedding_batch_size** | Option<**i32**> | | | +**return_doc** | Option<**bool**> | | | +**action** | Option<[**IndexAction**](.md)> | | | +**dirty_values** | Option<[**DirtyValues**](.md)> | | | ### Return type @@ -359,7 +277,7 @@ Name | Type | Description | Required | Notes ## index_document -> serde_json::Value index_document(collection_name, body, action) +> serde_json::Value index_document(collection_name, body, action, dirty_values) Index a document A document to be indexed in a given collection must conform to the schema of the collection. @@ -371,7 +289,8 @@ Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection to add the document to | [required] | **body** | **serde_json::Value** | The document object to be indexed | [required] | -**action** | Option<**String**> | Additional action to perform | | +**action** | Option<**IndexAction**> | Additional action to perform | | +**dirty_values** | Option<[**DirtyValues**](.md)> | Dealing with Dirty Data | | ### Return type @@ -391,7 +310,7 @@ Name | Type | Description | Required | Notes ## multi_search -> crate::models::MultiSearchResult multi_search(multi_search_parameters, multi_search_searches_parameter) +> models::MultiSearchResult multi_search(q, query_by, query_by_weights, text_match_type, prefix, infix, max_extra_prefix, max_extra_suffix, filter_by, sort_by, facet_by, max_facet_values, facet_query, num_typos, page, per_page, limit, offset, group_by, group_limit, group_missing_values, include_fields, exclude_fields, highlight_full_fields, highlight_affix_num_tokens, highlight_start_tag, highlight_end_tag, snippet_threshold, drop_tokens_threshold, drop_tokens_mode, typo_tokens_threshold, enable_typos_for_alpha_numerical_tokens, filter_curated_hits, enable_synonyms, synonym_prefix, synonym_num_typos, pinned_hits, hidden_hits, override_tags, highlight_fields, pre_segmented_query, preset, enable_overrides, prioritize_exact_match, prioritize_token_position, prioritize_num_matching_fields, enable_typos_for_numerical_tokens, exhaustive_search, search_cutoff_ms, use_cache, cache_ttl, min_len_1typo, min_len_2typo, vector_query, remote_embedding_timeout_ms, remote_embedding_num_tries, facet_strategy, stopwords, facet_return_parent, voice_query, conversation, conversation_model_id, conversation_id, multi_search_searches_parameter) send multiple search requests in a single HTTP request This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. @@ -401,12 +320,74 @@ This is especially useful to avoid round-trip network latencies incurred otherwi Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- -**multi_search_parameters** | [**MultiSearchParameters**](.md) | | [required] | +**q** | Option<**String**> | | | +**query_by** | Option<**String**> | | | +**query_by_weights** | Option<**String**> | | | +**text_match_type** | Option<**String**> | | | +**prefix** | Option<**String**> | | | +**infix** | Option<**String**> | | | +**max_extra_prefix** | Option<**i32**> | | | +**max_extra_suffix** | Option<**i32**> | | | +**filter_by** | Option<**String**> | | | +**sort_by** | Option<**String**> | | | +**facet_by** | Option<**String**> | | | +**max_facet_values** | Option<**i32**> | | | +**facet_query** | Option<**String**> | | | +**num_typos** | Option<**String**> | | | +**page** | Option<**i32**> | | | +**per_page** | Option<**i32**> | | | +**limit** | Option<**i32**> | | | +**offset** | Option<**i32**> | | | +**group_by** | Option<**String**> | | | +**group_limit** | Option<**i32**> | | | +**group_missing_values** | Option<**bool**> | | | +**include_fields** | Option<**String**> | | | +**exclude_fields** | Option<**String**> | | | +**highlight_full_fields** | Option<**String**> | | | +**highlight_affix_num_tokens** | Option<**i32**> | | | +**highlight_start_tag** | Option<**String**> | | | +**highlight_end_tag** | Option<**String**> | | | +**snippet_threshold** | Option<**i32**> | | | +**drop_tokens_threshold** | Option<**i32**> | | | +**drop_tokens_mode** | Option<[**DropTokensMode**](.md)> | | | +**typo_tokens_threshold** | Option<**i32**> | | | +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | | | +**filter_curated_hits** | Option<**bool**> | | | +**enable_synonyms** | Option<**bool**> | | | +**synonym_prefix** | Option<**bool**> | | | +**synonym_num_typos** | Option<**i32**> | | | +**pinned_hits** | Option<**String**> | | | +**hidden_hits** | Option<**String**> | | | +**override_tags** | Option<**String**> | | | +**highlight_fields** | Option<**String**> | | | +**pre_segmented_query** | Option<**bool**> | | |[default to false] +**preset** | Option<**String**> | | | +**enable_overrides** | Option<**bool**> | | |[default to false] +**prioritize_exact_match** | Option<**bool**> | | |[default to true] +**prioritize_token_position** | Option<**bool**> | | |[default to false] +**prioritize_num_matching_fields** | Option<**bool**> | | |[default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | | |[default to true] +**exhaustive_search** | Option<**bool**> | | | +**search_cutoff_ms** | Option<**i32**> | | | +**use_cache** | Option<**bool**> | | | +**cache_ttl** | Option<**i32**> | | | +**min_len_1typo** | Option<**i32**> | | | +**min_len_2typo** | Option<**i32**> | | | +**vector_query** | Option<**String**> | | | +**remote_embedding_timeout_ms** | Option<**i32**> | | | +**remote_embedding_num_tries** | Option<**i32**> | | | +**facet_strategy** | Option<**String**> | | | +**stopwords** | Option<**String**> | | | +**facet_return_parent** | Option<**String**> | | | +**voice_query** | Option<**String**> | | | +**conversation** | Option<**bool**> | | | +**conversation_model_id** | Option<**String**> | | | +**conversation_id** | Option<**String**> | | | **multi_search_searches_parameter** | Option<[**MultiSearchSearchesParameter**](MultiSearchSearchesParameter.md)> | | | ### Return type -[**crate::models::MultiSearchResult**](MultiSearchResult.md) +[**models::MultiSearchResult**](MultiSearchResult.md) ### Authorization @@ -422,7 +403,7 @@ Name | Type | Description | Required | Notes ## search_collection -> crate::models::SearchResult search_collection(collection_name, search_parameters) +> models::SearchResult search_collection(collection_name, q, query_by, nl_query, nl_model_id, query_by_weights, text_match_type, prefix, infix, max_extra_prefix, max_extra_suffix, filter_by, max_filter_by_candidates, sort_by, facet_by, max_facet_values, facet_query, num_typos, page, per_page, limit, offset, group_by, group_limit, group_missing_values, include_fields, exclude_fields, highlight_full_fields, highlight_affix_num_tokens, highlight_start_tag, highlight_end_tag, enable_highlight_v1, snippet_threshold, drop_tokens_threshold, drop_tokens_mode, typo_tokens_threshold, enable_typos_for_alpha_numerical_tokens, filter_curated_hits, enable_synonyms, synonym_prefix, synonym_num_typos, pinned_hits, hidden_hits, override_tags, highlight_fields, split_join_tokens, pre_segmented_query, preset, enable_overrides, prioritize_exact_match, max_candidates, prioritize_token_position, prioritize_num_matching_fields, enable_typos_for_numerical_tokens, exhaustive_search, search_cutoff_ms, use_cache, cache_ttl, min_len_1typo, min_len_2typo, vector_query, remote_embedding_timeout_ms, remote_embedding_num_tries, facet_strategy, stopwords, facet_return_parent, voice_query, conversation, conversation_model_id, conversation_id) Search for documents in a collection Search for documents in a collection that match the search criteria. @@ -433,11 +414,79 @@ Search for documents in a collection that match the search criteria. Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection to search for the document under | [required] | -**search_parameters** | [**SearchParameters**](.md) | | [required] | +**q** | Option<**String**> | | | +**query_by** | Option<**String**> | | | +**nl_query** | Option<**bool**> | | | +**nl_model_id** | Option<**String**> | | | +**query_by_weights** | Option<**String**> | | | +**text_match_type** | Option<**String**> | | | +**prefix** | Option<**String**> | | | +**infix** | Option<**String**> | | | +**max_extra_prefix** | Option<**i32**> | | | +**max_extra_suffix** | Option<**i32**> | | | +**filter_by** | Option<**String**> | | | +**max_filter_by_candidates** | Option<**i32**> | | | +**sort_by** | Option<**String**> | | | +**facet_by** | Option<**String**> | | | +**max_facet_values** | Option<**i32**> | | | +**facet_query** | Option<**String**> | | | +**num_typos** | Option<**String**> | | | +**page** | Option<**i32**> | | | +**per_page** | Option<**i32**> | | | +**limit** | Option<**i32**> | | | +**offset** | Option<**i32**> | | | +**group_by** | Option<**String**> | | | +**group_limit** | Option<**i32**> | | | +**group_missing_values** | Option<**bool**> | | | +**include_fields** | Option<**String**> | | | +**exclude_fields** | Option<**String**> | | | +**highlight_full_fields** | Option<**String**> | | | +**highlight_affix_num_tokens** | Option<**i32**> | | | +**highlight_start_tag** | Option<**String**> | | | +**highlight_end_tag** | Option<**String**> | | | +**enable_highlight_v1** | Option<**bool**> | | |[default to true] +**snippet_threshold** | Option<**i32**> | | | +**drop_tokens_threshold** | Option<**i32**> | | | +**drop_tokens_mode** | Option<[**DropTokensMode**](.md)> | | | +**typo_tokens_threshold** | Option<**i32**> | | | +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | | | +**filter_curated_hits** | Option<**bool**> | | | +**enable_synonyms** | Option<**bool**> | | | +**synonym_prefix** | Option<**bool**> | | | +**synonym_num_typos** | Option<**i32**> | | | +**pinned_hits** | Option<**String**> | | | +**hidden_hits** | Option<**String**> | | | +**override_tags** | Option<**String**> | | | +**highlight_fields** | Option<**String**> | | | +**split_join_tokens** | Option<**String**> | | | +**pre_segmented_query** | Option<**bool**> | | | +**preset** | Option<**String**> | | | +**enable_overrides** | Option<**bool**> | | |[default to false] +**prioritize_exact_match** | Option<**bool**> | | |[default to true] +**max_candidates** | Option<**i32**> | | | +**prioritize_token_position** | Option<**bool**> | | |[default to false] +**prioritize_num_matching_fields** | Option<**bool**> | | |[default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | | |[default to true] +**exhaustive_search** | Option<**bool**> | | | +**search_cutoff_ms** | Option<**i32**> | | | +**use_cache** | Option<**bool**> | | | +**cache_ttl** | Option<**i32**> | | | +**min_len_1typo** | Option<**i32**> | | | +**min_len_2typo** | Option<**i32**> | | | +**vector_query** | Option<**String**> | | | +**remote_embedding_timeout_ms** | Option<**i32**> | | | +**remote_embedding_num_tries** | Option<**i32**> | | | +**facet_strategy** | Option<**String**> | | | +**stopwords** | Option<**String**> | | | +**facet_return_parent** | Option<**String**> | | | +**voice_query** | Option<**String**> | | | +**conversation** | Option<**bool**> | | | +**conversation_model_id** | Option<**String**> | | | +**conversation_id** | Option<**String**> | | | ### Return type -[**crate::models::SearchResult**](SearchResult.md) +[**models::SearchResult**](SearchResult.md) ### Authorization @@ -453,7 +502,7 @@ Name | Type | Description | Required | Notes ## update_document -> serde_json::Value update_document(collection_name, document_id, body) +> serde_json::Value update_document(collection_name, document_id, body, dirty_values) Update a document Update an individual document from a collection by using its ID. The update can be partial. @@ -466,6 +515,7 @@ Name | Type | Description | Required | Notes **collection_name** | **String** | The name of the collection to search for the document under | [required] | **document_id** | **String** | The Document ID | [required] | **body** | **serde_json::Value** | The document object with fields to be updated | [required] | +**dirty_values** | Option<[**DirtyValues**](.md)> | Dealing with Dirty Data | | ### Return type @@ -485,7 +535,7 @@ Name | Type | Description | Required | Notes ## update_documents -> crate::models::UpdateDocuments200Response update_documents(collection_name, body, update_documents_parameters) +> models::UpdateDocuments200Response update_documents(collection_name, body, filter_by) Update documents with conditional query The filter_by query parameter is used to filter to specify a condition against which the documents are matched. The request body contains the fields that should be updated for any documents that match the filter condition. This endpoint is only available if the Typesense server is version `0.25.0.rc12` or later. @@ -497,11 +547,11 @@ Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection to update documents in | [required] | **body** | **serde_json::Value** | The document fields to be updated | [required] | -**update_documents_parameters** | Option<[**UpdateDocumentsUpdateDocumentsParametersParameter**](.md)> | | | +**filter_by** | Option<**String**> | | | ### Return type -[**crate::models::UpdateDocuments200Response**](updateDocuments_200_response.md) +[**models::UpdateDocuments200Response**](updateDocuments_200_response.md) ### Authorization @@ -517,7 +567,7 @@ Name | Type | Description | Required | Notes ## upsert_search_override -> crate::models::SearchOverride upsert_search_override(collection_name, override_id, search_override_schema) +> models::SearchOverride upsert_search_override(collection_name, override_id, search_override_schema) Create or update an override to promote certain documents over others Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. @@ -533,39 +583,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) - -### Authorization - -[api_key_header](../README.md#api_key_header) - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -## upsert_search_synonym - -> crate::models::SearchSynonym upsert_search_synonym(collection_name, synonym_id, search_synonym_schema) -Create or update a synonym - -Create or update a synonym to define search terms that should be considered equivalent. - -### Parameters - - -Name | Type | Description | Required | Notes -------------- | ------------- | ------------- | ------------- | ------------- -**collection_name** | **String** | The name of the collection | [required] | -**synonym_id** | **String** | The ID of the search synonym to create/update | [required] | -**search_synonym_schema** | [**SearchSynonymSchema**](SearchSynonymSchema.md) | The search synonym object to be created/updated | [required] | - -### Return type - -[**crate::models::SearchSynonym**](SearchSynonym.md) +[**models::SearchOverride**](SearchOverride.md) ### Authorization diff --git a/typesense_codegen/docs/DropTokensMode.md b/typesense_codegen/docs/DropTokensMode.md new file mode 100644 index 0000000..f6da263 --- /dev/null +++ b/typesense_codegen/docs/DropTokensMode.md @@ -0,0 +1,14 @@ +# DropTokensMode + +## Enum Variants + +| Name | Value | +|---- | -----| +| RightToLeft | right_to_left | +| LeftToRight | left_to_right | +| BothSidesColon3 | both_sides:3 | + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ExportDocumentsExportDocumentsParametersParameter.md b/typesense_codegen/docs/ExportDocumentsExportDocumentsParametersParameter.md index 14b7aaa..553431f 100644 --- a/typesense_codegen/docs/ExportDocumentsExportDocumentsParametersParameter.md +++ b/typesense_codegen/docs/ExportDocumentsExportDocumentsParametersParameter.md @@ -5,8 +5,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **filter_by** | Option<**String**> | Filter conditions for refining your search results. Separate multiple conditions with &&. | [optional] -**include_fields** | **String** | List of fields from the document to include in the search result | -**exclude_fields** | **String** | List of fields from the document to exclude in the search result | +**include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] +**exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/ExportDocumentsParameters.md b/typesense_codegen/docs/ExportDocumentsParameters.md new file mode 100644 index 0000000..25c7dc7 --- /dev/null +++ b/typesense_codegen/docs/ExportDocumentsParameters.md @@ -0,0 +1,13 @@ +# ExportDocumentsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**filter_by** | Option<**String**> | Filter conditions for refining your search results. Separate multiple conditions with &&. | [optional] +**include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] +**exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/FacetCounts.md b/typesense_codegen/docs/FacetCounts.md index e850701..4b170c1 100644 --- a/typesense_codegen/docs/FacetCounts.md +++ b/typesense_codegen/docs/FacetCounts.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**counts** | Option<[**Vec**](FacetCounts_counts_inner.md)> | | [optional] +**counts** | Option<[**Vec**](FacetCounts_counts_inner.md)> | | [optional] **field_name** | Option<**String**> | | [optional] -**stats** | Option<[**crate::models::FacetCountsStats**](FacetCounts_stats.md)> | | [optional] +**stats** | Option<[**models::FacetCountsStats**](FacetCounts_stats.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/FacetCountsCountsInner.md b/typesense_codegen/docs/FacetCountsCountsInner.md index 23befac..3733448 100644 --- a/typesense_codegen/docs/FacetCountsCountsInner.md +++ b/typesense_codegen/docs/FacetCountsCountsInner.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **count** | Option<**i32**> | | [optional] **highlighted** | Option<**String**> | | [optional] **value** | Option<**String**> | | [optional] +**parent** | Option<[**serde_json::Value**](.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/Field.md b/typesense_codegen/docs/Field.md index dbf6a9e..17afabd 100644 --- a/typesense_codegen/docs/Field.md +++ b/typesense_codegen/docs/Field.md @@ -12,9 +12,17 @@ Name | Type | Description | Notes **locale** | Option<**String**> | | [optional] **sort** | Option<**bool**> | | [optional] **infix** | Option<**bool**> | | [optional][default to false] +**reference** | Option<**String**> | Name of a field in another collection that should be linked to this collection so that it can be joined during query. | [optional] **num_dim** | Option<**i32**> | | [optional] **drop** | Option<**bool**> | | [optional] -**embed** | Option<[**crate::models::FieldEmbed**](Field_embed.md)> | | [optional] +**store** | Option<**bool**> | When set to false, the field value will not be stored on disk. Default: true. | [optional] +**vec_dist** | Option<**String**> | The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. | [optional] +**range_index** | Option<**bool**> | Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. | [optional] +**stem** | Option<**bool**> | Values are stemmed before indexing in-memory. Default: false. | [optional] +**stem_dictionary** | Option<**String**> | Name of the stemming dictionary to use for this field | [optional] +**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] +**symbols_to_index** | Option<**Vec**> | List of symbols or special characters to be indexed. | [optional][default to []] +**embed** | Option<[**models::FieldEmbed**](Field_embed.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/FieldEmbed.md b/typesense_codegen/docs/FieldEmbed.md index b1dc03b..dca3983 100644 --- a/typesense_codegen/docs/FieldEmbed.md +++ b/typesense_codegen/docs/FieldEmbed.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **from** | **Vec** | | -**model_config** | [**crate::models::FieldEmbedModelConfig**](Field_embed_model_config.md) | | +**model_config** | [**models::FieldEmbedModelConfig**](Field_embed_model_config.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/FieldEmbedModelConfig.md b/typesense_codegen/docs/FieldEmbedModelConfig.md index 88c03af..8ee1235 100644 --- a/typesense_codegen/docs/FieldEmbedModelConfig.md +++ b/typesense_codegen/docs/FieldEmbedModelConfig.md @@ -6,10 +6,14 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **model_name** | **String** | | **api_key** | Option<**String**> | | [optional] +**url** | Option<**String**> | | [optional] **access_token** | Option<**String**> | | [optional] +**refresh_token** | Option<**String**> | | [optional] **client_id** | Option<**String**> | | [optional] **client_secret** | Option<**String**> | | [optional] **project_id** | Option<**String**> | | [optional] +**indexing_prefix** | Option<**String**> | | [optional] +**query_prefix** | Option<**String**> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/HealthApi.md b/typesense_codegen/docs/HealthApi.md index 8c4d523..d7ed07c 100644 --- a/typesense_codegen/docs/HealthApi.md +++ b/typesense_codegen/docs/HealthApi.md @@ -10,7 +10,7 @@ Method | HTTP request | Description ## health -> crate::models::HealthStatus health() +> models::HealthStatus health() Checks if Typesense server is ready to accept requests. Checks if Typesense server is ready to accept requests. @@ -21,7 +21,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::HealthStatus**](HealthStatus.md) +[**models::HealthStatus**](HealthStatus.md) ### Authorization diff --git a/typesense_codegen/docs/ImportDocumentsImportDocumentsParametersParameter.md b/typesense_codegen/docs/ImportDocumentsImportDocumentsParametersParameter.md index aea6558..185baaa 100644 --- a/typesense_codegen/docs/ImportDocumentsImportDocumentsParametersParameter.md +++ b/typesense_codegen/docs/ImportDocumentsImportDocumentsParametersParameter.md @@ -4,10 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**action** | Option<**String**> | | [optional] **batch_size** | Option<**i32**> | | [optional] -**dirty_values** | Option<**String**> | | [optional] +**return_id** | Option<**bool**> | Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. | [optional] **remote_embedding_batch_size** | Option<**i32**> | | [optional] +**return_doc** | Option<**bool**> | | [optional] +**action** | Option<[**models::IndexAction**](IndexAction.md)> | | [optional] +**dirty_values** | Option<[**models::DirtyValues**](DirtyValues.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/ImportDocumentsParameters.md b/typesense_codegen/docs/ImportDocumentsParameters.md new file mode 100644 index 0000000..67099eb --- /dev/null +++ b/typesense_codegen/docs/ImportDocumentsParameters.md @@ -0,0 +1,16 @@ +# ImportDocumentsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**batch_size** | Option<**i32**> | | [optional] +**return_id** | Option<**bool**> | Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. | [optional] +**remote_embedding_batch_size** | Option<**i32**> | | [optional] +**return_doc** | Option<**bool**> | | [optional] +**action** | Option<[**models::IndexAction**](IndexAction.md)> | | [optional] +**dirty_values** | Option<[**models::DirtyValues**](DirtyValues.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/IndexAction.md b/typesense_codegen/docs/IndexAction.md new file mode 100644 index 0000000..7c450eb --- /dev/null +++ b/typesense_codegen/docs/IndexAction.md @@ -0,0 +1,15 @@ +# IndexAction + +## Enum Variants + +| Name | Value | +|---- | -----| +| Create | create | +| Update | update | +| Upsert | upsert | +| Emplace | emplace | + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/KeysApi.md b/typesense_codegen/docs/KeysApi.md index 422c127..e7f4bc1 100644 --- a/typesense_codegen/docs/KeysApi.md +++ b/typesense_codegen/docs/KeysApi.md @@ -13,7 +13,7 @@ Method | HTTP request | Description ## create_key -> crate::models::ApiKey create_key(api_key_schema) +> models::ApiKey create_key(api_key_schema) Create an API Key Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. @@ -27,7 +27,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::ApiKey**](ApiKey.md) +[**models::ApiKey**](ApiKey.md) ### Authorization @@ -43,7 +43,7 @@ Name | Type | Description | Required | Notes ## delete_key -> crate::models::ApiKey delete_key(key_id) +> models::ApiKeyDeleteResponse delete_key(key_id) Delete an API key given its ID. ### Parameters @@ -55,7 +55,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::ApiKey**](ApiKey.md) +[**models::ApiKeyDeleteResponse**](ApiKeyDeleteResponse.md) ### Authorization @@ -71,7 +71,7 @@ Name | Type | Description | Required | Notes ## get_key -> crate::models::ApiKey get_key(key_id) +> models::ApiKey get_key(key_id) Retrieve (metadata about) a key Retrieve (metadata about) a key. Only the key prefix is returned when you retrieve a key. Due to security reasons, only the create endpoint returns the full API key. @@ -85,7 +85,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::ApiKey**](ApiKey.md) +[**models::ApiKey**](ApiKey.md) ### Authorization @@ -101,7 +101,7 @@ Name | Type | Description | Required | Notes ## get_keys -> crate::models::ApiKeysResponse get_keys() +> models::ApiKeysResponse get_keys() Retrieve (metadata about) all keys. ### Parameters @@ -110,7 +110,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::ApiKeysResponse**](ApiKeysResponse.md) +[**models::ApiKeysResponse**](ApiKeysResponse.md) ### Authorization diff --git a/typesense_codegen/docs/ListStemmingDictionaries200Response.md b/typesense_codegen/docs/ListStemmingDictionaries200Response.md new file mode 100644 index 0000000..d56a82d --- /dev/null +++ b/typesense_codegen/docs/ListStemmingDictionaries200Response.md @@ -0,0 +1,11 @@ +# ListStemmingDictionaries200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**dictionaries** | Option<**Vec**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/MultiSearchCollectionParameters.md b/typesense_codegen/docs/MultiSearchCollectionParameters.md index 07be3ee..8a611d2 100644 --- a/typesense_codegen/docs/MultiSearchCollectionParameters.md +++ b/typesense_codegen/docs/MultiSearchCollectionParameters.md @@ -20,10 +20,11 @@ Name | Type | Description | Notes **num_typos** | Option<**String**> | The number of typographical errors (1 or 2) that would be tolerated. Default: 2 | [optional] **page** | Option<**i32**> | Results from this specific page number would be fetched. | [optional] **per_page** | Option<**i32**> | Number of results to fetch per page. Default: 10 | [optional] -**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] +**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] **offset** | Option<**i32**> | Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. | [optional] **group_by** | Option<**String**> | You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. | [optional] **group_limit** | Option<**i32**> | Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 | [optional] +**group_missing_values** | Option<**bool**> | Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true | [optional] **include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] **exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] **highlight_full_fields** | Option<**String**> | List of fields which should be highlighted fully without snippeting | [optional] @@ -32,24 +33,43 @@ Name | Type | Description | Notes **highlight_end_tag** | Option<**String**> | The end tag used for the highlighted snippets. Default: `` | [optional] **snippet_threshold** | Option<**i32**> | Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 | [optional] **drop_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 | [optional] +**drop_tokens_mode** | Option<[**models::DropTokensMode**](DropTokensMode.md)> | | [optional] **typo_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 | [optional] -**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. | [optional] +**filter_curated_hits** | Option<**bool**> | Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false | [optional] +**enable_synonyms** | Option<**bool**> | If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true | [optional] +**synonym_prefix** | Option<**bool**> | Allow synonym resolution on word prefixes in the query. Default: false | [optional] +**synonym_num_typos** | Option<**i32**> | Allow synonym resolution on typo-corrected words in the query. Default: 0 | [optional] +**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] **hidden_hits** | Option<**String**> | A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] -**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] -**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional] +**override_tags** | Option<**String**> | Comma separated list of tags to trigger the curations rules that match the tags. | [optional] +**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] +**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional][default to false] **preset** | Option<**String**> | Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. | [optional] -**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional] -**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional] -**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] -**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] +**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional][default to false] +**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional][default to true] +**prioritize_token_position** | Option<**bool**> | Make Typesense prioritize documents where the query words appear earlier in the text. | [optional][default to false] +**prioritize_num_matching_fields** | Option<**bool**> | Make Typesense prioritize documents where the query words appear in more number of fields. | [optional][default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | Make Typesense disable typos for numerical tokens. | [optional][default to true] +**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] +**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] **use_cache** | Option<**bool**> | Enable server side caching of search query results. By default, caching is disabled. | [optional] -**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] -**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] -**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] +**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] **vector_query** | Option<**String**> | Vector query expression for fetching documents \"closest\" to a given query/document vector. | [optional] **remote_embedding_timeout_ms** | Option<**i32**> | Timeout (in milliseconds) for fetching remote embeddings. | [optional] **remote_embedding_num_tries** | Option<**i32**> | Number of times to retry fetching remote embeddings. | [optional] -**collection** | **String** | The collection to search in. | +**facet_strategy** | Option<**String**> | Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). | [optional] +**stopwords** | Option<**String**> | Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. | [optional] +**facet_return_parent** | Option<**String**> | Comma separated string of nested facet fields whose parent object should be returned in facet response. | [optional] +**voice_query** | Option<**String**> | The base64 encoded audio file in 16 khz 16-bit WAV format. | [optional] +**conversation** | Option<**bool**> | Enable conversational search. | [optional] +**conversation_model_id** | Option<**String**> | The Id of Conversation Model to be used. | [optional] +**conversation_id** | Option<**String**> | The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. | [optional] +**collection** | Option<**String**> | The collection to search in. | [optional] +**x_typesense_api_key** | Option<**String**> | A separate search API key for each search within a multi_search request | [optional] +**rerank_hybrid_matches** | Option<**bool**> | When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. | [optional][default to false] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/MultiSearchParameters.md b/typesense_codegen/docs/MultiSearchParameters.md index 20a33a7..08c363b 100644 --- a/typesense_codegen/docs/MultiSearchParameters.md +++ b/typesense_codegen/docs/MultiSearchParameters.md @@ -20,10 +20,11 @@ Name | Type | Description | Notes **num_typos** | Option<**String**> | The number of typographical errors (1 or 2) that would be tolerated. Default: 2 | [optional] **page** | Option<**i32**> | Results from this specific page number would be fetched. | [optional] **per_page** | Option<**i32**> | Number of results to fetch per page. Default: 10 | [optional] -**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] +**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] **offset** | Option<**i32**> | Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. | [optional] **group_by** | Option<**String**> | You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. | [optional] **group_limit** | Option<**i32**> | Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 | [optional] +**group_missing_values** | Option<**bool**> | Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true | [optional] **include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] **exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] **highlight_full_fields** | Option<**String**> | List of fields which should be highlighted fully without snippeting | [optional] @@ -32,23 +33,40 @@ Name | Type | Description | Notes **highlight_end_tag** | Option<**String**> | The end tag used for the highlighted snippets. Default: `` | [optional] **snippet_threshold** | Option<**i32**> | Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 | [optional] **drop_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 | [optional] +**drop_tokens_mode** | Option<[**models::DropTokensMode**](DropTokensMode.md)> | | [optional] **typo_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 | [optional] -**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. | [optional] +**filter_curated_hits** | Option<**bool**> | Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false | [optional] +**enable_synonyms** | Option<**bool**> | If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true | [optional] +**synonym_prefix** | Option<**bool**> | Allow synonym resolution on word prefixes in the query. Default: false | [optional] +**synonym_num_typos** | Option<**i32**> | Allow synonym resolution on typo-corrected words in the query. Default: 0 | [optional] +**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] **hidden_hits** | Option<**String**> | A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] -**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] -**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional] +**override_tags** | Option<**String**> | Comma separated list of tags to trigger the curations rules that match the tags. | [optional] +**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] +**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional][default to false] **preset** | Option<**String**> | Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. | [optional] -**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional] -**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional] -**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] -**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] +**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional][default to false] +**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional][default to true] +**prioritize_token_position** | Option<**bool**> | Make Typesense prioritize documents where the query words appear earlier in the text. | [optional][default to false] +**prioritize_num_matching_fields** | Option<**bool**> | Make Typesense prioritize documents where the query words appear in more number of fields. | [optional][default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | Make Typesense disable typos for numerical tokens. | [optional][default to true] +**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] +**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] **use_cache** | Option<**bool**> | Enable server side caching of search query results. By default, caching is disabled. | [optional] -**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] -**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] -**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] +**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] **vector_query** | Option<**String**> | Vector query expression for fetching documents \"closest\" to a given query/document vector. | [optional] **remote_embedding_timeout_ms** | Option<**i32**> | Timeout (in milliseconds) for fetching remote embeddings. | [optional] **remote_embedding_num_tries** | Option<**i32**> | Number of times to retry fetching remote embeddings. | [optional] +**facet_strategy** | Option<**String**> | Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). | [optional] +**stopwords** | Option<**String**> | Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. | [optional] +**facet_return_parent** | Option<**String**> | Comma separated string of nested facet fields whose parent object should be returned in facet response. | [optional] +**voice_query** | Option<**String**> | The base64 encoded audio file in 16 khz 16-bit WAV format. | [optional] +**conversation** | Option<**bool**> | Enable conversational search. | [optional] +**conversation_model_id** | Option<**String**> | The Id of Conversation Model to be used. | [optional] +**conversation_id** | Option<**String**> | The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/MultiSearchResult.md b/typesense_codegen/docs/MultiSearchResult.md index d9f399c..55bad9d 100644 --- a/typesense_codegen/docs/MultiSearchResult.md +++ b/typesense_codegen/docs/MultiSearchResult.md @@ -4,7 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**results** | [**Vec**](SearchResult.md) | | +**results** | [**Vec**](MultiSearchResultItem.md) | | +**conversation** | Option<[**models::SearchResultConversation**](SearchResultConversation.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/MultiSearchResultItem.md b/typesense_codegen/docs/MultiSearchResultItem.md new file mode 100644 index 0000000..7d88f4c --- /dev/null +++ b/typesense_codegen/docs/MultiSearchResultItem.md @@ -0,0 +1,23 @@ +# MultiSearchResultItem + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**facet_counts** | Option<[**Vec**](FacetCounts.md)> | | [optional] +**found** | Option<**i32**> | The number of documents found | [optional] +**found_docs** | Option<**i32**> | | [optional] +**search_time_ms** | Option<**i32**> | The number of milliseconds the search took | [optional] +**out_of** | Option<**i32**> | The total number of documents in the collection | [optional] +**search_cutoff** | Option<**bool**> | Whether the search was cut off | [optional] +**page** | Option<**i32**> | The search result page number | [optional] +**grouped_hits** | Option<[**Vec**](SearchGroupedHit.md)> | | [optional] +**hits** | Option<[**Vec**](SearchResultHit.md)> | The documents that matched the search query | [optional] +**request_params** | Option<[**models::SearchResultRequestParams**](SearchResult_request_params.md)> | | [optional] +**conversation** | Option<[**models::SearchResultConversation**](SearchResultConversation.md)> | | [optional] +**code** | Option<**i64**> | HTTP error code | [optional] +**error** | Option<**String**> | Error description | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/MultiSearchSearchesParameter.md b/typesense_codegen/docs/MultiSearchSearchesParameter.md index aee8e7f..0b71465 100644 --- a/typesense_codegen/docs/MultiSearchSearchesParameter.md +++ b/typesense_codegen/docs/MultiSearchSearchesParameter.md @@ -4,7 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**searches** | [**Vec**](MultiSearchCollectionParameters.md) | | +**union** | Option<**bool**> | When true, merges the search results from each search query into a single ordered set of hits. | [optional] +**searches** | [**Vec**](MultiSearchCollectionParameters.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/NlSearchModelBase.md b/typesense_codegen/docs/NlSearchModelBase.md new file mode 100644 index 0000000..b331895 --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelBase.md @@ -0,0 +1,28 @@ +# NlSearchModelBase + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**model_name** | Option<**String**> | Name of the NL model to use | [optional] +**api_key** | Option<**String**> | API key for the NL model service | [optional] +**api_url** | Option<**String**> | Custom API URL for the NL model service | [optional] +**max_bytes** | Option<**i32**> | Maximum number of bytes to process | [optional] +**temperature** | Option<**f64**> | Temperature parameter for the NL model | [optional] +**system_prompt** | Option<**String**> | System prompt for the NL model | [optional] +**top_p** | Option<**f64**> | Top-p parameter for the NL model (Google-specific) | [optional] +**top_k** | Option<**i32**> | Top-k parameter for the NL model (Google-specific) | [optional] +**stop_sequences** | Option<**Vec**> | Stop sequences for the NL model (Google-specific) | [optional] +**api_version** | Option<**String**> | API version for the NL model service | [optional] +**project_id** | Option<**String**> | Project ID for GCP Vertex AI | [optional] +**access_token** | Option<**String**> | Access token for GCP Vertex AI | [optional] +**refresh_token** | Option<**String**> | Refresh token for GCP Vertex AI | [optional] +**client_id** | Option<**String**> | Client ID for GCP Vertex AI | [optional] +**client_secret** | Option<**String**> | Client secret for GCP Vertex AI | [optional] +**region** | Option<**String**> | Region for GCP Vertex AI | [optional] +**max_output_tokens** | Option<**i32**> | Maximum output tokens for GCP Vertex AI | [optional] +**account_id** | Option<**String**> | Account ID for Cloudflare-specific models | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/NlSearchModelCreateSchema.md b/typesense_codegen/docs/NlSearchModelCreateSchema.md new file mode 100644 index 0000000..6690186 --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelCreateSchema.md @@ -0,0 +1,29 @@ +# NlSearchModelCreateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**model_name** | Option<**String**> | Name of the NL model to use | [optional] +**api_key** | Option<**String**> | API key for the NL model service | [optional] +**api_url** | Option<**String**> | Custom API URL for the NL model service | [optional] +**max_bytes** | Option<**i32**> | Maximum number of bytes to process | [optional] +**temperature** | Option<**f64**> | Temperature parameter for the NL model | [optional] +**system_prompt** | Option<**String**> | System prompt for the NL model | [optional] +**top_p** | Option<**f64**> | Top-p parameter for the NL model (Google-specific) | [optional] +**top_k** | Option<**i32**> | Top-k parameter for the NL model (Google-specific) | [optional] +**stop_sequences** | Option<**Vec**> | Stop sequences for the NL model (Google-specific) | [optional] +**api_version** | Option<**String**> | API version for the NL model service | [optional] +**project_id** | Option<**String**> | Project ID for GCP Vertex AI | [optional] +**access_token** | Option<**String**> | Access token for GCP Vertex AI | [optional] +**refresh_token** | Option<**String**> | Refresh token for GCP Vertex AI | [optional] +**client_id** | Option<**String**> | Client ID for GCP Vertex AI | [optional] +**client_secret** | Option<**String**> | Client secret for GCP Vertex AI | [optional] +**region** | Option<**String**> | Region for GCP Vertex AI | [optional] +**max_output_tokens** | Option<**i32**> | Maximum output tokens for GCP Vertex AI | [optional] +**account_id** | Option<**String**> | Account ID for Cloudflare-specific models | [optional] +**id** | Option<**String**> | Optional ID for the NL search model | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/NlSearchModelDeleteSchema.md b/typesense_codegen/docs/NlSearchModelDeleteSchema.md new file mode 100644 index 0000000..97be1ac --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelDeleteSchema.md @@ -0,0 +1,11 @@ +# NlSearchModelDeleteSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | ID of the deleted NL search model | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/NlSearchModelSchema.md b/typesense_codegen/docs/NlSearchModelSchema.md new file mode 100644 index 0000000..24f870f --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelSchema.md @@ -0,0 +1,29 @@ +# NlSearchModelSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**model_name** | Option<**String**> | Name of the NL model to use | [optional] +**api_key** | Option<**String**> | API key for the NL model service | [optional] +**api_url** | Option<**String**> | Custom API URL for the NL model service | [optional] +**max_bytes** | Option<**i32**> | Maximum number of bytes to process | [optional] +**temperature** | Option<**f64**> | Temperature parameter for the NL model | [optional] +**system_prompt** | Option<**String**> | System prompt for the NL model | [optional] +**top_p** | Option<**f64**> | Top-p parameter for the NL model (Google-specific) | [optional] +**top_k** | Option<**i32**> | Top-k parameter for the NL model (Google-specific) | [optional] +**stop_sequences** | Option<**Vec**> | Stop sequences for the NL model (Google-specific) | [optional] +**api_version** | Option<**String**> | API version for the NL model service | [optional] +**project_id** | Option<**String**> | Project ID for GCP Vertex AI | [optional] +**access_token** | Option<**String**> | Access token for GCP Vertex AI | [optional] +**refresh_token** | Option<**String**> | Refresh token for GCP Vertex AI | [optional] +**client_id** | Option<**String**> | Client ID for GCP Vertex AI | [optional] +**client_secret** | Option<**String**> | Client secret for GCP Vertex AI | [optional] +**region** | Option<**String**> | Region for GCP Vertex AI | [optional] +**max_output_tokens** | Option<**i32**> | Maximum output tokens for GCP Vertex AI | [optional] +**account_id** | Option<**String**> | Account ID for Cloudflare-specific models | [optional] +**id** | **String** | ID of the NL search model | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/NlSearchModelsApi.md b/typesense_codegen/docs/NlSearchModelsApi.md new file mode 100644 index 0000000..5608643 --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelsApi.md @@ -0,0 +1,161 @@ +# \NlSearchModelsApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_nl_search_model**](NlSearchModelsApi.md#create_nl_search_model) | **POST** /nl_search_models | Create a NL search model +[**delete_nl_search_model**](NlSearchModelsApi.md#delete_nl_search_model) | **DELETE** /nl_search_models/{modelId} | Delete a NL search model +[**retrieve_all_nl_search_models**](NlSearchModelsApi.md#retrieve_all_nl_search_models) | **GET** /nl_search_models | List all NL search models +[**retrieve_nl_search_model**](NlSearchModelsApi.md#retrieve_nl_search_model) | **GET** /nl_search_models/{modelId} | Retrieve a NL search model +[**update_nl_search_model**](NlSearchModelsApi.md#update_nl_search_model) | **PUT** /nl_search_models/{modelId} | Update a NL search model + + + +## create_nl_search_model + +> models::NlSearchModelSchema create_nl_search_model(nl_search_model_create_schema) +Create a NL search model + +Create a new NL search model. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**nl_search_model_create_schema** | [**NlSearchModelCreateSchema**](NlSearchModelCreateSchema.md) | The NL search model to be created | [required] | + +### Return type + +[**models::NlSearchModelSchema**](NLSearchModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## delete_nl_search_model + +> models::NlSearchModelDeleteSchema delete_nl_search_model(model_id) +Delete a NL search model + +Delete a specific NL search model by its ID. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The ID of the NL search model to delete | [required] | + +### Return type + +[**models::NlSearchModelDeleteSchema**](NLSearchModelDeleteSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_all_nl_search_models + +> Vec retrieve_all_nl_search_models() +List all NL search models + +Retrieve all NL search models. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**Vec**](NLSearchModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_nl_search_model + +> models::NlSearchModelSchema retrieve_nl_search_model(model_id) +Retrieve a NL search model + +Retrieve a specific NL search model by its ID. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The ID of the NL search model to retrieve | [required] | + +### Return type + +[**models::NlSearchModelSchema**](NLSearchModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## update_nl_search_model + +> models::NlSearchModelSchema update_nl_search_model(model_id, body) +Update a NL search model + +Update an existing NL search model. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The ID of the NL search model to update | [required] | +**body** | **models::NlSearchModelCreateSchema** | The NL search model fields to update | [required] | + +### Return type + +[**models::NlSearchModelSchema**](NLSearchModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/OperationsApi.md b/typesense_codegen/docs/OperationsApi.md index 9a499de..c8684fa 100644 --- a/typesense_codegen/docs/OperationsApi.md +++ b/typesense_codegen/docs/OperationsApi.md @@ -4,14 +4,98 @@ All URIs are relative to *http://localhost* Method | HTTP request | Description ------------- | ------------- | ------------- +[**get_schema_changes**](OperationsApi.md#get_schema_changes) | **GET** /operations/schema_changes | Get the status of in-progress schema change operations +[**retrieve_api_stats**](OperationsApi.md#retrieve_api_stats) | **GET** /stats.json | Get stats about API endpoints. +[**retrieve_metrics**](OperationsApi.md#retrieve_metrics) | **GET** /metrics.json | Get current RAM, CPU, Disk & Network usage metrics. [**take_snapshot**](OperationsApi.md#take_snapshot) | **POST** /operations/snapshot | Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. [**vote**](OperationsApi.md#vote) | **POST** /operations/vote | Triggers a follower node to initiate the raft voting process, which triggers leader re-election. +## get_schema_changes + +> Vec get_schema_changes() +Get the status of in-progress schema change operations + +Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**Vec**](SchemaChangeStatus.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_api_stats + +> models::ApiStatsResponse retrieve_api_stats() +Get stats about API endpoints. + +Retrieve the stats about API endpoints. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::ApiStatsResponse**](APIStatsResponse.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_metrics + +> serde_json::Value retrieve_metrics() +Get current RAM, CPU, Disk & Network usage metrics. + +Retrieve the metrics. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**serde_json::Value**](serde_json::Value.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + ## take_snapshot -> crate::models::SuccessStatus take_snapshot(snapshot_path) +> models::SuccessStatus take_snapshot(snapshot_path) Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. @@ -25,7 +109,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SuccessStatus**](SuccessStatus.md) +[**models::SuccessStatus**](SuccessStatus.md) ### Authorization @@ -41,7 +125,7 @@ Name | Type | Description | Required | Notes ## vote -> crate::models::SuccessStatus vote() +> models::SuccessStatus vote() Triggers a follower node to initiate the raft voting process, which triggers leader re-election. Triggers a follower node to initiate the raft voting process, which triggers leader re-election. The follower node that you run this operation against will become the new leader, once this command succeeds. @@ -52,7 +136,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::SuccessStatus**](SuccessStatus.md) +[**models::SuccessStatus**](SuccessStatus.md) ### Authorization diff --git a/typesense_codegen/docs/OverrideApi.md b/typesense_codegen/docs/OverrideApi.md index 02f1ca5..0cd9129 100644 --- a/typesense_codegen/docs/OverrideApi.md +++ b/typesense_codegen/docs/OverrideApi.md @@ -10,7 +10,7 @@ Method | HTTP request | Description ## get_search_override -> crate::models::SearchOverride get_search_override(collection_name, override_id) +> models::SearchOverride get_search_override(collection_name, override_id) Retrieve a single search override Retrieve the details of a search override, given its id. @@ -25,7 +25,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) +[**models::SearchOverride**](SearchOverride.md) ### Authorization diff --git a/typesense_codegen/docs/PresetDeleteSchema.md b/typesense_codegen/docs/PresetDeleteSchema.md new file mode 100644 index 0000000..36bbacf --- /dev/null +++ b/typesense_codegen/docs/PresetDeleteSchema.md @@ -0,0 +1,11 @@ +# PresetDeleteSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PresetSchema.md b/typesense_codegen/docs/PresetSchema.md new file mode 100644 index 0000000..e1457b9 --- /dev/null +++ b/typesense_codegen/docs/PresetSchema.md @@ -0,0 +1,12 @@ +# PresetSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**value** | [**models::PresetUpsertSchemaValue**](PresetUpsertSchema_value.md) | | +**name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PresetUpsertSchema.md b/typesense_codegen/docs/PresetUpsertSchema.md new file mode 100644 index 0000000..ac9f9cd --- /dev/null +++ b/typesense_codegen/docs/PresetUpsertSchema.md @@ -0,0 +1,11 @@ +# PresetUpsertSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**value** | [**models::PresetUpsertSchemaValue**](PresetUpsertSchema_value.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PresetUpsertSchemaValue.md b/typesense_codegen/docs/PresetUpsertSchemaValue.md new file mode 100644 index 0000000..073a07c --- /dev/null +++ b/typesense_codegen/docs/PresetUpsertSchemaValue.md @@ -0,0 +1,12 @@ +# PresetUpsertSchemaValue + +## Enum Variants + +| Name | Description | +|---- | -----| +| MultiSearchSearchesParameter | | +| SearchParameters | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PresetsApi.md b/typesense_codegen/docs/PresetsApi.md new file mode 100644 index 0000000..52b9f60 --- /dev/null +++ b/typesense_codegen/docs/PresetsApi.md @@ -0,0 +1,130 @@ +# \PresetsApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_preset**](PresetsApi.md#delete_preset) | **DELETE** /presets/{presetId} | Delete a preset. +[**retrieve_all_presets**](PresetsApi.md#retrieve_all_presets) | **GET** /presets | Retrieves all presets. +[**retrieve_preset**](PresetsApi.md#retrieve_preset) | **GET** /presets/{presetId} | Retrieves a preset. +[**upsert_preset**](PresetsApi.md#upsert_preset) | **PUT** /presets/{presetId} | Upserts a preset. + + + +## delete_preset + +> models::PresetDeleteSchema delete_preset(preset_id) +Delete a preset. + +Permanently deletes a preset, given it's name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**preset_id** | **String** | The ID of the preset to delete. | [required] | + +### Return type + +[**models::PresetDeleteSchema**](PresetDeleteSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_all_presets + +> models::PresetsRetrieveSchema retrieve_all_presets() +Retrieves all presets. + +Retrieve the details of all presets + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::PresetsRetrieveSchema**](PresetsRetrieveSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_preset + +> models::PresetSchema retrieve_preset(preset_id) +Retrieves a preset. + +Retrieve the details of a preset, given it's name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**preset_id** | **String** | The ID of the preset to retrieve. | [required] | + +### Return type + +[**models::PresetSchema**](PresetSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## upsert_preset + +> models::PresetSchema upsert_preset(preset_id, preset_upsert_schema) +Upserts a preset. + +Create or update an existing preset. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**preset_id** | **String** | The name of the preset set to upsert. | [required] | +**preset_upsert_schema** | [**PresetUpsertSchema**](PresetUpsertSchema.md) | The stopwords set to upsert. | [required] | + +### Return type + +[**models::PresetSchema**](PresetSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/PresetsRetrieveSchema.md b/typesense_codegen/docs/PresetsRetrieveSchema.md new file mode 100644 index 0000000..6c2ace3 --- /dev/null +++ b/typesense_codegen/docs/PresetsRetrieveSchema.md @@ -0,0 +1,11 @@ +# PresetsRetrieveSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**presets** | [**Vec**](PresetSchema.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SchemaChangeStatus.md b/typesense_codegen/docs/SchemaChangeStatus.md new file mode 100644 index 0000000..5a87798 --- /dev/null +++ b/typesense_codegen/docs/SchemaChangeStatus.md @@ -0,0 +1,13 @@ +# SchemaChangeStatus + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**collection** | Option<**String**> | Name of the collection being modified | [optional] +**validated_docs** | Option<**i32**> | Number of documents that have been validated | [optional] +**altered_docs** | Option<**i32**> | Number of documents that have been altered | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchGroupedHit.md b/typesense_codegen/docs/SearchGroupedHit.md index 996a423..1972f65 100644 --- a/typesense_codegen/docs/SearchGroupedHit.md +++ b/typesense_codegen/docs/SearchGroupedHit.md @@ -6,7 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **found** | Option<**i32**> | | [optional] **group_key** | [**Vec**](serde_json::Value.md) | | -**hits** | [**Vec**](SearchResultHit.md) | The documents that matched the search query | +**hits** | [**Vec**](SearchResultHit.md) | The documents that matched the search query | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchOverride.md b/typesense_codegen/docs/SearchOverride.md index 0c0cbfc..1204992 100644 --- a/typesense_codegen/docs/SearchOverride.md +++ b/typesense_codegen/docs/SearchOverride.md @@ -4,11 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**rule** | [**crate::models::SearchOverrideRule**](SearchOverrideRule.md) | | -**includes** | Option<[**Vec**](SearchOverrideInclude.md)> | List of document `id`s that should be included in the search results with their corresponding `position`s. | [optional] -**excludes** | Option<[**Vec**](SearchOverrideExclude.md)> | List of document `id`s that should be excluded from the search results. | [optional] +**rule** | [**models::SearchOverrideRule**](SearchOverrideRule.md) | | +**includes** | Option<[**Vec**](SearchOverrideInclude.md)> | List of document `id`s that should be included in the search results with their corresponding `position`s. | [optional] +**excludes** | Option<[**Vec**](SearchOverrideExclude.md)> | List of document `id`s that should be excluded from the search results. | [optional] **filter_by** | Option<**String**> | A filter by clause that is applied to any search query that matches the override rule. | [optional] **remove_matched_tokens** | Option<**bool**> | Indicates whether search query tokens that exist in the override's rule should be removed from the search query. | [optional] +**metadata** | Option<[**serde_json::Value**](.md)> | Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. | [optional] +**sort_by** | Option<**String**> | A sort by clause that is applied to any search query that matches the override rule. | [optional] +**replace_query** | Option<**String**> | Replaces the current search query with this value, when the search query matches the override rule. | [optional] +**filter_curated_hits** | Option<**bool**> | When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. | [optional] +**effective_from_ts** | Option<**i32**> | A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. | [optional] +**effective_to_ts** | Option<**i32**> | A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. | [optional] +**stop_processing** | Option<**bool**> | When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. | [optional] **id** | **String** | | [readonly] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchOverrideDeleteResponse.md b/typesense_codegen/docs/SearchOverrideDeleteResponse.md new file mode 100644 index 0000000..3392bd0 --- /dev/null +++ b/typesense_codegen/docs/SearchOverrideDeleteResponse.md @@ -0,0 +1,11 @@ +# SearchOverrideDeleteResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | The id of the override that was deleted | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchOverrideRule.md b/typesense_codegen/docs/SearchOverrideRule.md index f4ac180..2234944 100644 --- a/typesense_codegen/docs/SearchOverrideRule.md +++ b/typesense_codegen/docs/SearchOverrideRule.md @@ -4,8 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**query** | **String** | Indicates what search queries should be overridden | -**r#match** | **String** | Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. | +**tags** | Option<**Vec**> | List of tag values to associate with this override rule. | [optional] +**query** | Option<**String**> | Indicates what search queries should be overridden | [optional] +**r#match** | Option<**String**> | Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. | [optional] +**filter_by** | Option<**String**> | Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchOverrideSchema.md b/typesense_codegen/docs/SearchOverrideSchema.md index 6aaad22..4da9648 100644 --- a/typesense_codegen/docs/SearchOverrideSchema.md +++ b/typesense_codegen/docs/SearchOverrideSchema.md @@ -4,11 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**rule** | [**crate::models::SearchOverrideRule**](SearchOverrideRule.md) | | -**includes** | Option<[**Vec**](SearchOverrideInclude.md)> | List of document `id`s that should be included in the search results with their corresponding `position`s. | [optional] -**excludes** | Option<[**Vec**](SearchOverrideExclude.md)> | List of document `id`s that should be excluded from the search results. | [optional] +**rule** | [**models::SearchOverrideRule**](SearchOverrideRule.md) | | +**includes** | Option<[**Vec**](SearchOverrideInclude.md)> | List of document `id`s that should be included in the search results with their corresponding `position`s. | [optional] +**excludes** | Option<[**Vec**](SearchOverrideExclude.md)> | List of document `id`s that should be excluded from the search results. | [optional] **filter_by** | Option<**String**> | A filter by clause that is applied to any search query that matches the override rule. | [optional] **remove_matched_tokens** | Option<**bool**> | Indicates whether search query tokens that exist in the override's rule should be removed from the search query. | [optional] +**metadata** | Option<[**serde_json::Value**](.md)> | Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. | [optional] +**sort_by** | Option<**String**> | A sort by clause that is applied to any search query that matches the override rule. | [optional] +**replace_query** | Option<**String**> | Replaces the current search query with this value, when the search query matches the override rule. | [optional] +**filter_curated_hits** | Option<**bool**> | When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. | [optional] +**effective_from_ts** | Option<**i32**> | A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. | [optional] +**effective_to_ts** | Option<**i32**> | A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. | [optional] +**stop_processing** | Option<**bool**> | When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchOverridesResponse.md b/typesense_codegen/docs/SearchOverridesResponse.md index 422e1b3..4c3952b 100644 --- a/typesense_codegen/docs/SearchOverridesResponse.md +++ b/typesense_codegen/docs/SearchOverridesResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**overrides** | [**Vec**](SearchOverride.md) | | +**overrides** | [**Vec**](SearchOverride.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchParameters.md b/typesense_codegen/docs/SearchParameters.md index 740eb30..578cd4e 100644 --- a/typesense_codegen/docs/SearchParameters.md +++ b/typesense_codegen/docs/SearchParameters.md @@ -4,8 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**q** | **String** | The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. | -**query_by** | **String** | A list of `string` fields that should be queried against. Multiple fields are separated with a comma. | +**q** | Option<**String**> | The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. | [optional] +**query_by** | Option<**String**> | A list of `string` fields that should be queried against. Multiple fields are separated with a comma. | [optional] +**nl_query** | Option<**bool**> | Whether to use natural language processing to parse the query. | [optional] +**nl_model_id** | Option<**String**> | The ID of the natural language model to use. | [optional] **query_by_weights** | Option<**String**> | The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. | [optional] **text_match_type** | Option<**String**> | In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. | [optional] **prefix** | Option<**String**> | Boolean field to indicate that the last word in the query should be treated as a prefix, and not as a whole word. This is used for building autocomplete and instant search interfaces. Defaults to true. | [optional] @@ -13,6 +15,7 @@ Name | Type | Description | Notes **max_extra_prefix** | Option<**i32**> | There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query \"K2100\" has 2 extra symbols in \"6PK2100\". By default, any number of prefixes/suffixes can be present for a match. | [optional] **max_extra_suffix** | Option<**i32**> | There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query \"K2100\" has 2 extra symbols in \"6PK2100\". By default, any number of prefixes/suffixes can be present for a match. | [optional] **filter_by** | Option<**String**> | Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. | [optional] +**max_filter_by_candidates** | Option<**i32**> | Controls the number of similar words that Typesense considers during fuzzy search on filter_by values. Useful for controlling prefix matches like company_name:Acm*. | [optional] **sort_by** | Option<**String**> | A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` | [optional] **facet_by** | Option<**String**> | A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. | [optional] **max_facet_values** | Option<**i32**> | Maximum number of facet values to be returned. | [optional] @@ -20,10 +23,11 @@ Name | Type | Description | Notes **num_typos** | Option<**String**> | The number of typographical errors (1 or 2) that would be tolerated. Default: 2 | [optional] **page** | Option<**i32**> | Results from this specific page number would be fetched. | [optional] **per_page** | Option<**i32**> | Number of results to fetch per page. Default: 10 | [optional] -**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] +**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] **offset** | Option<**i32**> | Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. | [optional] **group_by** | Option<**String**> | You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. | [optional] **group_limit** | Option<**i32**> | Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 | [optional] +**group_missing_values** | Option<**bool**> | Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true | [optional] **include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] **exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] **highlight_full_fields** | Option<**String**> | List of fields which should be highlighted fully without snippeting | [optional] @@ -33,26 +37,42 @@ Name | Type | Description | Notes **enable_highlight_v1** | Option<**bool**> | Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true | [optional][default to true] **snippet_threshold** | Option<**i32**> | Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 | [optional] **drop_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 | [optional] +**drop_tokens_mode** | Option<[**models::DropTokensMode**](DropTokensMode.md)> | | [optional] **typo_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 | [optional] -**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. | [optional] +**filter_curated_hits** | Option<**bool**> | Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false | [optional] +**enable_synonyms** | Option<**bool**> | If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true | [optional] +**synonym_prefix** | Option<**bool**> | Allow synonym resolution on word prefixes in the query. Default: false | [optional] +**synonym_num_typos** | Option<**i32**> | Allow synonym resolution on typo-corrected words in the query. Default: 0 | [optional] +**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] **hidden_hits** | Option<**String**> | A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] -**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] +**override_tags** | Option<**String**> | Comma separated list of tags to trigger the curations rules that match the tags. | [optional] +**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] **split_join_tokens** | Option<**String**> | Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. | [optional] -**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional] +**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional] **preset** | Option<**String**> | Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. | [optional] -**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional] -**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional] +**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional][default to false] +**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional][default to true] **max_candidates** | Option<**i32**> | Control the number of words that Typesense considers for typo and prefix searching. | [optional] -**prioritize_token_position** | Option<**bool**> | Make Typesense prioritize documents where the query words appear earlier in the text. | [optional] -**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] -**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] +**prioritize_token_position** | Option<**bool**> | Make Typesense prioritize documents where the query words appear earlier in the text. | [optional][default to false] +**prioritize_num_matching_fields** | Option<**bool**> | Make Typesense prioritize documents where the query words appear in more number of fields. | [optional][default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | Make Typesense disable typos for numerical tokens. | [optional][default to true] +**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] +**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] **use_cache** | Option<**bool**> | Enable server side caching of search query results. By default, caching is disabled. | [optional] -**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] -**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] -**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] +**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] **vector_query** | Option<**String**> | Vector query expression for fetching documents \"closest\" to a given query/document vector. | [optional] **remote_embedding_timeout_ms** | Option<**i32**> | Timeout (in milliseconds) for fetching remote embeddings. | [optional] **remote_embedding_num_tries** | Option<**i32**> | Number of times to retry fetching remote embeddings. | [optional] +**facet_strategy** | Option<**String**> | Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). | [optional] +**stopwords** | Option<**String**> | Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. | [optional] +**facet_return_parent** | Option<**String**> | Comma separated string of nested facet fields whose parent object should be returned in facet response. | [optional] +**voice_query** | Option<**String**> | The base64 encoded audio file in 16 khz 16-bit WAV format. | [optional] +**conversation** | Option<**bool**> | Enable conversational search. | [optional] +**conversation_model_id** | Option<**String**> | The Id of Conversation Model to be used. | [optional] +**conversation_id** | Option<**String**> | The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchResult.md b/typesense_codegen/docs/SearchResult.md index 857f5ea..2739d28 100644 --- a/typesense_codegen/docs/SearchResult.md +++ b/typesense_codegen/docs/SearchResult.md @@ -4,15 +4,17 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**facet_counts** | Option<[**Vec**](FacetCounts.md)> | | [optional] +**facet_counts** | Option<[**Vec**](FacetCounts.md)> | | [optional] **found** | Option<**i32**> | The number of documents found | [optional] +**found_docs** | Option<**i32**> | | [optional] **search_time_ms** | Option<**i32**> | The number of milliseconds the search took | [optional] **out_of** | Option<**i32**> | The total number of documents in the collection | [optional] **search_cutoff** | Option<**bool**> | Whether the search was cut off | [optional] **page** | Option<**i32**> | The search result page number | [optional] -**grouped_hits** | Option<[**Vec**](SearchGroupedHit.md)> | | [optional] -**hits** | Option<[**Vec**](SearchResultHit.md)> | The documents that matched the search query | [optional] -**request_params** | Option<[**crate::models::SearchResultRequestParams**](SearchResult_request_params.md)> | | [optional] +**grouped_hits** | Option<[**Vec**](SearchGroupedHit.md)> | | [optional] +**hits** | Option<[**Vec**](SearchResultHit.md)> | The documents that matched the search query | [optional] +**request_params** | Option<[**models::SearchResultRequestParams**](SearchResult_request_params.md)> | | [optional] +**conversation** | Option<[**models::SearchResultConversation**](SearchResultConversation.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchResultConversation.md b/typesense_codegen/docs/SearchResultConversation.md new file mode 100644 index 0000000..2428ba7 --- /dev/null +++ b/typesense_codegen/docs/SearchResultConversation.md @@ -0,0 +1,14 @@ +# SearchResultConversation + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**answer** | **String** | | +**conversation_history** | [**Vec**](serde_json::Value.md) | | +**conversation_id** | **String** | | +**query** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchResultHit.md b/typesense_codegen/docs/SearchResultHit.md index 3b9d460..df343b1 100644 --- a/typesense_codegen/docs/SearchResultHit.md +++ b/typesense_codegen/docs/SearchResultHit.md @@ -4,11 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**highlights** | Option<[**Vec**](SearchHighlight.md)> | (Deprecated) Contains highlighted portions of the search fields | [optional] -**highlight** | Option<[**::std::collections::HashMap**](serde_json::Value.md)> | Highlighted version of the matching document | [optional] -**document** | Option<[**::std::collections::HashMap**](serde_json::Value.md)> | Can be any key-value pair | [optional] +**highlights** | Option<[**Vec**](SearchHighlight.md)> | (Deprecated) Contains highlighted portions of the search fields | [optional] +**highlight** | Option<[**std::collections::HashMap**](serde_json::Value.md)> | Highlighted version of the matching document | [optional] +**document** | Option<[**serde_json::Value**](.md)> | Can be any key-value pair | [optional] **text_match** | Option<**i64**> | | [optional] -**geo_distance_meters** | Option<**::std::collections::HashMap**> | Can be any key-value pair | [optional] +**text_match_info** | Option<[**models::SearchResultHitTextMatchInfo**](SearchResultHit_text_match_info.md)> | | [optional] +**geo_distance_meters** | Option<**std::collections::HashMap**> | Can be any key-value pair | [optional] **vector_distance** | Option<**f32**> | Distance between the query vector and matching document's vector value | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchResultHitTextMatchInfo.md b/typesense_codegen/docs/SearchResultHitTextMatchInfo.md new file mode 100644 index 0000000..21faffa --- /dev/null +++ b/typesense_codegen/docs/SearchResultHitTextMatchInfo.md @@ -0,0 +1,17 @@ +# SearchResultHitTextMatchInfo + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**best_field_score** | Option<**String**> | | [optional] +**best_field_weight** | Option<**i32**> | | [optional] +**fields_matched** | Option<**i32**> | | [optional] +**num_tokens_dropped** | Option<**i64**> | | [optional] +**score** | Option<**String**> | | [optional] +**tokens_matched** | Option<**i32**> | | [optional] +**typo_prefix_score** | Option<**i32**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchResultRequestParams.md b/typesense_codegen/docs/SearchResultRequestParams.md index 2ba855f..9eeb27e 100644 --- a/typesense_codegen/docs/SearchResultRequestParams.md +++ b/typesense_codegen/docs/SearchResultRequestParams.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **collection_name** | **String** | | **q** | **String** | | **per_page** | **i32** | | +**voice_query** | Option<[**models::SearchResultRequestParamsVoiceQuery**](SearchResult_request_params_voice_query.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchResultRequestParamsVoiceQuery.md b/typesense_codegen/docs/SearchResultRequestParamsVoiceQuery.md new file mode 100644 index 0000000..e7293e7 --- /dev/null +++ b/typesense_codegen/docs/SearchResultRequestParamsVoiceQuery.md @@ -0,0 +1,11 @@ +# SearchResultRequestParamsVoiceQuery + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**transcribed_query** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchSynonym.md b/typesense_codegen/docs/SearchSynonym.md index 4061c2b..70c9964 100644 --- a/typesense_codegen/docs/SearchSynonym.md +++ b/typesense_codegen/docs/SearchSynonym.md @@ -6,6 +6,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **root** | Option<**String**> | For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. | [optional] **synonyms** | **Vec** | Array of words that should be considered as synonyms. | +**locale** | Option<**String**> | Locale for the synonym, leave blank to use the standard tokenizer. | [optional] +**symbols_to_index** | Option<**Vec**> | By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. | [optional] **id** | **String** | | [readonly] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchSynonymDeleteResponse.md b/typesense_codegen/docs/SearchSynonymDeleteResponse.md new file mode 100644 index 0000000..76ab57c --- /dev/null +++ b/typesense_codegen/docs/SearchSynonymDeleteResponse.md @@ -0,0 +1,11 @@ +# SearchSynonymDeleteResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | The id of the synonym that was deleted | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchSynonymSchema.md b/typesense_codegen/docs/SearchSynonymSchema.md index bcb5956..bac8165 100644 --- a/typesense_codegen/docs/SearchSynonymSchema.md +++ b/typesense_codegen/docs/SearchSynonymSchema.md @@ -6,6 +6,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **root** | Option<**String**> | For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. | [optional] **synonyms** | **Vec** | Array of words that should be considered as synonyms. | +**locale** | Option<**String**> | Locale for the synonym, leave blank to use the standard tokenizer. | [optional] +**symbols_to_index** | Option<**Vec**> | By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchSynonymsResponse.md b/typesense_codegen/docs/SearchSynonymsResponse.md index f88f04c..6b946ee 100644 --- a/typesense_codegen/docs/SearchSynonymsResponse.md +++ b/typesense_codegen/docs/SearchSynonymsResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**synonyms** | [**Vec**](SearchSynonym.md) | | +**synonyms** | [**Vec**](SearchSynonym.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/StemmingApi.md b/typesense_codegen/docs/StemmingApi.md new file mode 100644 index 0000000..582bb81 --- /dev/null +++ b/typesense_codegen/docs/StemmingApi.md @@ -0,0 +1,99 @@ +# \StemmingApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**get_stemming_dictionary**](StemmingApi.md#get_stemming_dictionary) | **GET** /stemming/dictionaries/{dictionaryId} | Retrieve a stemming dictionary +[**import_stemming_dictionary**](StemmingApi.md#import_stemming_dictionary) | **POST** /stemming/dictionaries/import | Import a stemming dictionary +[**list_stemming_dictionaries**](StemmingApi.md#list_stemming_dictionaries) | **GET** /stemming/dictionaries | List all stemming dictionaries + + + +## get_stemming_dictionary + +> models::StemmingDictionary get_stemming_dictionary(dictionary_id) +Retrieve a stemming dictionary + +Fetch details of a specific stemming dictionary. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**dictionary_id** | **String** | The ID of the dictionary to retrieve | [required] | + +### Return type + +[**models::StemmingDictionary**](StemmingDictionary.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## import_stemming_dictionary + +> String import_stemming_dictionary(id, body) +Import a stemming dictionary + +Upload a JSONL file containing word mappings to create or update a stemming dictionary. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**id** | **String** | The ID to assign to the dictionary | [required] | +**body** | **String** | The JSONL file containing word mappings | [required] | + +### Return type + +**String** + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/octet-stream, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## list_stemming_dictionaries + +> models::ListStemmingDictionaries200Response list_stemming_dictionaries() +List all stemming dictionaries + +Retrieve a list of all available stemming dictionaries. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::ListStemmingDictionaries200Response**](listStemmingDictionaries_200_response.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/StemmingDictionary.md b/typesense_codegen/docs/StemmingDictionary.md new file mode 100644 index 0000000..4aa3a3e --- /dev/null +++ b/typesense_codegen/docs/StemmingDictionary.md @@ -0,0 +1,12 @@ +# StemmingDictionary + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | Unique identifier for the dictionary | +**words** | [**Vec**](StemmingDictionary_words_inner.md) | List of word mappings in the dictionary | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StemmingDictionaryWordsInner.md b/typesense_codegen/docs/StemmingDictionaryWordsInner.md new file mode 100644 index 0000000..7d9a515 --- /dev/null +++ b/typesense_codegen/docs/StemmingDictionaryWordsInner.md @@ -0,0 +1,12 @@ +# StemmingDictionaryWordsInner + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**word** | **String** | The word form to be stemmed | +**root** | **String** | The root form of the word | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StopwordsApi.md b/typesense_codegen/docs/StopwordsApi.md new file mode 100644 index 0000000..ec7664f --- /dev/null +++ b/typesense_codegen/docs/StopwordsApi.md @@ -0,0 +1,130 @@ +# \StopwordsApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_stopwords_set**](StopwordsApi.md#delete_stopwords_set) | **DELETE** /stopwords/{setId} | Delete a stopwords set. +[**retrieve_stopwords_set**](StopwordsApi.md#retrieve_stopwords_set) | **GET** /stopwords/{setId} | Retrieves a stopwords set. +[**retrieve_stopwords_sets**](StopwordsApi.md#retrieve_stopwords_sets) | **GET** /stopwords | Retrieves all stopwords sets. +[**upsert_stopwords_set**](StopwordsApi.md#upsert_stopwords_set) | **PUT** /stopwords/{setId} | Upserts a stopwords set. + + + +## delete_stopwords_set + +> models::DeleteStopwordsSet200Response delete_stopwords_set(set_id) +Delete a stopwords set. + +Permanently deletes a stopwords set, given it's name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**set_id** | **String** | The ID of the stopwords set to delete. | [required] | + +### Return type + +[**models::DeleteStopwordsSet200Response**](deleteStopwordsSet_200_response.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_stopwords_set + +> models::StopwordsSetRetrieveSchema retrieve_stopwords_set(set_id) +Retrieves a stopwords set. + +Retrieve the details of a stopwords set, given it's name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**set_id** | **String** | The ID of the stopwords set to retrieve. | [required] | + +### Return type + +[**models::StopwordsSetRetrieveSchema**](StopwordsSetRetrieveSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_stopwords_sets + +> models::StopwordsSetsRetrieveAllSchema retrieve_stopwords_sets() +Retrieves all stopwords sets. + +Retrieve the details of all stopwords sets + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::StopwordsSetsRetrieveAllSchema**](StopwordsSetsRetrieveAllSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## upsert_stopwords_set + +> models::StopwordsSetSchema upsert_stopwords_set(set_id, stopwords_set_upsert_schema) +Upserts a stopwords set. + +When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**set_id** | **String** | The ID of the stopwords set to upsert. | [required] | +**stopwords_set_upsert_schema** | [**StopwordsSetUpsertSchema**](StopwordsSetUpsertSchema.md) | The stopwords set to upsert. | [required] | + +### Return type + +[**models::StopwordsSetSchema**](StopwordsSetSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/StopwordsSetRetrieveSchema.md b/typesense_codegen/docs/StopwordsSetRetrieveSchema.md new file mode 100644 index 0000000..284a9ed --- /dev/null +++ b/typesense_codegen/docs/StopwordsSetRetrieveSchema.md @@ -0,0 +1,11 @@ +# StopwordsSetRetrieveSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stopwords** | [**models::StopwordsSetSchema**](StopwordsSetSchema.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StopwordsSetSchema.md b/typesense_codegen/docs/StopwordsSetSchema.md new file mode 100644 index 0000000..97d49dc --- /dev/null +++ b/typesense_codegen/docs/StopwordsSetSchema.md @@ -0,0 +1,13 @@ +# StopwordsSetSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | | +**stopwords** | **Vec** | | +**locale** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StopwordsSetUpsertSchema.md b/typesense_codegen/docs/StopwordsSetUpsertSchema.md new file mode 100644 index 0000000..29082d9 --- /dev/null +++ b/typesense_codegen/docs/StopwordsSetUpsertSchema.md @@ -0,0 +1,12 @@ +# StopwordsSetUpsertSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stopwords** | **Vec** | | +**locale** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StopwordsSetsRetrieveAllSchema.md b/typesense_codegen/docs/StopwordsSetsRetrieveAllSchema.md new file mode 100644 index 0000000..074531b --- /dev/null +++ b/typesense_codegen/docs/StopwordsSetsRetrieveAllSchema.md @@ -0,0 +1,11 @@ +# StopwordsSetsRetrieveAllSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stopwords** | [**Vec**](StopwordsSetSchema.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SynonymsApi.md b/typesense_codegen/docs/SynonymsApi.md new file mode 100644 index 0000000..b09a9dc --- /dev/null +++ b/typesense_codegen/docs/SynonymsApi.md @@ -0,0 +1,132 @@ +# \SynonymsApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_search_synonym**](SynonymsApi.md#delete_search_synonym) | **DELETE** /collections/{collectionName}/synonyms/{synonymId} | Delete a synonym associated with a collection +[**get_search_synonym**](SynonymsApi.md#get_search_synonym) | **GET** /collections/{collectionName}/synonyms/{synonymId} | Retrieve a single search synonym +[**get_search_synonyms**](SynonymsApi.md#get_search_synonyms) | **GET** /collections/{collectionName}/synonyms | List all collection synonyms +[**upsert_search_synonym**](SynonymsApi.md#upsert_search_synonym) | **PUT** /collections/{collectionName}/synonyms/{synonymId} | Create or update a synonym + + + +## delete_search_synonym + +> models::SearchSynonymDeleteResponse delete_search_synonym(collection_name, synonym_id) +Delete a synonym associated with a collection + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**collection_name** | **String** | The name of the collection | [required] | +**synonym_id** | **String** | The ID of the search synonym to delete | [required] | + +### Return type + +[**models::SearchSynonymDeleteResponse**](SearchSynonymDeleteResponse.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## get_search_synonym + +> models::SearchSynonym get_search_synonym(collection_name, synonym_id) +Retrieve a single search synonym + +Retrieve the details of a search synonym, given its id. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**collection_name** | **String** | The name of the collection | [required] | +**synonym_id** | **String** | The id of the search synonym | [required] | + +### Return type + +[**models::SearchSynonym**](SearchSynonym.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## get_search_synonyms + +> models::SearchSynonymsResponse get_search_synonyms(collection_name) +List all collection synonyms + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**collection_name** | **String** | The name of the collection | [required] | + +### Return type + +[**models::SearchSynonymsResponse**](SearchSynonymsResponse.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## upsert_search_synonym + +> models::SearchSynonym upsert_search_synonym(collection_name, synonym_id, search_synonym_schema) +Create or update a synonym + +Create or update a synonym to define search terms that should be considered equivalent. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**collection_name** | **String** | The name of the collection | [required] | +**synonym_id** | **String** | The ID of the search synonym to create/update | [required] | +**search_synonym_schema** | [**SearchSynonymSchema**](SearchSynonymSchema.md) | The search synonym object to be created/updated | [required] | + +### Return type + +[**models::SearchSynonym**](SearchSynonym.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/UpdateDocumentsParameters.md b/typesense_codegen/docs/UpdateDocumentsParameters.md new file mode 100644 index 0000000..31eef40 --- /dev/null +++ b/typesense_codegen/docs/UpdateDocumentsParameters.md @@ -0,0 +1,11 @@ +# UpdateDocumentsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**filter_by** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/VoiceQueryModelCollectionConfig.md b/typesense_codegen/docs/VoiceQueryModelCollectionConfig.md new file mode 100644 index 0000000..24b0aa9 --- /dev/null +++ b/typesense_codegen/docs/VoiceQueryModelCollectionConfig.md @@ -0,0 +1,11 @@ +# VoiceQueryModelCollectionConfig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**model_name** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/src/apis/analytics_api.rs b/typesense_codegen/src/apis/analytics_api.rs index f0c1c7e..ad3b431 100644 --- a/typesense_codegen/src/apis/analytics_api.rs +++ b/typesense_codegen/src/apis/analytics_api.rs @@ -3,19 +3,68 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ -use super::{configuration, Error}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`create_analytics_event`] +#[derive(Clone, Debug)] +pub struct CreateAnalyticsEventParams { + /// The Analytics event to be created + pub analytics_event_create_schema: models::AnalyticsEventCreateSchema +} + +/// struct for passing parameters to the method [`create_analytics_rule`] +#[derive(Clone, Debug)] +pub struct CreateAnalyticsRuleParams { + /// The Analytics rule to be created + pub analytics_rule_schema: models::AnalyticsRuleSchema +} + +/// struct for passing parameters to the method [`delete_analytics_rule`] +#[derive(Clone, Debug)] +pub struct DeleteAnalyticsRuleParams { + /// The name of the analytics rule to delete + pub rule_name: String +} + +/// struct for passing parameters to the method [`retrieve_analytics_rule`] +#[derive(Clone, Debug)] +pub struct RetrieveAnalyticsRuleParams { + /// The name of the analytics rule to retrieve + pub rule_name: String +} + +/// struct for passing parameters to the method [`upsert_analytics_rule`] +#[derive(Clone, Debug)] +pub struct UpsertAnalyticsRuleParams { + /// The name of the analytics rule to upsert + pub rule_name: String, + /// The Analytics rule to be upserted + pub analytics_rule_upsert_schema: models::AnalyticsRuleUpsertSchema +} + + +/// struct for typed errors of method [`create_analytics_event`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateAnalyticsEventError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} /// struct for typed errors of method [`create_analytics_rule`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum CreateAnalyticsRuleError { - Status400(crate::models::ApiResponse), + Status400(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -23,7 +72,7 @@ pub enum CreateAnalyticsRuleError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteAnalyticsRuleError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -31,7 +80,7 @@ pub enum DeleteAnalyticsRuleError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum RetrieveAnalyticsRuleError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -42,198 +91,273 @@ pub enum RetrieveAnalyticsRulesError { UnknownValue(serde_json::Value), } -/// When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. -pub async fn create_analytics_rule( - configuration: &configuration::Configuration, - analytics_rule_schema: crate::models::AnalyticsRuleSchema, -) -> Result> { - let local_var_configuration = configuration; +/// struct for typed errors of method [`upsert_analytics_rule`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertAnalyticsRuleError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} - let local_var_client = &local_var_configuration.client; - let local_var_uri_str = format!("{}/analytics/rules", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); +/// Sending events for analytics e.g rank search results based on popularity. +pub async fn create_analytics_event(configuration: &configuration::Configuration, params: CreateAnalyticsEventParams) -> Result> { - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + let uri_str = format!("{}/analytics/events", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&analytics_rule_schema); + req_builder = req_builder.json(¶ms.analytics_event_create_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; +/// When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. +pub async fn create_analytics_rule(configuration: &configuration::Configuration, params: CreateAnalyticsRuleParams) -> Result> { - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let uri_str = format!("{}/analytics/rules", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.analytics_rule_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRuleSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRuleSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Permanently deletes an analytics rule, given it's name -pub async fn delete_analytics_rule( - configuration: &configuration::Configuration, - rule_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/analytics/rules/{ruleName}", - local_var_configuration.base_path, - ruleName = crate::apis::urlencode(rule_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn delete_analytics_rule(configuration: &configuration::Configuration, params: DeleteAnalyticsRuleParams) -> Result> { + + let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRuleDeleteResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRuleDeleteResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the details of an analytics rule, given it's name -pub async fn retrieve_analytics_rule( - configuration: &configuration::Configuration, - rule_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/analytics/rules/{ruleName}", - local_var_configuration.base_path, - ruleName = crate::apis::urlencode(rule_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn retrieve_analytics_rule(configuration: &configuration::Configuration, params: RetrieveAnalyticsRuleParams) -> Result> { + + let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRuleSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRuleSchema`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the details of all analytics rules -pub async fn retrieve_analytics_rules( - configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; +pub async fn retrieve_analytics_rules(configuration: &configuration::Configuration) -> Result> { - let local_var_uri_str = format!("{}/analytics/rules", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let uri_str = format!("{}/analytics/rules", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRulesRetrieveSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRulesRetrieveSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; +/// Upserts an analytics rule with the given name. +pub async fn upsert_analytics_rule(configuration: &configuration::Configuration, params: UpsertAnalyticsRuleParams) -> Result> { - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + let uri_str = format!("{}/analytics/rules/{ruleName}", configuration.base_path, ruleName=crate::apis::urlencode(params.rule_name)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.analytics_rule_upsert_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::AnalyticsRuleSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRuleSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/collections_api.rs b/typesense_codegen/src/apis/collections_api.rs index 0e0f5bf..9f24d9c 100644 --- a/typesense_codegen/src/apis/collections_api.rs +++ b/typesense_codegen/src/apis/collections_api.rs @@ -3,20 +3,77 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ -use super::{configuration, Error}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`create_collection`] +#[derive(Clone, Debug)] +pub struct CreateCollectionParams { + /// The collection object to be created + pub collection_schema: models::CollectionSchema +} + +/// struct for passing parameters to the method [`delete_alias`] +#[derive(Clone, Debug)] +pub struct DeleteAliasParams { + /// The name of the alias to delete + pub alias_name: String +} + +/// struct for passing parameters to the method [`delete_collection`] +#[derive(Clone, Debug)] +pub struct DeleteCollectionParams { + /// The name of the collection to delete + pub collection_name: String +} + +/// struct for passing parameters to the method [`get_alias`] +#[derive(Clone, Debug)] +pub struct GetAliasParams { + /// The name of the alias to retrieve + pub alias_name: String +} + +/// struct for passing parameters to the method [`get_collection`] +#[derive(Clone, Debug)] +pub struct GetCollectionParams { + /// The name of the collection to retrieve + pub collection_name: String +} + +/// struct for passing parameters to the method [`update_collection`] +#[derive(Clone, Debug)] +pub struct UpdateCollectionParams { + /// The name of the collection to update + pub collection_name: String, + /// The document object with fields to be updated + pub collection_update_schema: models::CollectionUpdateSchema +} + +/// struct for passing parameters to the method [`upsert_alias`] +#[derive(Clone, Debug)] +pub struct UpsertAliasParams { + /// The name of the alias to create/update + pub alias_name: String, + /// Collection alias to be created/updated + pub collection_alias_schema: Option +} + /// struct for typed errors of method [`create_collection`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum CreateCollectionError { - Status400(crate::models::ApiResponse), - Status409(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status409(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -24,7 +81,7 @@ pub enum CreateCollectionError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteAliasError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -32,7 +89,7 @@ pub enum DeleteAliasError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteCollectionError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -40,7 +97,7 @@ pub enum DeleteCollectionError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetAliasError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -55,7 +112,7 @@ pub enum GetAliasesError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetCollectionError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -70,8 +127,8 @@ pub enum GetCollectionsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpdateCollectionError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -79,455 +136,398 @@ pub enum UpdateCollectionError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpsertAliasError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } -/// When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. -pub async fn create_collection( - configuration: &configuration::Configuration, - collection_schema: crate::models::CollectionSchema, -) -> Result> { - let local_var_configuration = configuration; - let local_var_client = &local_var_configuration.client; +/// When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. +pub async fn create_collection(configuration: &configuration::Configuration, params: CreateCollectionParams) -> Result> { - let local_var_uri_str = format!("{}/collections", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + let uri_str = format!("{}/collections", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&collection_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.collection_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -pub async fn delete_alias( - configuration: &configuration::Configuration, - alias_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/aliases/{aliasName}", - local_var_configuration.base_path, - aliasName = crate::apis::urlencode(alias_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn delete_alias(configuration: &configuration::Configuration, params: DeleteAliasParams) -> Result> { + + let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Permanently drops a collection. This action cannot be undone. For large collections, this might have an impact on read latencies. -pub async fn delete_collection( - configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn delete_collection(configuration: &configuration::Configuration, params: DeleteCollectionParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Find out which collection an alias points to by fetching it -pub async fn get_alias( - configuration: &configuration::Configuration, - alias_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/aliases/{aliasName}", - local_var_configuration.base_path, - aliasName = crate::apis::urlencode(alias_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn get_alias(configuration: &configuration::Configuration, params: GetAliasParams) -> Result> { + + let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// List all aliases and the corresponding collections that they map to. -pub async fn get_aliases( - configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; +pub async fn get_aliases(configuration: &configuration::Configuration) -> Result> { - let local_var_client = &local_var_configuration.client; + let uri_str = format!("{}/aliases", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_uri_str = format!("{}/aliases", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAliasesResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAliasesResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve the details of a collection, given its name. -pub async fn get_collection( - configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn get_collection(configuration: &configuration::Configuration, params: GetCollectionParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first. -pub async fn get_collections( - configuration: &configuration::Configuration, -) -> Result, Error> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; +pub async fn get_collections(configuration: &configuration::Configuration) -> Result, Error> { - let local_var_uri_str = format!("{}/collections", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let uri_str = format!("{}/collections", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::CollectionResponse>`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::CollectionResponse>`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Update a collection's schema to modify the fields and their types. -pub async fn update_collection( - configuration: &configuration::Configuration, - collection_name: &str, - collection_update_schema: crate::models::CollectionUpdateSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PATCH, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn update_collection(configuration: &configuration::Configuration, params: UpdateCollectionParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::PATCH, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&collection_update_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.collection_update_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionUpdateSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionUpdateSchema`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Create or update a collection alias. An alias is a virtual collection name that points to a real collection. If you're familiar with symbolic links on Linux, it's very similar to that. Aliases are useful when you want to reindex your data in the background on a new collection and switch your application to it without any changes to your code. -pub async fn upsert_alias( - configuration: &configuration::Configuration, - alias_name: &str, - collection_alias_schema: Option, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/aliases/{aliasName}", - local_var_configuration.base_path, - aliasName = crate::apis::urlencode(alias_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn upsert_alias(configuration: &configuration::Configuration, params: UpsertAliasParams) -> Result> { + + let uri_str = format!("{}/aliases/{aliasName}", configuration.base_path, aliasName=crate::apis::urlencode(params.alias_name)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&collection_alias_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.collection_alias_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/configuration.rs b/typesense_codegen/src/apis/configuration.rs index f5e29b4..8d3c1c1 100644 --- a/typesense_codegen/src/apis/configuration.rs +++ b/typesense_codegen/src/apis/configuration.rs @@ -3,21 +3,22 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ + + #[derive(Debug, Clone)] pub struct Configuration { pub base_path: String, pub user_agent: Option, - pub client: reqwest::Client, + pub client: reqwest_middleware::ClientWithMiddleware, pub basic_auth: Option, pub oauth_access_token: Option, pub bearer_access_token: Option, pub api_key: Option, - // TODO: take an oauth2 token source, similar to the go one } pub type BasicAuth = (String, Option); @@ -28,6 +29,7 @@ pub struct ApiKey { pub key: String, } + impl Configuration { pub fn new() -> Configuration { Configuration::default() @@ -38,8 +40,8 @@ impl Default for Configuration { fn default() -> Self { Configuration { base_path: "http://localhost".to_owned(), - user_agent: Some("OpenAPI-Generator/0.25.0/rust".to_owned()), - client: reqwest::Client::new(), + user_agent: Some("OpenAPI-Generator/28.0/rust".to_owned()), + client: reqwest_middleware::ClientBuilder::new(reqwest::Client::new()).build(), basic_auth: None, oauth_access_token: None, bearer_access_token: None, diff --git a/typesense_codegen/src/apis/conversations_api.rs b/typesense_codegen/src/apis/conversations_api.rs new file mode 100644 index 0000000..951d1c3 --- /dev/null +++ b/typesense_codegen/src/apis/conversations_api.rs @@ -0,0 +1,299 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`create_conversation_model`] +#[derive(Clone, Debug)] +pub struct CreateConversationModelParams { + pub conversation_model_create_schema: models::ConversationModelCreateSchema +} + +/// struct for passing parameters to the method [`delete_conversation_model`] +#[derive(Clone, Debug)] +pub struct DeleteConversationModelParams { + /// The id of the conversation model to delete + pub model_id: String +} + +/// struct for passing parameters to the method [`retrieve_conversation_model`] +#[derive(Clone, Debug)] +pub struct RetrieveConversationModelParams { + /// The id of the conversation model to retrieve + pub model_id: String +} + +/// struct for passing parameters to the method [`update_conversation_model`] +#[derive(Clone, Debug)] +pub struct UpdateConversationModelParams { + /// The id of the conversation model to update + pub model_id: String, + pub conversation_model_update_schema: models::ConversationModelUpdateSchema +} + + +/// struct for typed errors of method [`create_conversation_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateConversationModelError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`delete_conversation_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteConversationModelError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_all_conversation_models`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveAllConversationModelsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_conversation_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveConversationModelError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`update_conversation_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpdateConversationModelError { + UnknownValue(serde_json::Value), +} + + +/// Create a Conversation Model +pub async fn create_conversation_model(configuration: &configuration::Configuration, params: CreateConversationModelParams) -> Result> { + + let uri_str = format!("{}/conversations/models", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.conversation_model_create_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Delete a conversation model +pub async fn delete_conversation_model(configuration: &configuration::Configuration, params: DeleteConversationModelParams) -> Result> { + + let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve all conversation models +pub async fn retrieve_all_conversation_models(configuration: &configuration::Configuration) -> Result, Error> { + + let uri_str = format!("{}/conversations/models", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::ConversationModelSchema>`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::ConversationModelSchema>`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve a conversation model +pub async fn retrieve_conversation_model(configuration: &configuration::Configuration, params: RetrieveConversationModelParams) -> Result> { + + let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Update a conversation model +pub async fn update_conversation_model(configuration: &configuration::Configuration, params: UpdateConversationModelParams) -> Result> { + + let uri_str = format!("{}/conversations/models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.conversation_model_update_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/typesense_codegen/src/apis/curation_api.rs b/typesense_codegen/src/apis/curation_api.rs new file mode 100644 index 0000000..52db601 --- /dev/null +++ b/typesense_codegen/src/apis/curation_api.rs @@ -0,0 +1,196 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`delete_search_override`] +#[derive(Clone, Debug)] +pub struct DeleteSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search override to delete + pub override_id: String +} + +/// struct for passing parameters to the method [`get_search_overrides`] +#[derive(Clone, Debug)] +pub struct GetSearchOverridesParams { + /// The name of the collection + pub collection_name: String +} + +/// struct for passing parameters to the method [`upsert_search_override`] +#[derive(Clone, Debug)] +pub struct UpsertSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search override to create/update + pub override_id: String, + /// The search override object to be created/updated + pub search_override_schema: models::SearchOverrideSchema +} + + +/// struct for typed errors of method [`delete_search_override`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteSearchOverrideError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_search_overrides`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetSearchOverridesError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`upsert_search_override`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertSearchOverrideError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + + +pub async fn delete_search_override(configuration: &configuration::Configuration, params: DeleteSearchOverrideParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +pub async fn get_search_overrides(configuration: &configuration::Configuration, params: GetSearchOverridesParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. +pub async fn upsert_search_override(configuration: &configuration::Configuration, params: UpsertSearchOverrideParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.search_override_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/typesense_codegen/src/apis/debug_api.rs b/typesense_codegen/src/apis/debug_api.rs index 60a727a..af71894 100644 --- a/typesense_codegen/src/apis/debug_api.rs +++ b/typesense_codegen/src/apis/debug_api.rs @@ -3,13 +3,17 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ -use super::{configuration, Error}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + /// struct for typed errors of method [`debug`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -18,47 +22,47 @@ pub enum DebugError { UnknownValue(serde_json::Value), } -/// Print debugging information -pub async fn debug( - configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; - let local_var_client = &local_var_configuration.client; +/// Print debugging information +pub async fn debug(configuration: &configuration::Configuration) -> Result> { - let local_var_uri_str = format!("{}/debug", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let uri_str = format!("{}/debug", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Debug200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Debug200Response`")))), + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/documents_api.rs b/typesense_codegen/src/apis/documents_api.rs index b0ca978..e5335ff 100644 --- a/typesense_codegen/src/apis/documents_api.rs +++ b/typesense_codegen/src/apis/documents_api.rs @@ -3,19 +3,292 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 28.0 * * Generated by: https://openapi-generator.tech */ -use super::{configuration, Error}; -use crate::apis::ResponseContent; +use super::{configuration, ContentType, Error}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{de::Error as _, Deserialize, Serialize}; + +/// struct for passing parameters to the method [`delete_document`] +#[derive(Clone, Debug)] +pub struct DeleteDocumentParams { + /// The name of the collection to search for the document under + pub collection_name: String, + /// The Document ID + pub document_id: String, +} + +/// struct for passing parameters to the method [`delete_documents`] +#[derive(Clone, Debug)] +pub struct DeleteDocumentsParams { + /// The name of the collection to delete documents from + pub collection_name: String, + pub filter_by: Option, + pub batch_size: Option, + pub ignore_not_found: Option, + pub truncate: Option, +} + +/// struct for passing parameters to the method [`delete_search_override`] +#[derive(Clone, Debug)] +pub struct DeleteSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search override to delete + pub override_id: String, +} + +/// struct for passing parameters to the method [`export_documents`] +#[derive(Clone, Debug)] +pub struct ExportDocumentsParams { + /// The name of the collection + pub collection_name: String, + pub filter_by: Option, + pub include_fields: Option, + pub exclude_fields: Option, +} + +/// struct for passing parameters to the method [`get_document`] +#[derive(Clone, Debug)] +pub struct GetDocumentParams { + /// The name of the collection to search for the document under + pub collection_name: String, + /// The Document ID + pub document_id: String, +} + +/// struct for passing parameters to the method [`get_search_override`] +#[derive(Clone, Debug)] +pub struct GetSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The id of the search override + pub override_id: String, +} + +/// struct for passing parameters to the method [`get_search_overrides`] +#[derive(Clone, Debug)] +pub struct GetSearchOverridesParams { + /// The name of the collection + pub collection_name: String, +} + +/// struct for passing parameters to the method [`import_documents`] +#[derive(Clone, Debug)] +pub struct ImportDocumentsParams { + /// The name of the collection + pub collection_name: String, + /// The json array of documents or the JSONL file to import + pub body: String, + pub batch_size: Option, + pub return_id: Option, + pub remote_embedding_batch_size: Option, + pub return_doc: Option, + pub action: Option, + pub dirty_values: Option, +} + +/// struct for passing parameters to the method [`index_document`] +#[derive(Clone, Debug)] +pub struct IndexDocumentParams { + /// The name of the collection to add the document to + pub collection_name: String, + /// The document object to be indexed + pub body: serde_json::Value, + /// Additional action to perform + pub action: Option, + /// Dealing with Dirty Data + pub dirty_values: Option, +} + +/// struct for passing parameters to the method [`multi_search`] +#[derive(Clone, Debug)] +pub struct MultiSearchParams { + pub q: Option, + pub query_by: Option, + pub query_by_weights: Option, + pub text_match_type: Option, + pub prefix: Option, + pub infix: Option, + pub max_extra_prefix: Option, + pub max_extra_suffix: Option, + pub filter_by: Option, + pub sort_by: Option, + pub facet_by: Option, + pub max_facet_values: Option, + pub facet_query: Option, + pub num_typos: Option, + pub page: Option, + pub per_page: Option, + pub limit: Option, + pub offset: Option, + pub group_by: Option, + pub group_limit: Option, + pub group_missing_values: Option, + pub include_fields: Option, + pub exclude_fields: Option, + pub highlight_full_fields: Option, + pub highlight_affix_num_tokens: Option, + pub highlight_start_tag: Option, + pub highlight_end_tag: Option, + pub snippet_threshold: Option, + pub drop_tokens_threshold: Option, + pub drop_tokens_mode: Option, + pub typo_tokens_threshold: Option, + pub enable_typos_for_alpha_numerical_tokens: Option, + pub filter_curated_hits: Option, + pub enable_synonyms: Option, + pub synonym_prefix: Option, + pub synonym_num_typos: Option, + pub pinned_hits: Option, + pub hidden_hits: Option, + pub override_tags: Option, + pub highlight_fields: Option, + pub pre_segmented_query: Option, + pub preset: Option, + pub enable_overrides: Option, + pub prioritize_exact_match: Option, + pub prioritize_token_position: Option, + pub prioritize_num_matching_fields: Option, + pub enable_typos_for_numerical_tokens: Option, + pub exhaustive_search: Option, + pub search_cutoff_ms: Option, + pub use_cache: Option, + pub cache_ttl: Option, + pub min_len_1typo: Option, + pub min_len_2typo: Option, + pub vector_query: Option, + pub remote_embedding_timeout_ms: Option, + pub remote_embedding_num_tries: Option, + pub facet_strategy: Option, + pub stopwords: Option, + pub facet_return_parent: Option, + pub voice_query: Option, + pub conversation: Option, + pub conversation_model_id: Option, + pub conversation_id: Option, + pub multi_search_searches_parameter: Option, +} + +/// struct for passing parameters to the method [`search_collection`] +#[derive(Clone, Debug)] +pub struct SearchCollectionParams { + /// The name of the collection to search for the document under + pub collection_name: String, + pub q: Option, + pub query_by: Option, + pub nl_query: Option, + pub nl_model_id: Option, + pub query_by_weights: Option, + pub text_match_type: Option, + pub prefix: Option, + pub infix: Option, + pub max_extra_prefix: Option, + pub max_extra_suffix: Option, + pub filter_by: Option, + pub max_filter_by_candidates: Option, + pub sort_by: Option, + pub facet_by: Option, + pub max_facet_values: Option, + pub facet_query: Option, + pub num_typos: Option, + pub page: Option, + pub per_page: Option, + pub limit: Option, + pub offset: Option, + pub group_by: Option, + pub group_limit: Option, + pub group_missing_values: Option, + pub include_fields: Option, + pub exclude_fields: Option, + pub highlight_full_fields: Option, + pub highlight_affix_num_tokens: Option, + pub highlight_start_tag: Option, + pub highlight_end_tag: Option, + pub enable_highlight_v1: Option, + pub snippet_threshold: Option, + pub drop_tokens_threshold: Option, + pub drop_tokens_mode: Option, + pub typo_tokens_threshold: Option, + pub enable_typos_for_alpha_numerical_tokens: Option, + pub filter_curated_hits: Option, + pub enable_synonyms: Option, + pub synonym_prefix: Option, + pub synonym_num_typos: Option, + pub pinned_hits: Option, + pub hidden_hits: Option, + pub override_tags: Option, + pub highlight_fields: Option, + pub split_join_tokens: Option, + pub pre_segmented_query: Option, + pub preset: Option, + pub enable_overrides: Option, + pub prioritize_exact_match: Option, + pub max_candidates: Option, + pub prioritize_token_position: Option, + pub prioritize_num_matching_fields: Option, + pub enable_typos_for_numerical_tokens: Option, + pub exhaustive_search: Option, + pub search_cutoff_ms: Option, + pub use_cache: Option, + pub cache_ttl: Option, + pub min_len_1typo: Option, + pub min_len_2typo: Option, + pub vector_query: Option, + pub remote_embedding_timeout_ms: Option, + pub remote_embedding_num_tries: Option, + pub facet_strategy: Option, + pub stopwords: Option, + pub facet_return_parent: Option, + pub voice_query: Option, + pub conversation: Option, + pub conversation_model_id: Option, + pub conversation_id: Option, +} + +/// struct for passing parameters to the method [`update_document`] +#[derive(Clone, Debug)] +pub struct UpdateDocumentParams { + /// The name of the collection to search for the document under + pub collection_name: String, + /// The Document ID + pub document_id: String, + /// The document object with fields to be updated + pub body: serde_json::Value, + /// Dealing with Dirty Data + pub dirty_values: Option, +} + +/// struct for passing parameters to the method [`update_documents`] +#[derive(Clone, Debug)] +pub struct UpdateDocumentsParams { + /// The name of the collection to update documents in + pub collection_name: String, + /// The document fields to be updated + pub body: serde_json::Value, + pub filter_by: Option, +} + +/// struct for passing parameters to the method [`upsert_search_override`] +#[derive(Clone, Debug)] +pub struct UpsertSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search override to create/update + pub override_id: String, + /// The search override object to be created/updated + pub search_override_schema: models::SearchOverrideSchema, +} /// struct for typed errors of method [`delete_document`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteDocumentError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -23,7 +296,7 @@ pub enum DeleteDocumentError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteDocumentsError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -31,15 +304,7 @@ pub enum DeleteDocumentsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteSearchOverrideError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`delete_search_synonym`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum DeleteSearchSynonymError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -47,7 +312,7 @@ pub enum DeleteSearchSynonymError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum ExportDocumentsError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -55,7 +320,7 @@ pub enum ExportDocumentsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetDocumentError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -73,28 +338,12 @@ pub enum GetSearchOverridesError { UnknownValue(serde_json::Value), } -/// struct for typed errors of method [`get_search_synonym`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum GetSearchSynonymError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`get_search_synonyms`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum GetSearchSynonymsError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - /// struct for typed errors of method [`import_documents`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum ImportDocumentsError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -102,7 +351,7 @@ pub enum ImportDocumentsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum IndexDocumentError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -110,7 +359,7 @@ pub enum IndexDocumentError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum MultiSearchError { - Status400(crate::models::ApiResponse), + Status400(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -118,8 +367,8 @@ pub enum MultiSearchError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum SearchCollectionError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -127,7 +376,7 @@ pub enum SearchCollectionError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpdateDocumentError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -135,8 +384,8 @@ pub enum UpdateDocumentError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpdateDocumentsError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -144,990 +393,1247 @@ pub enum UpdateDocumentsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpsertSearchOverrideError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`upsert_search_synonym`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum UpsertSearchSynonymError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } /// Delete an individual document from a collection by using its ID. pub async fn delete_document( configuration: &configuration::Configuration, - collection_name: &str, - document_id: &str, + params: DeleteDocumentParams, ) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + let uri_str = format!( "{}/collections/{collectionName}/documents/{documentId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - documentId = crate::apis::urlencode(document_id) + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + documentId = crate::apis::urlencode(params.document_id) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Delete a bunch of documents that match a specific filter condition. Use the `batch_size` parameter to control the number of documents that should deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. pub async fn delete_documents( configuration: &configuration::Configuration, - collection_name: &str, - delete_documents_parameters: Option< - crate::models::DeleteDocumentsDeleteDocumentsParametersParameter, - >, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: DeleteDocumentsParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/documents", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); - if let Some(ref delete_documents_parameters_ref) = delete_documents_parameters { - local_var_req_builder = local_var_req_builder.query(&delete_documents_parameters_ref); + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref param_value) = params.batch_size { + req_builder = req_builder.query(&[("batch_size", ¶m_value.to_string())]); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref param_value) = params.ignore_not_found { + req_builder = req_builder.query(&[("ignore_not_found", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.truncate { + req_builder = req_builder.query(&[("truncate", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::DeleteDocuments200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::DeleteDocuments200Response`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } pub async fn delete_search_override( configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: DeleteSearchOverrideParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } -} - -pub async fn delete_search_synonym( - configuration: &configuration::Configuration, - collection_name: &str, - synonym_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/synonyms/{synonymId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - synonymId = crate::apis::urlencode(synonym_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Export all documents in a collection in JSON lines format. pub async fn export_documents( configuration: &configuration::Configuration, - collection_name: &str, - export_documents_parameters: Option< - crate::models::ExportDocumentsExportDocumentsParametersParameter, - >, + params: ExportDocumentsParams, ) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + let uri_str = format!( "{}/collections/{collectionName}/documents/export", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref export_documents_parameters_ref) = export_documents_parameters { - local_var_req_builder = local_var_req_builder.query(&export_documents_parameters_ref); + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.include_fields { + req_builder = req_builder.query(&[("include_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.exclude_fields { + req_builder = req_builder.query(&[("exclude_fields", ¶m_value.to_string())]); } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + // changed by hand + match content_type { + ContentType::Json | ContentType::Text => Ok(content), + ContentType::Unsupported(unknown_type) => Err(Error::from( + serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `String`" + )), + )), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Fetch an individual document from a collection by using its ID. pub async fn get_document( configuration: &configuration::Configuration, - collection_name: &str, - document_id: &str, + params: GetDocumentParams, ) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + let uri_str = format!( "{}/collections/{collectionName}/documents/{documentId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - documentId = crate::apis::urlencode(document_id) + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + documentId = crate::apis::urlencode(params.document_id) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of a search override, given its id. pub async fn get_search_override( configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: GetSearchOverrideParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } pub async fn get_search_overrides( configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: GetSearchOverridesParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/overrides", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } -} - -/// Retrieve the details of a search synonym, given its id. -pub async fn get_search_synonym( - configuration: &configuration::Configuration, - collection_name: &str, - synonym_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/synonyms/{synonymId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - synonymId = crate::apis::urlencode(synonym_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) - } -} - -pub async fn get_search_synonyms( - configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/synonyms", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. pub async fn import_documents( configuration: &configuration::Configuration, - collection_name: &str, - body: String, - import_documents_parameters: Option< - crate::models::ImportDocumentsImportDocumentsParametersParameter, - >, + params: ImportDocumentsParams, ) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + let uri_str = format!( "{}/collections/{collectionName}/documents/import", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); - if let Some(ref import_documents_parameters_ref) = import_documents_parameters { - local_var_req_builder = local_var_req_builder.query(&import_documents_parameters_ref); + if let Some(ref param_value) = params.batch_size { + req_builder = req_builder.query(&[("batch_size", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.return_id { + req_builder = req_builder.query(&[("return_id", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_batch_size { + req_builder = + req_builder.query(&[("remote_embedding_batch_size", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.return_doc { + req_builder = req_builder.query(&[("return_doc", ¶m_value.to_string())]); } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref param_value) = params.action { + req_builder = req_builder.query(&[("action", ¶m_value.to_string())]); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref param_value) = params.dirty_values { + req_builder = req_builder.query(&[("dirty_values", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - // was changed by hand - local_var_req_builder = local_var_req_builder.body(body); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - // was changed by hand - Ok(local_var_content) + // changed by hand + req_builder = req_builder.body(params.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + // changed by hand + match content_type { + ContentType::Json | ContentType::Text => Ok(content), + ContentType::Unsupported(unknown_type) => Err(Error::from( + serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `String`" + )), + )), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// A document to be indexed in a given collection must conform to the schema of the collection. pub async fn index_document( configuration: &configuration::Configuration, - collection_name: &str, - body: serde_json::Value, - action: Option<&str>, + params: IndexDocumentParams, ) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + let uri_str = format!( "{}/collections/{collectionName}/documents", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - if let Some(ref local_var_str) = action { - local_var_req_builder = - local_var_req_builder.query(&[("action", &local_var_str.to_string())]); - } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref param_value) = params.action { + req_builder = req_builder.query(&[("action", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.dirty_values { + req_builder = req_builder.query(&[("dirty_values", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&body); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. -pub async fn multi_search serde::Deserialize<'d>>( +pub async fn multi_search( configuration: &configuration::Configuration, - multi_search_parameters: crate::models::MultiSearchParameters, - multi_search_searches_parameter: Option, -) -> Result, Error> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/multi_search", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - local_var_req_builder = local_var_req_builder.query(&multi_search_parameters); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + params: MultiSearchParams, +) -> Result> { + let uri_str = format!("{}/multi_search", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref param_value) = params.q { + req_builder = req_builder.query(&[("q", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.query_by { + req_builder = req_builder.query(&[("query_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.query_by_weights { + req_builder = req_builder.query(&[("query_by_weights", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.text_match_type { + req_builder = req_builder.query(&[("text_match_type", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prefix { + req_builder = req_builder.query(&[("prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.infix { + req_builder = req_builder.query(&[("infix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_extra_prefix { + req_builder = req_builder.query(&[("max_extra_prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_extra_suffix { + req_builder = req_builder.query(&[("max_extra_suffix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.sort_by { + req_builder = req_builder.query(&[("sort_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_by { + req_builder = req_builder.query(&[("facet_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_facet_values { + req_builder = req_builder.query(&[("max_facet_values", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_query { + req_builder = req_builder.query(&[("facet_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.num_typos { + req_builder = req_builder.query(&[("num_typos", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.page { + req_builder = req_builder.query(&[("page", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.per_page { + req_builder = req_builder.query(&[("per_page", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.limit { + req_builder = req_builder.query(&[("limit", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.offset { + req_builder = req_builder.query(&[("offset", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_by { + req_builder = req_builder.query(&[("group_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_limit { + req_builder = req_builder.query(&[("group_limit", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_missing_values { + req_builder = req_builder.query(&[("group_missing_values", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.include_fields { + req_builder = req_builder.query(&[("include_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.exclude_fields { + req_builder = req_builder.query(&[("exclude_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_full_fields { + req_builder = req_builder.query(&[("highlight_full_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_affix_num_tokens { + req_builder = + req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_start_tag { + req_builder = req_builder.query(&[("highlight_start_tag", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_end_tag { + req_builder = req_builder.query(&[("highlight_end_tag", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.snippet_threshold { + req_builder = req_builder.query(&[("snippet_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.drop_tokens_threshold { + req_builder = req_builder.query(&[("drop_tokens_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.drop_tokens_mode { + req_builder = req_builder.query(&[("drop_tokens_mode", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.typo_tokens_threshold { + req_builder = req_builder.query(&[("typo_tokens_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_typos_for_alpha_numerical_tokens { + req_builder = req_builder.query(&[( + "enable_typos_for_alpha_numerical_tokens", + ¶m_value.to_string(), + )]); + } + if let Some(ref param_value) = params.filter_curated_hits { + req_builder = req_builder.query(&[("filter_curated_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_synonyms { + req_builder = req_builder.query(&[("enable_synonyms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_prefix { + req_builder = req_builder.query(&[("synonym_prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_num_typos { + req_builder = req_builder.query(&[("synonym_num_typos", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.pinned_hits { + req_builder = req_builder.query(&[("pinned_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.hidden_hits { + req_builder = req_builder.query(&[("hidden_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.override_tags { + req_builder = req_builder.query(&[("override_tags", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_fields { + req_builder = req_builder.query(&[("highlight_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.pre_segmented_query { + req_builder = req_builder.query(&[("pre_segmented_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.preset { + req_builder = req_builder.query(&[("preset", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_overrides { + req_builder = req_builder.query(&[("enable_overrides", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_exact_match { + req_builder = req_builder.query(&[("prioritize_exact_match", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_token_position { + req_builder = req_builder.query(&[("prioritize_token_position", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_num_matching_fields { + req_builder = + req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_typos_for_numerical_tokens { + req_builder = req_builder.query(&[( + "enable_typos_for_numerical_tokens", + ¶m_value.to_string(), + )]); + } + if let Some(ref param_value) = params.exhaustive_search { + req_builder = req_builder.query(&[("exhaustive_search", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.search_cutoff_ms { + req_builder = req_builder.query(&[("search_cutoff_ms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.use_cache { + req_builder = req_builder.query(&[("use_cache", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.cache_ttl { + req_builder = req_builder.query(&[("cache_ttl", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.min_len_1typo { + req_builder = req_builder.query(&[("min_len_1typo", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.min_len_2typo { + req_builder = req_builder.query(&[("min_len_2typo", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.vector_query { + req_builder = req_builder.query(&[("vector_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_timeout_ms { + req_builder = + req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_num_tries { + req_builder = + req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_strategy { + req_builder = req_builder.query(&[("facet_strategy", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.stopwords { + req_builder = req_builder.query(&[("stopwords", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_return_parent { + req_builder = req_builder.query(&[("facet_return_parent", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.voice_query { + req_builder = req_builder.query(&[("voice_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation { + req_builder = req_builder.query(&[("conversation", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation_model_id { + req_builder = req_builder.query(&[("conversation_model_id", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation_id { + req_builder = req_builder.query(&[("conversation_id", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&multi_search_searches_parameter); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.multi_search_searches_parameter); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::MultiSearchResult`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::MultiSearchResult`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Search for documents in a collection that match the search criteria. -pub async fn search_collection serde::Deserialize<'d>>( +pub async fn search_collection( configuration: &configuration::Configuration, - collection_name: &str, - search_parameters: crate::models::SearchParameters, -) -> Result, Error> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: SearchCollectionParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/documents/search", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - local_var_req_builder = local_var_req_builder.query(&search_parameters); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref param_value) = params.q { + req_builder = req_builder.query(&[("q", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.query_by { + req_builder = req_builder.query(&[("query_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.nl_query { + req_builder = req_builder.query(&[("nl_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.nl_model_id { + req_builder = req_builder.query(&[("nl_model_id", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.query_by_weights { + req_builder = req_builder.query(&[("query_by_weights", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.text_match_type { + req_builder = req_builder.query(&[("text_match_type", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prefix { + req_builder = req_builder.query(&[("prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.infix { + req_builder = req_builder.query(&[("infix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_extra_prefix { + req_builder = req_builder.query(&[("max_extra_prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_extra_suffix { + req_builder = req_builder.query(&[("max_extra_suffix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_filter_by_candidates { + req_builder = req_builder.query(&[("max_filter_by_candidates", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.sort_by { + req_builder = req_builder.query(&[("sort_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_by { + req_builder = req_builder.query(&[("facet_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_facet_values { + req_builder = req_builder.query(&[("max_facet_values", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_query { + req_builder = req_builder.query(&[("facet_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.num_typos { + req_builder = req_builder.query(&[("num_typos", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.page { + req_builder = req_builder.query(&[("page", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.per_page { + req_builder = req_builder.query(&[("per_page", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.limit { + req_builder = req_builder.query(&[("limit", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.offset { + req_builder = req_builder.query(&[("offset", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_by { + req_builder = req_builder.query(&[("group_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_limit { + req_builder = req_builder.query(&[("group_limit", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_missing_values { + req_builder = req_builder.query(&[("group_missing_values", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.include_fields { + req_builder = req_builder.query(&[("include_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.exclude_fields { + req_builder = req_builder.query(&[("exclude_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_full_fields { + req_builder = req_builder.query(&[("highlight_full_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_affix_num_tokens { + req_builder = + req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_start_tag { + req_builder = req_builder.query(&[("highlight_start_tag", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_end_tag { + req_builder = req_builder.query(&[("highlight_end_tag", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_highlight_v1 { + req_builder = req_builder.query(&[("enable_highlight_v1", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.snippet_threshold { + req_builder = req_builder.query(&[("snippet_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.drop_tokens_threshold { + req_builder = req_builder.query(&[("drop_tokens_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.drop_tokens_mode { + req_builder = req_builder.query(&[("drop_tokens_mode", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.typo_tokens_threshold { + req_builder = req_builder.query(&[("typo_tokens_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_typos_for_alpha_numerical_tokens { + req_builder = req_builder.query(&[( + "enable_typos_for_alpha_numerical_tokens", + ¶m_value.to_string(), + )]); + } + if let Some(ref param_value) = params.filter_curated_hits { + req_builder = req_builder.query(&[("filter_curated_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_synonyms { + req_builder = req_builder.query(&[("enable_synonyms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_prefix { + req_builder = req_builder.query(&[("synonym_prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_num_typos { + req_builder = req_builder.query(&[("synonym_num_typos", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.pinned_hits { + req_builder = req_builder.query(&[("pinned_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.hidden_hits { + req_builder = req_builder.query(&[("hidden_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.override_tags { + req_builder = req_builder.query(&[("override_tags", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_fields { + req_builder = req_builder.query(&[("highlight_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.split_join_tokens { + req_builder = req_builder.query(&[("split_join_tokens", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.pre_segmented_query { + req_builder = req_builder.query(&[("pre_segmented_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.preset { + req_builder = req_builder.query(&[("preset", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_overrides { + req_builder = req_builder.query(&[("enable_overrides", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_exact_match { + req_builder = req_builder.query(&[("prioritize_exact_match", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_candidates { + req_builder = req_builder.query(&[("max_candidates", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_token_position { + req_builder = req_builder.query(&[("prioritize_token_position", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_num_matching_fields { + req_builder = + req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_typos_for_numerical_tokens { + req_builder = req_builder.query(&[( + "enable_typos_for_numerical_tokens", + ¶m_value.to_string(), + )]); + } + if let Some(ref param_value) = params.exhaustive_search { + req_builder = req_builder.query(&[("exhaustive_search", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.search_cutoff_ms { + req_builder = req_builder.query(&[("search_cutoff_ms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.use_cache { + req_builder = req_builder.query(&[("use_cache", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.cache_ttl { + req_builder = req_builder.query(&[("cache_ttl", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.min_len_1typo { + req_builder = req_builder.query(&[("min_len_1typo", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.min_len_2typo { + req_builder = req_builder.query(&[("min_len_2typo", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.vector_query { + req_builder = req_builder.query(&[("vector_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_timeout_ms { + req_builder = + req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_num_tries { + req_builder = + req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_strategy { + req_builder = req_builder.query(&[("facet_strategy", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.stopwords { + req_builder = req_builder.query(&[("stopwords", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_return_parent { + req_builder = req_builder.query(&[("facet_return_parent", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.voice_query { + req_builder = req_builder.query(&[("voice_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation { + req_builder = req_builder.query(&[("conversation", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation_model_id { + req_builder = req_builder.query(&[("conversation_model_id", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation_id { + req_builder = req_builder.query(&[("conversation_id", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchResult`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchResult`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Update an individual document from a collection by using its ID. The update can be partial. pub async fn update_document( configuration: &configuration::Configuration, - collection_name: &str, - document_id: &str, - body: serde_json::Value, + params: UpdateDocumentParams, ) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + let uri_str = format!( "{}/collections/{collectionName}/documents/{documentId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - documentId = crate::apis::urlencode(document_id) + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + documentId = crate::apis::urlencode(params.document_id) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PATCH, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + let mut req_builder = configuration + .client + .request(reqwest::Method::PATCH, &uri_str); + + if let Some(ref param_value) = params.dirty_values { + req_builder = req_builder.query(&[("dirty_values", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&body); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// The filter_by query parameter is used to filter to specify a condition against which the documents are matched. The request body contains the fields that should be updated for any documents that match the filter condition. This endpoint is only available if the Typesense server is version `0.25.0.rc12` or later. pub async fn update_documents( configuration: &configuration::Configuration, - collection_name: &str, - body: serde_json::Value, - update_documents_parameters: Option< - crate::models::UpdateDocumentsUpdateDocumentsParametersParameter, - >, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: UpdateDocumentsParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/documents", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PATCH, local_var_uri_str.as_str()); + let mut req_builder = configuration + .client + .request(reqwest::Method::PATCH, &uri_str); - if let Some(ref update_documents_parameters_ref) = update_documents_parameters { - local_var_req_builder = local_var_req_builder.query(&update_documents_parameters_ref); + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&body); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::UpdateDocuments200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::UpdateDocuments200Response`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. pub async fn upsert_search_override( configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, - search_override_schema: crate::models::SearchOverrideSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: UpsertSearchOverrideParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) + configuration.base_path, + collectionName = crate::apis::urlencode(params.collection_name), + overrideId = crate::apis::urlencode(params.override_id) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - local_var_req_builder = local_var_req_builder.json(&search_override_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } -} - -/// Create or update a synonym to define search terms that should be considered equivalent. -pub async fn upsert_search_synonym( - configuration: &configuration::Configuration, - collection_name: &str, - synonym_id: &str, - search_synonym_schema: crate::models::SearchSynonymSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/synonyms/{synonymId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - synonymId = crate::apis::urlencode(synonym_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&search_synonym_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.search_override_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } diff --git a/typesense_codegen/src/apis/health_api.rs b/typesense_codegen/src/apis/health_api.rs index d2978fb..9ce4c07 100644 --- a/typesense_codegen/src/apis/health_api.rs +++ b/typesense_codegen/src/apis/health_api.rs @@ -3,13 +3,17 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ -use super::{configuration, Error}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + /// struct for typed errors of method [`health`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -18,47 +22,47 @@ pub enum HealthError { UnknownValue(serde_json::Value), } -/// Checks if Typesense server is ready to accept requests. -pub async fn health( - configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; - let local_var_client = &local_var_configuration.client; +/// Checks if Typesense server is ready to accept requests. +pub async fn health(configuration: &configuration::Configuration) -> Result> { - let local_var_uri_str = format!("{}/health", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let uri_str = format!("{}/health", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::HealthStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::HealthStatus`")))), + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/keys_api.rs b/typesense_codegen/src/apis/keys_api.rs index 6b42ab8..5490f79 100644 --- a/typesense_codegen/src/apis/keys_api.rs +++ b/typesense_codegen/src/apis/keys_api.rs @@ -3,20 +3,45 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ -use super::{configuration, Error}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`create_key`] +#[derive(Clone, Debug)] +pub struct CreateKeyParams { + /// The object that describes API key scope + pub api_key_schema: Option +} + +/// struct for passing parameters to the method [`delete_key`] +#[derive(Clone, Debug)] +pub struct DeleteKeyParams { + /// The ID of the key to delete + pub key_id: i64 +} + +/// struct for passing parameters to the method [`get_key`] +#[derive(Clone, Debug)] +pub struct GetKeyParams { + /// The ID of the key to retrieve + pub key_id: i64 +} + /// struct for typed errors of method [`create_key`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum CreateKeyError { - Status400(crate::models::ApiResponse), - Status409(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status409(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -24,8 +49,8 @@ pub enum CreateKeyError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteKeyError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -33,7 +58,7 @@ pub enum DeleteKeyError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetKeyError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -44,194 +69,175 @@ pub enum GetKeysError { UnknownValue(serde_json::Value), } -/// Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. -pub async fn create_key( - configuration: &configuration::Configuration, - api_key_schema: Option, -) -> Result> { - let local_var_configuration = configuration; - let local_var_client = &local_var_configuration.client; +/// Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. +pub async fn create_key(configuration: &configuration::Configuration, params: CreateKeyParams) -> Result> { - let local_var_uri_str = format!("{}/keys", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + let uri_str = format!("{}/keys", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&api_key_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.api_key_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKey`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -pub async fn delete_key( - configuration: &configuration::Configuration, - key_id: i64, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/keys/{keyId}", - local_var_configuration.base_path, - keyId = key_id - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn delete_key(configuration: &configuration::Configuration, params: DeleteKeyParams) -> Result> { + + let uri_str = format!("{}/keys/{keyId}", configuration.base_path, keyId=params.key_id); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKeyDeleteResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeyDeleteResponse`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } /// Retrieve (metadata about) a key. Only the key prefix is returned when you retrieve a key. Due to security reasons, only the create endpoint returns the full API key. -pub async fn get_key( - configuration: &configuration::Configuration, - key_id: i64, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/keys/{keyId}", - local_var_configuration.base_path, - keyId = key_id - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +pub async fn get_key(configuration: &configuration::Configuration, params: GetKeyParams) -> Result> { + + let uri_str = format!("{}/keys/{keyId}", configuration.base_path, keyId=params.key_id); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKey`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`")))), + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -pub async fn get_keys( - configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; +pub async fn get_keys(configuration: &configuration::Configuration) -> Result> { - let local_var_client = &local_var_configuration.client; + let uri_str = format!("{}/keys", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_uri_str = format!("{}/keys", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiKeysResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeysResponse`")))), + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/mod.rs b/typesense_codegen/src/apis/mod.rs index 130e195..070f27a 100644 --- a/typesense_codegen/src/apis/mod.rs +++ b/typesense_codegen/src/apis/mod.rs @@ -11,15 +11,17 @@ pub struct ResponseContent { #[derive(Debug)] pub enum Error { Reqwest(reqwest::Error), + ReqwestMiddleware(reqwest_middleware::Error), Serde(serde_json::Error), Io(std::io::Error), ResponseError(ResponseContent), } -impl fmt::Display for Error { +impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let (module, e) = match self { Error::Reqwest(e) => ("reqwest", e.to_string()), + Error::ReqwestMiddleware(e) => ("reqwest-middleware", e.to_string()), Error::Serde(e) => ("serde", e.to_string()), Error::Io(e) => ("IO", e.to_string()), Error::ResponseError(e) => ("response", format!("status code {}", e.status)), @@ -28,10 +30,11 @@ impl fmt::Display for Error { } } -impl error::Error for Error { +impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { Some(match self { Error::Reqwest(e) => e, + Error::ReqwestMiddleware(e) => e, Error::Serde(e) => e, Error::Io(e) => e, Error::ResponseError(_) => return None, @@ -39,19 +42,25 @@ impl error::Error for Error { } } -impl From for Error { +impl From for Error { fn from(e: reqwest::Error) -> Self { Error::Reqwest(e) } } -impl From for Error { +impl From for Error { + fn from(e: reqwest_middleware::Error) -> Self { + Error::ReqwestMiddleware(e) + } +} + +impl From for Error { fn from(e: serde_json::Error) -> Self { Error::Serde(e) } } -impl From for Error { +impl From for Error { fn from(e: std::io::Error) -> Self { Error::Io(e) } @@ -78,10 +87,8 @@ pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String value, )); } - } - serde_json::Value::String(s) => { - params.push((format!("{}[{}]", prefix, key), s.clone())) - } + }, + serde_json::Value::String(s) => params.push((format!("{}[{}]", prefix, key), s.clone())), _ => params.push((format!("{}[{}]", prefix, key), value.to_string())), } } @@ -92,14 +99,41 @@ pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String unimplemented!("Only objects are supported with style=deepObject") } +/// Internal use only +/// A content type supported by this client. +#[allow(dead_code)] +enum ContentType { + Json, + Text, + Unsupported(String) +} + +impl From<&str> for ContentType { + fn from(content_type: &str) -> Self { + if content_type.starts_with("application") && content_type.contains("json") { + return Self::Json; + } else if content_type.starts_with("text/plain") { + return Self::Text; + } else { + return Self::Unsupported(content_type.to_string()); + } + } +} + pub mod analytics_api; pub mod collections_api; +pub mod conversations_api; +pub mod curation_api; pub mod debug_api; pub mod documents_api; pub mod health_api; pub mod keys_api; +pub mod nl_search_models_api; pub mod operations_api; pub mod override_api; -pub mod promote_api; +pub mod presets_api; +pub mod stemming_api; +pub mod stopwords_api; +pub mod synonyms_api; pub mod configuration; diff --git a/typesense_codegen/src/apis/nl_search_models_api.rs b/typesense_codegen/src/apis/nl_search_models_api.rs new file mode 100644 index 0000000..0bf0ee8 --- /dev/null +++ b/typesense_codegen/src/apis/nl_search_models_api.rs @@ -0,0 +1,305 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`create_nl_search_model`] +#[derive(Clone, Debug)] +pub struct CreateNlSearchModelParams { + /// The NL search model to be created + pub nl_search_model_create_schema: models::NlSearchModelCreateSchema +} + +/// struct for passing parameters to the method [`delete_nl_search_model`] +#[derive(Clone, Debug)] +pub struct DeleteNlSearchModelParams { + /// The ID of the NL search model to delete + pub model_id: String +} + +/// struct for passing parameters to the method [`retrieve_nl_search_model`] +#[derive(Clone, Debug)] +pub struct RetrieveNlSearchModelParams { + /// The ID of the NL search model to retrieve + pub model_id: String +} + +/// struct for passing parameters to the method [`update_nl_search_model`] +#[derive(Clone, Debug)] +pub struct UpdateNlSearchModelParams { + /// The ID of the NL search model to update + pub model_id: String, + /// The NL search model fields to update + pub body: models::NlSearchModelCreateSchema +} + + +/// struct for typed errors of method [`create_nl_search_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateNlSearchModelError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`delete_nl_search_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteNlSearchModelError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_all_nl_search_models`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveAllNlSearchModelsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_nl_search_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveNlSearchModelError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`update_nl_search_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpdateNlSearchModelError { + Status400(models::ApiResponse), + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + + +/// Create a new NL search model. +pub async fn create_nl_search_model(configuration: &configuration::Configuration, params: CreateNlSearchModelParams) -> Result> { + + let uri_str = format!("{}/nl_search_models", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.nl_search_model_create_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Delete a specific NL search model by its ID. +pub async fn delete_nl_search_model(configuration: &configuration::Configuration, params: DeleteNlSearchModelParams) -> Result> { + + let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve all NL search models. +pub async fn retrieve_all_nl_search_models(configuration: &configuration::Configuration) -> Result, Error> { + + let uri_str = format!("{}/nl_search_models", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::NlSearchModelSchema>`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::NlSearchModelSchema>`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve a specific NL search model by its ID. +pub async fn retrieve_nl_search_model(configuration: &configuration::Configuration, params: RetrieveNlSearchModelParams) -> Result> { + + let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Update an existing NL search model. +pub async fn update_nl_search_model(configuration: &configuration::Configuration, params: UpdateNlSearchModelParams) -> Result> { + + let uri_str = format!("{}/nl_search_models/{modelId}", configuration.base_path, modelId=crate::apis::urlencode(params.model_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/typesense_codegen/src/apis/operations_api.rs b/typesense_codegen/src/apis/operations_api.rs index f7c2877..229c8cd 100644 --- a/typesense_codegen/src/apis/operations_api.rs +++ b/typesense_codegen/src/apis/operations_api.rs @@ -3,13 +3,45 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ -use super::{configuration, Error}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`take_snapshot`] +#[derive(Clone, Debug)] +pub struct TakeSnapshotParams { + /// The directory on the server where the snapshot should be saved. + pub snapshot_path: String +} + + +/// struct for typed errors of method [`get_schema_changes`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetSchemaChangesError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_api_stats`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveApiStatsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_metrics`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveMetricsError { + UnknownValue(serde_json::Value), +} /// struct for typed errors of method [`take_snapshot`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -25,96 +57,220 @@ pub enum VoteError { UnknownValue(serde_json::Value), } -/// Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. -pub async fn take_snapshot( - configuration: &configuration::Configuration, - snapshot_path: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/operations/snapshot", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - local_var_req_builder = - local_var_req_builder.query(&[("snapshot_path", &snapshot_path.to_string())]); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + +/// Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. +pub async fn get_schema_changes(configuration: &configuration::Configuration) -> Result, Error> { + + let uri_str = format!("{}/operations/schema_changes", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::SchemaChangeStatus>`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::SchemaChangeStatus>`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve the stats about API endpoints. +pub async fn retrieve_api_stats(configuration: &configuration::Configuration) -> Result> { + + let uri_str = format!("{}/stats.json", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ApiStatsResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ApiStatsResponse`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } -/// Triggers a follower node to initiate the raft voting process, which triggers leader re-election. The follower node that you run this operation against will become the new leader, once this command succeeds. -pub async fn vote( - configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; +/// Retrieve the metrics. +pub async fn retrieve_metrics(configuration: &configuration::Configuration) -> Result> { + + let uri_str = format!("{}/metrics.json", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `serde_json::Value`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} - let local_var_client = &local_var_configuration.client; +/// Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. +pub async fn take_snapshot(configuration: &configuration::Configuration, params: TakeSnapshotParams) -> Result> { - let local_var_uri_str = format!("{}/operations/vote", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + let uri_str = format!("{}/operations/snapshot", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + req_builder = req_builder.query(&[("snapshot_path", ¶ms.snapshot_path.to_string())]); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Triggers a follower node to initiate the raft voting process, which triggers leader re-election. The follower node that you run this operation against will become the new leader, once this command succeeds. +pub async fn vote(configuration: &configuration::Configuration) -> Result> { + + let uri_str = format!("{}/operations/vote", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/override_api.rs b/typesense_codegen/src/apis/override_api.rs index 069cc4e..be1b76f 100644 --- a/typesense_codegen/src/apis/override_api.rs +++ b/typesense_codegen/src/apis/override_api.rs @@ -3,13 +3,26 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ -use super::{configuration, Error}; -use crate::apis::ResponseContent; + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`get_search_override`] +#[derive(Clone, Debug)] +pub struct GetSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The id of the search override + pub override_id: String +} + /// struct for typed errors of method [`get_search_override`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -18,55 +31,47 @@ pub enum GetSearchOverrideError { UnknownValue(serde_json::Value), } -/// Retrieve the details of a search override, given its id. -pub async fn get_search_override( - configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, -) -> Result> { - let local_var_configuration = configuration; - let local_var_client = &local_var_configuration.client; +/// Retrieve the details of a search override, given its id. +pub async fn get_search_override(configuration: &configuration::Configuration, params: GetSearchOverrideParams) -> Result> { - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let uri_str = format!("{}/collections/{collectionName}/overrides/{overrideId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), overrideId=crate::apis::urlencode(params.override_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchOverride`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`")))), + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) } } + diff --git a/typesense_codegen/src/apis/presets_api.rs b/typesense_codegen/src/apis/presets_api.rs new file mode 100644 index 0000000..f90dd81 --- /dev/null +++ b/typesense_codegen/src/apis/presets_api.rs @@ -0,0 +1,245 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`delete_preset`] +#[derive(Clone, Debug)] +pub struct DeletePresetParams { + /// The ID of the preset to delete. + pub preset_id: String +} + +/// struct for passing parameters to the method [`retrieve_preset`] +#[derive(Clone, Debug)] +pub struct RetrievePresetParams { + /// The ID of the preset to retrieve. + pub preset_id: String +} + +/// struct for passing parameters to the method [`upsert_preset`] +#[derive(Clone, Debug)] +pub struct UpsertPresetParams { + /// The name of the preset set to upsert. + pub preset_id: String, + /// The stopwords set to upsert. + pub preset_upsert_schema: models::PresetUpsertSchema +} + + +/// struct for typed errors of method [`delete_preset`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeletePresetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_all_presets`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveAllPresetsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_preset`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrievePresetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`upsert_preset`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertPresetError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + + +/// Permanently deletes a preset, given it's name. +pub async fn delete_preset(configuration: &configuration::Configuration, params: DeletePresetParams) -> Result> { + + let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetDeleteSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetDeleteSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve the details of all presets +pub async fn retrieve_all_presets(configuration: &configuration::Configuration) -> Result> { + + let uri_str = format!("{}/presets", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetsRetrieveSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetsRetrieveSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve the details of a preset, given it's name. +pub async fn retrieve_preset(configuration: &configuration::Configuration, params: RetrievePresetParams) -> Result> { + + let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Create or update an existing preset. +pub async fn upsert_preset(configuration: &configuration::Configuration, params: UpsertPresetParams) -> Result> { + + let uri_str = format!("{}/presets/{presetId}", configuration.base_path, presetId=crate::apis::urlencode(params.preset_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.preset_upsert_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PresetSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/typesense_codegen/src/apis/promote_api.rs b/typesense_codegen/src/apis/promote_api.rs deleted file mode 100644 index 052d70f..0000000 --- a/typesense_codegen/src/apis/promote_api.rs +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -use super::{configuration, Error}; -use crate::apis::ResponseContent; - -/// struct for typed errors of method [`delete_search_override`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum DeleteSearchOverrideError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`get_search_overrides`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum GetSearchOverridesError { - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`upsert_search_override`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum UpsertSearchOverrideError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -pub async fn delete_search_override( - configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) - } -} - -pub async fn get_search_overrides( - configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) - } -} - -/// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. -pub async fn upsert_search_override( - configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, - search_override_schema: crate::models::SearchOverrideSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - local_var_req_builder = local_var_req_builder.json(&search_override_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) - } -} diff --git a/typesense_codegen/src/apis/stemming_api.rs b/typesense_codegen/src/apis/stemming_api.rs new file mode 100644 index 0000000..d8aaf50 --- /dev/null +++ b/typesense_codegen/src/apis/stemming_api.rs @@ -0,0 +1,212 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use super::{configuration, ContentType, Error}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{de::Error as _, Deserialize, Serialize}; + +/// struct for passing parameters to the method [`get_stemming_dictionary`] +#[derive(Clone, Debug)] +pub struct GetStemmingDictionaryParams { + /// The ID of the dictionary to retrieve + pub dictionary_id: String, +} + +/// struct for passing parameters to the method [`import_stemming_dictionary`] +#[derive(Clone, Debug)] +pub struct ImportStemmingDictionaryParams { + /// The ID to assign to the dictionary + pub id: String, + /// The JSONL file containing word mappings + pub body: String, +} + +/// struct for typed errors of method [`get_stemming_dictionary`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetStemmingDictionaryError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`import_stemming_dictionary`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ImportStemmingDictionaryError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`list_stemming_dictionaries`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ListStemmingDictionariesError { + UnknownValue(serde_json::Value), +} + +/// Fetch details of a specific stemming dictionary. +pub async fn get_stemming_dictionary( + configuration: &configuration::Configuration, + params: GetStemmingDictionaryParams, +) -> Result> { + let uri_str = format!( + "{}/stemming/dictionaries/{dictionaryId}", + configuration.base_path, + dictionaryId = crate::apis::urlencode(params.dictionary_id) + ); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StemmingDictionary`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StemmingDictionary`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Upload a JSONL file containing word mappings to create or update a stemming dictionary. +pub async fn import_stemming_dictionary( + configuration: &configuration::Configuration, + params: ImportStemmingDictionaryParams, +) -> Result> { + let uri_str = format!("{}/stemming/dictionaries/import", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + req_builder = req_builder.query(&[("id", ¶ms.id.to_string())]); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + // changed by hand + req_builder = req_builder.body(params.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + // changed by hand + match content_type { + ContentType::Json | ContentType::Text => Ok(content), + ContentType::Unsupported(unknown_type) => Err(Error::from( + serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `String`" + )), + )), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve a list of all available stemming dictionaries. +pub async fn list_stemming_dictionaries( + configuration: &configuration::Configuration, +) -> Result> { + let uri_str = format!("{}/stemming/dictionaries", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} diff --git a/typesense_codegen/src/apis/stopwords_api.rs b/typesense_codegen/src/apis/stopwords_api.rs new file mode 100644 index 0000000..e89df6e --- /dev/null +++ b/typesense_codegen/src/apis/stopwords_api.rs @@ -0,0 +1,245 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`delete_stopwords_set`] +#[derive(Clone, Debug)] +pub struct DeleteStopwordsSetParams { + /// The ID of the stopwords set to delete. + pub set_id: String +} + +/// struct for passing parameters to the method [`retrieve_stopwords_set`] +#[derive(Clone, Debug)] +pub struct RetrieveStopwordsSetParams { + /// The ID of the stopwords set to retrieve. + pub set_id: String +} + +/// struct for passing parameters to the method [`upsert_stopwords_set`] +#[derive(Clone, Debug)] +pub struct UpsertStopwordsSetParams { + /// The ID of the stopwords set to upsert. + pub set_id: String, + /// The stopwords set to upsert. + pub stopwords_set_upsert_schema: models::StopwordsSetUpsertSchema +} + + +/// struct for typed errors of method [`delete_stopwords_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteStopwordsSetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_stopwords_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveStopwordsSetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_stopwords_sets`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveStopwordsSetsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`upsert_stopwords_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertStopwordsSetError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + + +/// Permanently deletes a stopwords set, given it's name. +pub async fn delete_stopwords_set(configuration: &configuration::Configuration, params: DeleteStopwordsSetParams) -> Result> { + + let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve the details of a stopwords set, given it's name. +pub async fn retrieve_stopwords_set(configuration: &configuration::Configuration, params: RetrieveStopwordsSetParams) -> Result> { + + let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve the details of all stopwords sets +pub async fn retrieve_stopwords_sets(configuration: &configuration::Configuration) -> Result> { + + let uri_str = format!("{}/stopwords", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. +pub async fn upsert_stopwords_set(configuration: &configuration::Configuration, params: UpsertStopwordsSetParams) -> Result> { + + let uri_str = format!("{}/stopwords/{setId}", configuration.base_path, setId=crate::apis::urlencode(params.set_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.stopwords_set_upsert_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::StopwordsSetSchema`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetSchema`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/typesense_codegen/src/apis/synonyms_api.rs b/typesense_codegen/src/apis/synonyms_api.rs new file mode 100644 index 0000000..12429a3 --- /dev/null +++ b/typesense_codegen/src/apis/synonyms_api.rs @@ -0,0 +1,257 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +/// struct for passing parameters to the method [`delete_search_synonym`] +#[derive(Clone, Debug)] +pub struct DeleteSearchSynonymParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search synonym to delete + pub synonym_id: String +} + +/// struct for passing parameters to the method [`get_search_synonym`] +#[derive(Clone, Debug)] +pub struct GetSearchSynonymParams { + /// The name of the collection + pub collection_name: String, + /// The id of the search synonym + pub synonym_id: String +} + +/// struct for passing parameters to the method [`get_search_synonyms`] +#[derive(Clone, Debug)] +pub struct GetSearchSynonymsParams { + /// The name of the collection + pub collection_name: String +} + +/// struct for passing parameters to the method [`upsert_search_synonym`] +#[derive(Clone, Debug)] +pub struct UpsertSearchSynonymParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search synonym to create/update + pub synonym_id: String, + /// The search synonym object to be created/updated + pub search_synonym_schema: models::SearchSynonymSchema +} + + +/// struct for typed errors of method [`delete_search_synonym`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteSearchSynonymError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_search_synonym`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetSearchSynonymError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_search_synonyms`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetSearchSynonymsError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`upsert_search_synonym`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertSearchSynonymError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + + +pub async fn delete_search_synonym(configuration: &configuration::Configuration, params: DeleteSearchSynonymParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/synonyms/{synonymId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), synonymId=crate::apis::urlencode(params.synonym_id)); + let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchSynonymDeleteResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchSynonymDeleteResponse`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Retrieve the details of a search synonym, given its id. +pub async fn get_search_synonym(configuration: &configuration::Configuration, params: GetSearchSynonymParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/synonyms/{synonymId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), synonymId=crate::apis::urlencode(params.synonym_id)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchSynonym`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchSynonym`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +pub async fn get_search_synonyms(configuration: &configuration::Configuration, params: GetSearchSynonymsParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/synonyms", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchSynonymsResponse`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchSynonymsResponse`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +/// Create or update a synonym to define search terms that should be considered equivalent. +pub async fn upsert_search_synonym(configuration: &configuration::Configuration, params: UpsertSearchSynonymParams) -> Result> { + + let uri_str = format!("{}/collections/{collectionName}/synonyms/{synonymId}", configuration.base_path, collectionName=crate::apis::urlencode(params.collection_name), synonymId=crate::apis::urlencode(params.synonym_id)); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = apikey.key.clone(); + let value = match apikey.prefix { + Some(ref prefix) => format!("{} {}", prefix, key), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.search_synonym_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SearchSynonym`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SearchSynonym`")))), + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + diff --git a/typesense_codegen/src/lib.rs b/typesense_codegen/src/lib.rs index 4c8b05d..e152062 100644 --- a/typesense_codegen/src/lib.rs +++ b/typesense_codegen/src/lib.rs @@ -1,5 +1,11 @@ -#[macro_use] -extern crate serde_derive; +#![allow(unused_imports)] +#![allow(clippy::too_many_arguments)] + +extern crate serde_repr; +extern crate serde; +extern crate serde_json; +extern crate url; +extern crate reqwest; pub mod apis; pub mod models; diff --git a/typesense_codegen/src/models/analytics_event_create_response.rs b/typesense_codegen/src/models/analytics_event_create_response.rs new file mode 100644 index 0000000..f3f37ca --- /dev/null +++ b/typesense_codegen/src/models/analytics_event_create_response.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsEventCreateResponse { + #[serde(rename = "ok")] + pub ok: bool, +} + +impl AnalyticsEventCreateResponse { + pub fn new(ok: bool) -> AnalyticsEventCreateResponse { + AnalyticsEventCreateResponse { + ok, + } + } +} + diff --git a/typesense_codegen/src/models/analytics_event_create_schema.rs b/typesense_codegen/src/models/analytics_event_create_schema.rs new file mode 100644 index 0000000..ff08423 --- /dev/null +++ b/typesense_codegen/src/models/analytics_event_create_schema.rs @@ -0,0 +1,33 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsEventCreateSchema { + #[serde(rename = "type")] + pub r#type: String, + #[serde(rename = "name")] + pub name: String, + #[serde(rename = "data")] + pub data: serde_json::Value, +} + +impl AnalyticsEventCreateSchema { + pub fn new(r#type: String, name: String, data: serde_json::Value) -> AnalyticsEventCreateSchema { + AnalyticsEventCreateSchema { + r#type, + name, + data, + } + } +} + diff --git a/typesense_codegen/src/models/analytics_rule_delete_response.rs b/typesense_codegen/src/models/analytics_rule_delete_response.rs new file mode 100644 index 0000000..db39d65 --- /dev/null +++ b/typesense_codegen/src/models/analytics_rule_delete_response.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsRuleDeleteResponse { + #[serde(rename = "name")] + pub name: String, +} + +impl AnalyticsRuleDeleteResponse { + pub fn new(name: String) -> AnalyticsRuleDeleteResponse { + AnalyticsRuleDeleteResponse { + name, + } + } +} + diff --git a/typesense_codegen/src/models/analytics_rule_parameters.rs b/typesense_codegen/src/models/analytics_rule_parameters.rs index 32b4de4..8973e98 100644 --- a/typesense_codegen/src/models/analytics_rule_parameters.rs +++ b/typesense_codegen/src/models/analytics_rule_parameters.rs @@ -3,31 +3,34 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsRuleParameters { #[serde(rename = "source")] - pub source: Box, + pub source: Box, #[serde(rename = "destination")] - pub destination: Box, - #[serde(rename = "limit")] - pub limit: i32, + pub destination: Box, + #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] + pub limit: Option, + #[serde(rename = "expand_query", skip_serializing_if = "Option::is_none")] + pub expand_query: Option, } impl AnalyticsRuleParameters { - pub fn new( - source: crate::models::AnalyticsRuleParametersSource, - destination: crate::models::AnalyticsRuleParametersDestination, - limit: i32, - ) -> AnalyticsRuleParameters { + pub fn new(source: models::AnalyticsRuleParametersSource, destination: models::AnalyticsRuleParametersDestination) -> AnalyticsRuleParameters { AnalyticsRuleParameters { source: Box::new(source), destination: Box::new(destination), - limit, + limit: None, + expand_query: None, } } } + diff --git a/typesense_codegen/src/models/analytics_rule_parameters_destination.rs b/typesense_codegen/src/models/analytics_rule_parameters_destination.rs index b713af8..73d40ed 100644 --- a/typesense_codegen/src/models/analytics_rule_parameters_destination.rs +++ b/typesense_codegen/src/models/analytics_rule_parameters_destination.rs @@ -3,19 +3,28 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsRuleParametersDestination { - #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] - pub collection: Option, + #[serde(rename = "collection")] + pub collection: String, + #[serde(rename = "counter_field", skip_serializing_if = "Option::is_none")] + pub counter_field: Option, } impl AnalyticsRuleParametersDestination { - pub fn new() -> AnalyticsRuleParametersDestination { - AnalyticsRuleParametersDestination { collection: None } + pub fn new(collection: String) -> AnalyticsRuleParametersDestination { + AnalyticsRuleParametersDestination { + collection, + counter_field: None, + } } } + diff --git a/typesense_codegen/src/models/analytics_rule_parameters_source.rs b/typesense_codegen/src/models/analytics_rule_parameters_source.rs index ae055fa..01a3c53 100644 --- a/typesense_codegen/src/models/analytics_rule_parameters_source.rs +++ b/typesense_codegen/src/models/analytics_rule_parameters_source.rs @@ -3,19 +3,28 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsRuleParametersSource { - #[serde(rename = "collections", skip_serializing_if = "Option::is_none")] - pub collections: Option>, + #[serde(rename = "collections")] + pub collections: Vec, + #[serde(rename = "events", skip_serializing_if = "Option::is_none")] + pub events: Option>, } impl AnalyticsRuleParametersSource { - pub fn new() -> AnalyticsRuleParametersSource { - AnalyticsRuleParametersSource { collections: None } + pub fn new(collections: Vec) -> AnalyticsRuleParametersSource { + AnalyticsRuleParametersSource { + collections, + events: None, + } } } + diff --git a/typesense_codegen/src/models/analytics_rule_parameters_source_events_inner.rs b/typesense_codegen/src/models/analytics_rule_parameters_source_events_inner.rs new file mode 100644 index 0000000..083e6d2 --- /dev/null +++ b/typesense_codegen/src/models/analytics_rule_parameters_source_events_inner.rs @@ -0,0 +1,33 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsRuleParametersSourceEventsInner { + #[serde(rename = "type")] + pub r#type: String, + #[serde(rename = "weight")] + pub weight: f32, + #[serde(rename = "name")] + pub name: String, +} + +impl AnalyticsRuleParametersSourceEventsInner { + pub fn new(r#type: String, weight: f32, name: String) -> AnalyticsRuleParametersSourceEventsInner { + AnalyticsRuleParametersSourceEventsInner { + r#type, + weight, + name, + } + } +} + diff --git a/typesense_codegen/src/models/analytics_rule_schema.rs b/typesense_codegen/src/models/analytics_rule_schema.rs index 4d9c266..6e5d2e2 100644 --- a/typesense_codegen/src/models/analytics_rule_schema.rs +++ b/typesense_codegen/src/models/analytics_rule_schema.rs @@ -3,31 +3,47 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsRuleSchema { - #[serde(rename = "name")] - pub name: String, #[serde(rename = "type")] - pub r#type: String, + pub r#type: Type, #[serde(rename = "params")] - pub params: Box, + pub params: Box, + #[serde(rename = "name")] + pub name: String, } impl AnalyticsRuleSchema { - pub fn new( - name: String, - r#type: String, - params: crate::models::AnalyticsRuleParameters, - ) -> AnalyticsRuleSchema { + pub fn new(r#type: Type, params: models::AnalyticsRuleParameters, name: String) -> AnalyticsRuleSchema { AnalyticsRuleSchema { - name, r#type, params: Box::new(params), + name, } } } +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Type { + #[serde(rename = "popular_queries")] + PopularQueries, + #[serde(rename = "nohits_queries")] + NohitsQueries, + #[serde(rename = "counter")] + Counter, +} + +impl Default for Type { + fn default() -> Type { + Self::PopularQueries + } +} + diff --git a/typesense_codegen/src/models/analytics_rule_upsert_schema.rs b/typesense_codegen/src/models/analytics_rule_upsert_schema.rs new file mode 100644 index 0000000..f4a31d7 --- /dev/null +++ b/typesense_codegen/src/models/analytics_rule_upsert_schema.rs @@ -0,0 +1,46 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsRuleUpsertSchema { + #[serde(rename = "type")] + pub r#type: Type, + #[serde(rename = "params")] + pub params: Box, +} + +impl AnalyticsRuleUpsertSchema { + pub fn new(r#type: Type, params: models::AnalyticsRuleParameters) -> AnalyticsRuleUpsertSchema { + AnalyticsRuleUpsertSchema { + r#type, + params: Box::new(params), + } + } +} +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Type { + #[serde(rename = "popular_queries")] + PopularQueries, + #[serde(rename = "nohits_queries")] + NohitsQueries, + #[serde(rename = "counter")] + Counter, +} + +impl Default for Type { + fn default() -> Type { + Self::PopularQueries + } +} + diff --git a/typesense_codegen/src/models/analytics_rules_retrieve_schema.rs b/typesense_codegen/src/models/analytics_rules_retrieve_schema.rs index ed32555..f55a63c 100644 --- a/typesense_codegen/src/models/analytics_rules_retrieve_schema.rs +++ b/typesense_codegen/src/models/analytics_rules_retrieve_schema.rs @@ -3,19 +3,25 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalyticsRulesRetrieveSchema { #[serde(rename = "rules", skip_serializing_if = "Option::is_none")] - pub rules: Option>, + pub rules: Option>, } impl AnalyticsRulesRetrieveSchema { pub fn new() -> AnalyticsRulesRetrieveSchema { - AnalyticsRulesRetrieveSchema { rules: None } + AnalyticsRulesRetrieveSchema { + rules: None, + } } } + diff --git a/typesense_codegen/src/models/api_key.rs b/typesense_codegen/src/models/api_key.rs index 7de6d81..687614c 100644 --- a/typesense_codegen/src/models/api_key.rs +++ b/typesense_codegen/src/models/api_key.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKey { #[serde(rename = "value", skip_serializing_if = "Option::is_none")] @@ -39,3 +42,4 @@ impl ApiKey { } } } + diff --git a/typesense_codegen/src/models/api_key_delete_response.rs b/typesense_codegen/src/models/api_key_delete_response.rs new file mode 100644 index 0000000..8eb776a --- /dev/null +++ b/typesense_codegen/src/models/api_key_delete_response.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ApiKeyDeleteResponse { + /// The id of the API key that was deleted + #[serde(rename = "id")] + pub id: i64, +} + +impl ApiKeyDeleteResponse { + pub fn new(id: i64) -> ApiKeyDeleteResponse { + ApiKeyDeleteResponse { + id, + } + } +} + diff --git a/typesense_codegen/src/models/api_key_schema.rs b/typesense_codegen/src/models/api_key_schema.rs index 2f6cb2b..5d2922a 100644 --- a/typesense_codegen/src/models/api_key_schema.rs +++ b/typesense_codegen/src/models/api_key_schema.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKeySchema { #[serde(rename = "value", skip_serializing_if = "Option::is_none")] @@ -23,11 +26,7 @@ pub struct ApiKeySchema { } impl ApiKeySchema { - pub fn new( - description: String, - actions: Vec, - collections: Vec, - ) -> ApiKeySchema { + pub fn new(description: String, actions: Vec, collections: Vec) -> ApiKeySchema { ApiKeySchema { value: None, description, @@ -37,3 +36,4 @@ impl ApiKeySchema { } } } + diff --git a/typesense_codegen/src/models/api_keys_response.rs b/typesense_codegen/src/models/api_keys_response.rs index f523a98..71b3d28 100644 --- a/typesense_codegen/src/models/api_keys_response.rs +++ b/typesense_codegen/src/models/api_keys_response.rs @@ -3,19 +3,25 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKeysResponse { #[serde(rename = "keys")] - pub keys: Vec, + pub keys: Vec, } impl ApiKeysResponse { - pub fn new(keys: Vec) -> ApiKeysResponse { - ApiKeysResponse { keys } + pub fn new(keys: Vec) -> ApiKeysResponse { + ApiKeysResponse { + keys, + } } } + diff --git a/typesense_codegen/src/models/api_response.rs b/typesense_codegen/src/models/api_response.rs index 691ea49..42e90ba 100644 --- a/typesense_codegen/src/models/api_response.rs +++ b/typesense_codegen/src/models/api_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiResponse { #[serde(rename = "message")] @@ -16,6 +19,9 @@ pub struct ApiResponse { impl ApiResponse { pub fn new(message: String) -> ApiResponse { - ApiResponse { message } + ApiResponse { + message, + } } } + diff --git a/typesense_codegen/src/models/api_stats_response.rs b/typesense_codegen/src/models/api_stats_response.rs new file mode 100644 index 0000000..9daf9bb --- /dev/null +++ b/typesense_codegen/src/models/api_stats_response.rs @@ -0,0 +1,63 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ApiStatsResponse { + #[serde(rename = "delete_latency_ms", skip_serializing_if = "Option::is_none")] + pub delete_latency_ms: Option, + #[serde(rename = "delete_requests_per_second", skip_serializing_if = "Option::is_none")] + pub delete_requests_per_second: Option, + #[serde(rename = "import_latency_ms", skip_serializing_if = "Option::is_none")] + pub import_latency_ms: Option, + #[serde(rename = "import_requests_per_second", skip_serializing_if = "Option::is_none")] + pub import_requests_per_second: Option, + #[serde(rename = "latency_ms", skip_serializing_if = "Option::is_none")] + pub latency_ms: Option, + #[serde(rename = "overloaded_requests_per_second", skip_serializing_if = "Option::is_none")] + pub overloaded_requests_per_second: Option, + #[serde(rename = "pending_write_batches", skip_serializing_if = "Option::is_none")] + pub pending_write_batches: Option, + #[serde(rename = "requests_per_second", skip_serializing_if = "Option::is_none")] + pub requests_per_second: Option, + #[serde(rename = "search_latency_ms", skip_serializing_if = "Option::is_none")] + pub search_latency_ms: Option, + #[serde(rename = "search_requests_per_second", skip_serializing_if = "Option::is_none")] + pub search_requests_per_second: Option, + #[serde(rename = "total_requests_per_second", skip_serializing_if = "Option::is_none")] + pub total_requests_per_second: Option, + #[serde(rename = "write_latency_ms", skip_serializing_if = "Option::is_none")] + pub write_latency_ms: Option, + #[serde(rename = "write_requests_per_second", skip_serializing_if = "Option::is_none")] + pub write_requests_per_second: Option, +} + +impl ApiStatsResponse { + pub fn new() -> ApiStatsResponse { + ApiStatsResponse { + delete_latency_ms: None, + delete_requests_per_second: None, + import_latency_ms: None, + import_requests_per_second: None, + latency_ms: None, + overloaded_requests_per_second: None, + pending_write_batches: None, + requests_per_second: None, + search_latency_ms: None, + search_requests_per_second: None, + total_requests_per_second: None, + write_latency_ms: None, + write_requests_per_second: None, + } + } +} + diff --git a/typesense_codegen/src/models/collection_alias.rs b/typesense_codegen/src/models/collection_alias.rs index b5ab76e..d25ff0c 100644 --- a/typesense_codegen/src/models/collection_alias.rs +++ b/typesense_codegen/src/models/collection_alias.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionAlias { /// Name of the collection alias @@ -26,3 +29,4 @@ impl CollectionAlias { } } } + diff --git a/typesense_codegen/src/models/collection_alias_schema.rs b/typesense_codegen/src/models/collection_alias_schema.rs index 279e88f..5c3c15f 100644 --- a/typesense_codegen/src/models/collection_alias_schema.rs +++ b/typesense_codegen/src/models/collection_alias_schema.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionAliasSchema { /// Name of the collection you wish to map the alias to @@ -17,6 +20,9 @@ pub struct CollectionAliasSchema { impl CollectionAliasSchema { pub fn new(collection_name: String) -> CollectionAliasSchema { - CollectionAliasSchema { collection_name } + CollectionAliasSchema { + collection_name, + } } } + diff --git a/typesense_codegen/src/models/collection_aliases_response.rs b/typesense_codegen/src/models/collection_aliases_response.rs index 2bc9560..8529794 100644 --- a/typesense_codegen/src/models/collection_aliases_response.rs +++ b/typesense_codegen/src/models/collection_aliases_response.rs @@ -3,19 +3,25 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionAliasesResponse { #[serde(rename = "aliases")] - pub aliases: Vec, + pub aliases: Vec, } impl CollectionAliasesResponse { - pub fn new(aliases: Vec) -> CollectionAliasesResponse { - CollectionAliasesResponse { aliases } + pub fn new(aliases: Vec) -> CollectionAliasesResponse { + CollectionAliasesResponse { + aliases, + } } } + diff --git a/typesense_codegen/src/models/collection_response.rs b/typesense_codegen/src/models/collection_response.rs index 8676b81..4c56f37 100644 --- a/typesense_codegen/src/models/collection_response.rs +++ b/typesense_codegen/src/models/collection_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionResponse { /// Name of the collection @@ -15,25 +18,21 @@ pub struct CollectionResponse { pub name: String, /// A list of fields for querying, filtering and faceting #[serde(rename = "fields")] - pub fields: Vec, + pub fields: Vec, /// The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. - #[serde( - rename = "default_sorting_field", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "default_sorting_field", skip_serializing_if = "Option::is_none")] pub default_sorting_field: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, /// Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. - #[serde( - rename = "enable_nested_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "enable_nested_fields", skip_serializing_if = "Option::is_none")] pub enable_nested_fields: Option, - /// List of symbols or special characters to be indexed. + /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, + #[serde(rename = "voice_query_model", skip_serializing_if = "Option::is_none")] + pub voice_query_model: Option>, /// Number of documents in the collection #[serde(rename = "num_documents")] pub num_documents: i64, @@ -43,12 +42,7 @@ pub struct CollectionResponse { } impl CollectionResponse { - pub fn new( - name: String, - fields: Vec, - num_documents: i64, - created_at: i64, - ) -> CollectionResponse { + pub fn new(name: String, fields: Vec, num_documents: i64, created_at: i64) -> CollectionResponse { CollectionResponse { name, fields, @@ -56,8 +50,10 @@ impl CollectionResponse { token_separators: None, enable_nested_fields: None, symbols_to_index: None, + voice_query_model: None, num_documents, created_at, } } } + diff --git a/typesense_codegen/src/models/collection_schema.rs b/typesense_codegen/src/models/collection_schema.rs index 5a373f6..c3375ef 100644 --- a/typesense_codegen/src/models/collection_schema.rs +++ b/typesense_codegen/src/models/collection_schema.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionSchema { /// Name of the collection @@ -15,29 +18,25 @@ pub struct CollectionSchema { pub name: String, /// A list of fields for querying, filtering and faceting #[serde(rename = "fields")] - pub fields: Vec, + pub fields: Vec, /// The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. - #[serde( - rename = "default_sorting_field", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "default_sorting_field", skip_serializing_if = "Option::is_none")] pub default_sorting_field: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, /// Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. - #[serde( - rename = "enable_nested_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "enable_nested_fields", skip_serializing_if = "Option::is_none")] pub enable_nested_fields: Option, - /// List of symbols or special characters to be indexed. + /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, + #[serde(rename = "voice_query_model", skip_serializing_if = "Option::is_none")] + pub voice_query_model: Option>, } impl CollectionSchema { - pub fn new(name: String, fields: Vec) -> CollectionSchema { + pub fn new(name: String, fields: Vec) -> CollectionSchema { CollectionSchema { name, fields, @@ -45,6 +44,8 @@ impl CollectionSchema { token_separators: None, enable_nested_fields: None, symbols_to_index: None, + voice_query_model: None, } } } + diff --git a/typesense_codegen/src/models/collection_update_schema.rs b/typesense_codegen/src/models/collection_update_schema.rs index f4a4078..672fe56 100644 --- a/typesense_codegen/src/models/collection_update_schema.rs +++ b/typesense_codegen/src/models/collection_update_schema.rs @@ -3,20 +3,26 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionUpdateSchema { /// A list of fields for querying, filtering and faceting #[serde(rename = "fields")] - pub fields: Vec, + pub fields: Vec, } impl CollectionUpdateSchema { - pub fn new(fields: Vec) -> CollectionUpdateSchema { - CollectionUpdateSchema { fields } + pub fn new(fields: Vec) -> CollectionUpdateSchema { + CollectionUpdateSchema { + fields, + } } } + diff --git a/typesense_codegen/src/models/conversation_model_create_schema.rs b/typesense_codegen/src/models/conversation_model_create_schema.rs new file mode 100644 index 0000000..3ae1f37 --- /dev/null +++ b/typesense_codegen/src/models/conversation_model_create_schema.rs @@ -0,0 +1,60 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ConversationModelCreateSchema { + /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + #[serde(rename = "id", skip_serializing_if = "Option::is_none")] + pub id: Option, + /// Name of the LLM model offered by OpenAI, Cloudflare or vLLM + #[serde(rename = "model_name")] + pub model_name: String, + /// The LLM service's API Key + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Typesense collection that stores the historical conversations + #[serde(rename = "history_collection")] + pub history_collection: String, + /// LLM service's account ID (only applicable for Cloudflare) + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// The system prompt that contains special instructions to the LLM + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] + pub ttl: Option, + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + #[serde(rename = "max_bytes")] + pub max_bytes: i32, + /// URL of vLLM service + #[serde(rename = "vllm_url", skip_serializing_if = "Option::is_none")] + pub vllm_url: Option, +} + +impl ConversationModelCreateSchema { + pub fn new(model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelCreateSchema { + ConversationModelCreateSchema { + id: None, + model_name, + api_key: None, + history_collection, + account_id: None, + system_prompt: None, + ttl: None, + max_bytes, + vllm_url: None, + } + } +} + diff --git a/typesense_codegen/src/models/conversation_model_schema.rs b/typesense_codegen/src/models/conversation_model_schema.rs new file mode 100644 index 0000000..271c58d --- /dev/null +++ b/typesense_codegen/src/models/conversation_model_schema.rs @@ -0,0 +1,60 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ConversationModelSchema { + /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + #[serde(rename = "id")] + pub id: String, + /// Name of the LLM model offered by OpenAI, Cloudflare or vLLM + #[serde(rename = "model_name")] + pub model_name: String, + /// The LLM service's API Key + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Typesense collection that stores the historical conversations + #[serde(rename = "history_collection")] + pub history_collection: String, + /// LLM service's account ID (only applicable for Cloudflare) + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// The system prompt that contains special instructions to the LLM + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] + pub ttl: Option, + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + #[serde(rename = "max_bytes")] + pub max_bytes: i32, + /// URL of vLLM service + #[serde(rename = "vllm_url", skip_serializing_if = "Option::is_none")] + pub vllm_url: Option, +} + +impl ConversationModelSchema { + pub fn new(id: String, model_name: String, history_collection: String, max_bytes: i32) -> ConversationModelSchema { + ConversationModelSchema { + id, + model_name, + api_key: None, + history_collection, + account_id: None, + system_prompt: None, + ttl: None, + max_bytes, + vllm_url: None, + } + } +} + diff --git a/typesense_codegen/src/models/conversation_model_update_schema.rs b/typesense_codegen/src/models/conversation_model_update_schema.rs new file mode 100644 index 0000000..1a05887 --- /dev/null +++ b/typesense_codegen/src/models/conversation_model_update_schema.rs @@ -0,0 +1,60 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ConversationModelUpdateSchema { + /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + #[serde(rename = "id", skip_serializing_if = "Option::is_none")] + pub id: Option, + /// Name of the LLM model offered by OpenAI, Cloudflare or vLLM + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, + /// The LLM service's API Key + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Typesense collection that stores the historical conversations + #[serde(rename = "history_collection", skip_serializing_if = "Option::is_none")] + pub history_collection: Option, + /// LLM service's account ID (only applicable for Cloudflare) + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// The system prompt that contains special instructions to the LLM + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] + pub ttl: Option, + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] + pub max_bytes: Option, + /// URL of vLLM service + #[serde(rename = "vllm_url", skip_serializing_if = "Option::is_none")] + pub vllm_url: Option, +} + +impl ConversationModelUpdateSchema { + pub fn new() -> ConversationModelUpdateSchema { + ConversationModelUpdateSchema { + id: None, + model_name: None, + api_key: None, + history_collection: None, + account_id: None, + system_prompt: None, + ttl: None, + max_bytes: None, + vllm_url: None, + } + } +} + diff --git a/typesense_codegen/src/models/debug_200_response.rs b/typesense_codegen/src/models/debug_200_response.rs index 365fc42..3b1cf17 100644 --- a/typesense_codegen/src/models/debug_200_response.rs +++ b/typesense_codegen/src/models/debug_200_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct Debug200Response { #[serde(rename = "version", skip_serializing_if = "Option::is_none")] @@ -16,6 +19,9 @@ pub struct Debug200Response { impl Debug200Response { pub fn new() -> Debug200Response { - Debug200Response { version: None } + Debug200Response { + version: None, + } } } + diff --git a/typesense_codegen/src/models/delete_documents_200_response.rs b/typesense_codegen/src/models/delete_documents_200_response.rs index a509291..03e22e6 100644 --- a/typesense_codegen/src/models/delete_documents_200_response.rs +++ b/typesense_codegen/src/models/delete_documents_200_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct DeleteDocuments200Response { #[serde(rename = "num_deleted")] @@ -16,6 +19,9 @@ pub struct DeleteDocuments200Response { impl DeleteDocuments200Response { pub fn new(num_deleted: i32) -> DeleteDocuments200Response { - DeleteDocuments200Response { num_deleted } + DeleteDocuments200Response { + num_deleted, + } } } + diff --git a/typesense_codegen/src/models/delete_documents_delete_documents_parameters_parameter.rs b/typesense_codegen/src/models/delete_documents_delete_documents_parameters_parameter.rs index 722bdc4..71531e2 100644 --- a/typesense_codegen/src/models/delete_documents_delete_documents_parameters_parameter.rs +++ b/typesense_codegen/src/models/delete_documents_delete_documents_parameters_parameter.rs @@ -3,25 +3,36 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct DeleteDocumentsDeleteDocumentsParametersParameter { - #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] - pub filter_by: Option, + #[serde(rename = "filter_by")] + pub filter_by: String, /// Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] pub batch_size: Option, + #[serde(rename = "ignore_not_found", skip_serializing_if = "Option::is_none")] + pub ignore_not_found: Option, + /// When true, removes all documents from the collection while preserving the collection and its schema. + #[serde(rename = "truncate", skip_serializing_if = "Option::is_none")] + pub truncate: Option, } impl DeleteDocumentsDeleteDocumentsParametersParameter { - pub fn new() -> DeleteDocumentsDeleteDocumentsParametersParameter { + pub fn new(filter_by: String) -> DeleteDocumentsDeleteDocumentsParametersParameter { DeleteDocumentsDeleteDocumentsParametersParameter { - filter_by: None, + filter_by, batch_size: None, + ignore_not_found: None, + truncate: None, } } } + diff --git a/typesense_codegen/src/models/delete_documents_parameters.rs b/typesense_codegen/src/models/delete_documents_parameters.rs new file mode 100644 index 0000000..1833431 --- /dev/null +++ b/typesense_codegen/src/models/delete_documents_parameters.rs @@ -0,0 +1,38 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct DeleteDocumentsParameters { + #[serde(rename = "filter_by")] + pub filter_by: String, + /// Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. + #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] + pub batch_size: Option, + #[serde(rename = "ignore_not_found", skip_serializing_if = "Option::is_none")] + pub ignore_not_found: Option, + /// When true, removes all documents from the collection while preserving the collection and its schema. + #[serde(rename = "truncate", skip_serializing_if = "Option::is_none")] + pub truncate: Option, +} + +impl DeleteDocumentsParameters { + pub fn new(filter_by: String) -> DeleteDocumentsParameters { + DeleteDocumentsParameters { + filter_by, + batch_size: None, + ignore_not_found: None, + truncate: None, + } + } +} + diff --git a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs new file mode 100644 index 0000000..716b6e7 --- /dev/null +++ b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct DeleteStopwordsSet200Response { + #[serde(rename = "id")] + pub id: String, +} + +impl DeleteStopwordsSet200Response { + pub fn new(id: String) -> DeleteStopwordsSet200Response { + DeleteStopwordsSet200Response { + id, + } + } +} + diff --git a/typesense_codegen/src/models/dirty_values.rs b/typesense_codegen/src/models/dirty_values.rs new file mode 100644 index 0000000..ab01406 --- /dev/null +++ b/typesense_codegen/src/models/dirty_values.rs @@ -0,0 +1,44 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum DirtyValues { + #[serde(rename = "coerce_or_reject")] + CoerceOrReject, + #[serde(rename = "coerce_or_drop")] + CoerceOrDrop, + #[serde(rename = "drop")] + Drop, + #[serde(rename = "reject")] + Reject, + +} + +impl std::fmt::Display for DirtyValues { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::CoerceOrReject => write!(f, "coerce_or_reject"), + Self::CoerceOrDrop => write!(f, "coerce_or_drop"), + Self::Drop => write!(f, "drop"), + Self::Reject => write!(f, "reject"), + } + } +} + +impl Default for DirtyValues { + fn default() -> DirtyValues { + Self::CoerceOrReject + } +} + diff --git a/typesense_codegen/src/models/document_index_parameters.rs b/typesense_codegen/src/models/document_index_parameters.rs new file mode 100644 index 0000000..339c8f3 --- /dev/null +++ b/typesense_codegen/src/models/document_index_parameters.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct DocumentIndexParameters { + #[serde(rename = "dirty_values", skip_serializing_if = "Option::is_none")] + pub dirty_values: Option, +} + +impl DocumentIndexParameters { + pub fn new() -> DocumentIndexParameters { + DocumentIndexParameters { + dirty_values: None, + } + } +} + diff --git a/typesense_codegen/src/models/drop_tokens_mode.rs b/typesense_codegen/src/models/drop_tokens_mode.rs new file mode 100644 index 0000000..79ced42 --- /dev/null +++ b/typesense_codegen/src/models/drop_tokens_mode.rs @@ -0,0 +1,42 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// DropTokensMode : Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries upto 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left +/// Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries upto 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum DropTokensMode { + #[serde(rename = "right_to_left")] + RightToLeft, + #[serde(rename = "left_to_right")] + LeftToRight, + #[serde(rename = "both_sides:3")] + BothSidesColon3, + +} + +impl std::fmt::Display for DropTokensMode { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::RightToLeft => write!(f, "right_to_left"), + Self::LeftToRight => write!(f, "left_to_right"), + Self::BothSidesColon3 => write!(f, "both_sides:3"), + } + } +} + +impl Default for DropTokensMode { + fn default() -> DropTokensMode { + Self::RightToLeft + } +} + diff --git a/typesense_codegen/src/models/error_response.rs b/typesense_codegen/src/models/error_response.rs index ec2ef82..45c3487 100644 --- a/typesense_codegen/src/models/error_response.rs +++ b/typesense_codegen/src/models/error_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponse { #[serde(rename = "message", skip_serializing_if = "Option::is_none")] @@ -16,6 +19,9 @@ pub struct ErrorResponse { impl ErrorResponse { pub fn new() -> ErrorResponse { - ErrorResponse { message: None } + ErrorResponse { + message: None, + } } } + diff --git a/typesense_codegen/src/models/export_documents_export_documents_parameters_parameter.rs b/typesense_codegen/src/models/export_documents_export_documents_parameters_parameter.rs index c798028..3d35251 100644 --- a/typesense_codegen/src/models/export_documents_export_documents_parameters_parameter.rs +++ b/typesense_codegen/src/models/export_documents_export_documents_parameters_parameter.rs @@ -3,33 +3,34 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportDocumentsExportDocumentsParametersParameter { /// Filter conditions for refining your search results. Separate multiple conditions with &&. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, /// List of fields from the document to include in the search result - #[serde(rename = "include_fields")] - pub include_fields: String, + #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] + pub include_fields: Option, /// List of fields from the document to exclude in the search result - #[serde(rename = "exclude_fields")] - pub exclude_fields: String, + #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] + pub exclude_fields: Option, } impl ExportDocumentsExportDocumentsParametersParameter { - pub fn new( - include_fields: String, - exclude_fields: String, - ) -> ExportDocumentsExportDocumentsParametersParameter { + pub fn new() -> ExportDocumentsExportDocumentsParametersParameter { ExportDocumentsExportDocumentsParametersParameter { filter_by: None, - include_fields, - exclude_fields, + include_fields: None, + exclude_fields: None, } } } + diff --git a/typesense_codegen/src/models/export_documents_parameters.rs b/typesense_codegen/src/models/export_documents_parameters.rs new file mode 100644 index 0000000..f6c8384 --- /dev/null +++ b/typesense_codegen/src/models/export_documents_parameters.rs @@ -0,0 +1,36 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ExportDocumentsParameters { + /// Filter conditions for refining your search results. Separate multiple conditions with &&. + #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] + pub filter_by: Option, + /// List of fields from the document to include in the search result + #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] + pub include_fields: Option, + /// List of fields from the document to exclude in the search result + #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] + pub exclude_fields: Option, +} + +impl ExportDocumentsParameters { + pub fn new() -> ExportDocumentsParameters { + ExportDocumentsParameters { + filter_by: None, + include_fields: None, + exclude_fields: None, + } + } +} + diff --git a/typesense_codegen/src/models/facet_counts.rs b/typesense_codegen/src/models/facet_counts.rs index 3e0a930..4735264 100644 --- a/typesense_codegen/src/models/facet_counts.rs +++ b/typesense_codegen/src/models/facet_counts.rs @@ -3,19 +3,22 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FacetCounts { #[serde(rename = "counts", skip_serializing_if = "Option::is_none")] - pub counts: Option>, + pub counts: Option>, #[serde(rename = "field_name", skip_serializing_if = "Option::is_none")] pub field_name: Option, #[serde(rename = "stats", skip_serializing_if = "Option::is_none")] - pub stats: Option>, + pub stats: Option>, } impl FacetCounts { @@ -27,3 +30,4 @@ impl FacetCounts { } } } + diff --git a/typesense_codegen/src/models/facet_counts_counts_inner.rs b/typesense_codegen/src/models/facet_counts_counts_inner.rs index a4dca2e..0ff18c9 100644 --- a/typesense_codegen/src/models/facet_counts_counts_inner.rs +++ b/typesense_codegen/src/models/facet_counts_counts_inner.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FacetCountsCountsInner { #[serde(rename = "count", skip_serializing_if = "Option::is_none")] @@ -16,6 +19,8 @@ pub struct FacetCountsCountsInner { pub highlighted: Option, #[serde(rename = "value", skip_serializing_if = "Option::is_none")] pub value: Option, + #[serde(rename = "parent", skip_serializing_if = "Option::is_none")] + pub parent: Option, } impl FacetCountsCountsInner { @@ -24,6 +29,8 @@ impl FacetCountsCountsInner { count: None, highlighted: None, value: None, + parent: None, } } } + diff --git a/typesense_codegen/src/models/facet_counts_stats.rs b/typesense_codegen/src/models/facet_counts_stats.rs index 142d2ce..25d71ab 100644 --- a/typesense_codegen/src/models/facet_counts_stats.rs +++ b/typesense_codegen/src/models/facet_counts_stats.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FacetCountsStats { #[serde(rename = "max", skip_serializing_if = "Option::is_none")] @@ -33,3 +36,4 @@ impl FacetCountsStats { } } } + diff --git a/typesense_codegen/src/models/field.rs b/typesense_codegen/src/models/field.rs index 454ae90..5e260bc 100644 --- a/typesense_codegen/src/models/field.rs +++ b/typesense_codegen/src/models/field.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct Field { #[serde(rename = "name")] @@ -26,12 +29,36 @@ pub struct Field { pub sort: Option, #[serde(rename = "infix", skip_serializing_if = "Option::is_none")] pub infix: Option, + /// Name of a field in another collection that should be linked to this collection so that it can be joined during query. + #[serde(rename = "reference", skip_serializing_if = "Option::is_none")] + pub reference: Option, #[serde(rename = "num_dim", skip_serializing_if = "Option::is_none")] pub num_dim: Option, #[serde(rename = "drop", skip_serializing_if = "Option::is_none")] pub drop: Option, + /// When set to false, the field value will not be stored on disk. Default: true. + #[serde(rename = "store", skip_serializing_if = "Option::is_none")] + pub store: Option, + /// The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. + #[serde(rename = "vec_dist", skip_serializing_if = "Option::is_none")] + pub vec_dist: Option, + /// Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. + #[serde(rename = "range_index", skip_serializing_if = "Option::is_none")] + pub range_index: Option, + /// Values are stemmed before indexing in-memory. Default: false. + #[serde(rename = "stem", skip_serializing_if = "Option::is_none")] + pub stem: Option, + /// Name of the stemming dictionary to use for this field + #[serde(rename = "stem_dictionary", skip_serializing_if = "Option::is_none")] + pub stem_dictionary: Option, + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] + pub token_separators: Option>, + /// List of symbols or special characters to be indexed. + #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] + pub symbols_to_index: Option>, #[serde(rename = "embed", skip_serializing_if = "Option::is_none")] - pub embed: Option>, + pub embed: Option>, } impl Field { @@ -45,9 +72,18 @@ impl Field { locale: None, sort: None, infix: None, + reference: None, num_dim: None, drop: None, + store: None, + vec_dist: None, + range_index: None, + stem: None, + stem_dictionary: None, + token_separators: None, + symbols_to_index: None, embed: None, } } } + diff --git a/typesense_codegen/src/models/field_embed.rs b/typesense_codegen/src/models/field_embed.rs index fcb68e4..92c75cd 100644 --- a/typesense_codegen/src/models/field_embed.rs +++ b/typesense_codegen/src/models/field_embed.rs @@ -3,27 +3,28 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FieldEmbed { #[serde(rename = "from")] pub from: Vec, #[serde(rename = "model_config")] - pub model_config: Box, + pub model_config: Box, } impl FieldEmbed { - pub fn new( - from: Vec, - model_config: crate::models::FieldEmbedModelConfig, - ) -> FieldEmbed { + pub fn new(from: Vec, model_config: models::FieldEmbedModelConfig) -> FieldEmbed { FieldEmbed { from, model_config: Box::new(model_config), } } } + diff --git a/typesense_codegen/src/models/field_embed_model_config.rs b/typesense_codegen/src/models/field_embed_model_config.rs index a7af536..479a253 100644 --- a/typesense_codegen/src/models/field_embed_model_config.rs +++ b/typesense_codegen/src/models/field_embed_model_config.rs @@ -3,25 +3,36 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FieldEmbedModelConfig { #[serde(rename = "model_name")] pub model_name: String, #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] pub api_key: Option, + #[serde(rename = "url", skip_serializing_if = "Option::is_none")] + pub url: Option, #[serde(rename = "access_token", skip_serializing_if = "Option::is_none")] pub access_token: Option, + #[serde(rename = "refresh_token", skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, #[serde(rename = "client_id", skip_serializing_if = "Option::is_none")] pub client_id: Option, #[serde(rename = "client_secret", skip_serializing_if = "Option::is_none")] pub client_secret: Option, #[serde(rename = "project_id", skip_serializing_if = "Option::is_none")] pub project_id: Option, + #[serde(rename = "indexing_prefix", skip_serializing_if = "Option::is_none")] + pub indexing_prefix: Option, + #[serde(rename = "query_prefix", skip_serializing_if = "Option::is_none")] + pub query_prefix: Option, } impl FieldEmbedModelConfig { @@ -29,10 +40,15 @@ impl FieldEmbedModelConfig { FieldEmbedModelConfig { model_name, api_key: None, + url: None, access_token: None, + refresh_token: None, client_id: None, client_secret: None, project_id: None, + indexing_prefix: None, + query_prefix: None, } } } + diff --git a/typesense_codegen/src/models/health_status.rs b/typesense_codegen/src/models/health_status.rs index b33a2ba..f0433ec 100644 --- a/typesense_codegen/src/models/health_status.rs +++ b/typesense_codegen/src/models/health_status.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct HealthStatus { #[serde(rename = "ok")] @@ -16,6 +19,9 @@ pub struct HealthStatus { impl HealthStatus { pub fn new(ok: bool) -> HealthStatus { - HealthStatus { ok } + HealthStatus { + ok, + } } } + diff --git a/typesense_codegen/src/models/import_documents_import_documents_parameters_parameter.rs b/typesense_codegen/src/models/import_documents_import_documents_parameters_parameter.rs index 9dd0edb..321d0ed 100644 --- a/typesense_codegen/src/models/import_documents_import_documents_parameters_parameter.rs +++ b/typesense_codegen/src/models/import_documents_import_documents_parameters_parameter.rs @@ -3,51 +3,41 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ImportDocumentsImportDocumentsParametersParameter { - #[serde(rename = "action", skip_serializing_if = "Option::is_none")] - pub action: Option, #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] pub batch_size: Option, - #[serde(rename = "dirty_values", skip_serializing_if = "Option::is_none")] - pub dirty_values: Option, - #[serde( - rename = "remote_embedding_batch_size", - skip_serializing_if = "Option::is_none" - )] + /// Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. + #[serde(rename = "return_id", skip_serializing_if = "Option::is_none")] + pub return_id: Option, + #[serde(rename = "remote_embedding_batch_size", skip_serializing_if = "Option::is_none")] pub remote_embedding_batch_size: Option, + #[serde(rename = "return_doc", skip_serializing_if = "Option::is_none")] + pub return_doc: Option, + #[serde(rename = "action", skip_serializing_if = "Option::is_none")] + pub action: Option, + #[serde(rename = "dirty_values", skip_serializing_if = "Option::is_none")] + pub dirty_values: Option, } impl ImportDocumentsImportDocumentsParametersParameter { pub fn new() -> ImportDocumentsImportDocumentsParametersParameter { ImportDocumentsImportDocumentsParametersParameter { - action: None, batch_size: None, - dirty_values: None, + return_id: None, remote_embedding_batch_size: None, + return_doc: None, + action: None, + dirty_values: None, } } } -#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] -pub enum DirtyValues { - #[serde(rename = "coerce_or_reject")] - CoerceOrReject, - #[serde(rename = "coerce_or_drop")] - CoerceOrDrop, - #[serde(rename = "drop")] - Drop, - #[serde(rename = "reject")] - Reject, -} - -impl Default for DirtyValues { - fn default() -> DirtyValues { - Self::CoerceOrReject - } -} diff --git a/typesense_codegen/src/models/import_documents_parameters.rs b/typesense_codegen/src/models/import_documents_parameters.rs new file mode 100644 index 0000000..c10e880 --- /dev/null +++ b/typesense_codegen/src/models/import_documents_parameters.rs @@ -0,0 +1,43 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ImportDocumentsParameters { + #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] + pub batch_size: Option, + /// Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. + #[serde(rename = "return_id", skip_serializing_if = "Option::is_none")] + pub return_id: Option, + #[serde(rename = "remote_embedding_batch_size", skip_serializing_if = "Option::is_none")] + pub remote_embedding_batch_size: Option, + #[serde(rename = "return_doc", skip_serializing_if = "Option::is_none")] + pub return_doc: Option, + #[serde(rename = "action", skip_serializing_if = "Option::is_none")] + pub action: Option, + #[serde(rename = "dirty_values", skip_serializing_if = "Option::is_none")] + pub dirty_values: Option, +} + +impl ImportDocumentsParameters { + pub fn new() -> ImportDocumentsParameters { + ImportDocumentsParameters { + batch_size: None, + return_id: None, + remote_embedding_batch_size: None, + return_doc: None, + action: None, + dirty_values: None, + } + } +} + diff --git a/typesense_codegen/src/models/index_action.rs b/typesense_codegen/src/models/index_action.rs new file mode 100644 index 0000000..ab27f00 --- /dev/null +++ b/typesense_codegen/src/models/index_action.rs @@ -0,0 +1,44 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum IndexAction { + #[serde(rename = "create")] + Create, + #[serde(rename = "update")] + Update, + #[serde(rename = "upsert")] + Upsert, + #[serde(rename = "emplace")] + Emplace, + +} + +impl std::fmt::Display for IndexAction { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::Create => write!(f, "create"), + Self::Update => write!(f, "update"), + Self::Upsert => write!(f, "upsert"), + Self::Emplace => write!(f, "emplace"), + } + } +} + +impl Default for IndexAction { + fn default() -> IndexAction { + Self::Create + } +} + diff --git a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs new file mode 100644 index 0000000..e1e3622 --- /dev/null +++ b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ListStemmingDictionaries200Response { + #[serde(rename = "dictionaries", skip_serializing_if = "Option::is_none")] + pub dictionaries: Option>, +} + +impl ListStemmingDictionaries200Response { + pub fn new() -> ListStemmingDictionaries200Response { + ListStemmingDictionaries200Response { + dictionaries: None, + } + } +} + diff --git a/typesense_codegen/src/models/mod.rs b/typesense_codegen/src/models/mod.rs index f8fb452..4af5098 100644 --- a/typesense_codegen/src/models/mod.rs +++ b/typesense_codegen/src/models/mod.rs @@ -1,21 +1,35 @@ +pub mod analytics_event_create_response; +pub use self::analytics_event_create_response::AnalyticsEventCreateResponse; +pub mod analytics_event_create_schema; +pub use self::analytics_event_create_schema::AnalyticsEventCreateSchema; +pub mod analytics_rule_delete_response; +pub use self::analytics_rule_delete_response::AnalyticsRuleDeleteResponse; pub mod analytics_rule_parameters; pub use self::analytics_rule_parameters::AnalyticsRuleParameters; pub mod analytics_rule_parameters_destination; pub use self::analytics_rule_parameters_destination::AnalyticsRuleParametersDestination; pub mod analytics_rule_parameters_source; pub use self::analytics_rule_parameters_source::AnalyticsRuleParametersSource; +pub mod analytics_rule_parameters_source_events_inner; +pub use self::analytics_rule_parameters_source_events_inner::AnalyticsRuleParametersSourceEventsInner; pub mod analytics_rule_schema; pub use self::analytics_rule_schema::AnalyticsRuleSchema; +pub mod analytics_rule_upsert_schema; +pub use self::analytics_rule_upsert_schema::AnalyticsRuleUpsertSchema; pub mod analytics_rules_retrieve_schema; pub use self::analytics_rules_retrieve_schema::AnalyticsRulesRetrieveSchema; pub mod api_key; pub use self::api_key::ApiKey; +pub mod api_key_delete_response; +pub use self::api_key_delete_response::ApiKeyDeleteResponse; pub mod api_key_schema; pub use self::api_key_schema::ApiKeySchema; pub mod api_keys_response; pub use self::api_keys_response::ApiKeysResponse; pub mod api_response; pub use self::api_response::ApiResponse; +pub mod api_stats_response; +pub use self::api_stats_response::ApiStatsResponse; pub mod collection_alias; pub use self::collection_alias::CollectionAlias; pub mod collection_alias_schema; @@ -28,16 +42,30 @@ pub mod collection_schema; pub use self::collection_schema::CollectionSchema; pub mod collection_update_schema; pub use self::collection_update_schema::CollectionUpdateSchema; +pub mod conversation_model_create_schema; +pub use self::conversation_model_create_schema::ConversationModelCreateSchema; +pub mod conversation_model_schema; +pub use self::conversation_model_schema::ConversationModelSchema; +pub mod conversation_model_update_schema; +pub use self::conversation_model_update_schema::ConversationModelUpdateSchema; pub mod debug_200_response; pub use self::debug_200_response::Debug200Response; pub mod delete_documents_200_response; pub use self::delete_documents_200_response::DeleteDocuments200Response; -pub mod delete_documents_delete_documents_parameters_parameter; -pub use self::delete_documents_delete_documents_parameters_parameter::DeleteDocumentsDeleteDocumentsParametersParameter; +pub mod delete_documents_parameters; +pub use self::delete_documents_parameters::DeleteDocumentsParameters; +pub mod delete_stopwords_set_200_response; +pub use self::delete_stopwords_set_200_response::DeleteStopwordsSet200Response; +pub mod dirty_values; +pub use self::dirty_values::DirtyValues; +pub mod document_index_parameters; +pub use self::document_index_parameters::DocumentIndexParameters; +pub mod drop_tokens_mode; +pub use self::drop_tokens_mode::DropTokensMode; pub mod error_response; pub use self::error_response::ErrorResponse; -pub mod export_documents_export_documents_parameters_parameter; -pub use self::export_documents_export_documents_parameters_parameter::ExportDocumentsExportDocumentsParametersParameter; +pub mod export_documents_parameters; +pub use self::export_documents_parameters::ExportDocumentsParameters; pub mod facet_counts; pub use self::facet_counts::FacetCounts; pub mod facet_counts_counts_inner; @@ -52,16 +80,42 @@ pub mod field_embed_model_config; pub use self::field_embed_model_config::FieldEmbedModelConfig; pub mod health_status; pub use self::health_status::HealthStatus; -pub mod import_documents_import_documents_parameters_parameter; -pub use self::import_documents_import_documents_parameters_parameter::ImportDocumentsImportDocumentsParametersParameter; +pub mod import_documents_parameters; +pub use self::import_documents_parameters::ImportDocumentsParameters; +pub mod index_action; +pub use self::index_action::IndexAction; +pub mod list_stemming_dictionaries_200_response; +pub use self::list_stemming_dictionaries_200_response::ListStemmingDictionaries200Response; pub mod multi_search_collection_parameters; pub use self::multi_search_collection_parameters::MultiSearchCollectionParameters; pub mod multi_search_parameters; pub use self::multi_search_parameters::MultiSearchParameters; pub mod multi_search_result; pub use self::multi_search_result::MultiSearchResult; +pub mod multi_search_result_item; +pub use self::multi_search_result_item::MultiSearchResultItem; pub mod multi_search_searches_parameter; pub use self::multi_search_searches_parameter::MultiSearchSearchesParameter; +pub mod nl_search_model_base; +pub use self::nl_search_model_base::NlSearchModelBase; +pub mod nl_search_model_create_schema; +pub use self::nl_search_model_create_schema::NlSearchModelCreateSchema; +pub mod nl_search_model_delete_schema; +pub use self::nl_search_model_delete_schema::NlSearchModelDeleteSchema; +pub mod nl_search_model_schema; +pub use self::nl_search_model_schema::NlSearchModelSchema; +pub mod preset_delete_schema; +pub use self::preset_delete_schema::PresetDeleteSchema; +pub mod preset_schema; +pub use self::preset_schema::PresetSchema; +pub mod preset_upsert_schema; +pub use self::preset_upsert_schema::PresetUpsertSchema; +pub mod preset_upsert_schema_value; +pub use self::preset_upsert_schema_value::PresetUpsertSchemaValue; +pub mod presets_retrieve_schema; +pub use self::presets_retrieve_schema::PresetsRetrieveSchema; +pub mod schema_change_status; +pub use self::schema_change_status::SchemaChangeStatus; pub mod scoped_key_parameters; pub use self::scoped_key_parameters::ScopedKeyParameters; pub mod search_grouped_hit; @@ -70,6 +124,8 @@ pub mod search_highlight; pub use self::search_highlight::SearchHighlight; pub mod search_override; pub use self::search_override::SearchOverride; +pub mod search_override_delete_response; +pub use self::search_override_delete_response::SearchOverrideDeleteResponse; pub mod search_override_exclude; pub use self::search_override_exclude::SearchOverrideExclude; pub mod search_override_include; @@ -84,21 +140,43 @@ pub mod search_parameters; pub use self::search_parameters::SearchParameters; pub mod search_result; pub use self::search_result::SearchResult; +pub mod search_result_conversation; +pub use self::search_result_conversation::SearchResultConversation; pub mod search_result_hit; pub use self::search_result_hit::SearchResultHit; +pub mod search_result_hit_text_match_info; +pub use self::search_result_hit_text_match_info::SearchResultHitTextMatchInfo; pub mod search_result_request_params; pub use self::search_result_request_params::SearchResultRequestParams; +pub mod search_result_request_params_voice_query; +pub use self::search_result_request_params_voice_query::SearchResultRequestParamsVoiceQuery; pub mod search_synonym; pub use self::search_synonym::SearchSynonym; +pub mod search_synonym_delete_response; +pub use self::search_synonym_delete_response::SearchSynonymDeleteResponse; pub mod search_synonym_schema; pub use self::search_synonym_schema::SearchSynonymSchema; pub mod search_synonyms_response; pub use self::search_synonyms_response::SearchSynonymsResponse; pub mod snapshot_parameters; pub use self::snapshot_parameters::SnapshotParameters; +pub mod stemming_dictionary; +pub use self::stemming_dictionary::StemmingDictionary; +pub mod stemming_dictionary_words_inner; +pub use self::stemming_dictionary_words_inner::StemmingDictionaryWordsInner; +pub mod stopwords_set_retrieve_schema; +pub use self::stopwords_set_retrieve_schema::StopwordsSetRetrieveSchema; +pub mod stopwords_set_schema; +pub use self::stopwords_set_schema::StopwordsSetSchema; +pub mod stopwords_set_upsert_schema; +pub use self::stopwords_set_upsert_schema::StopwordsSetUpsertSchema; +pub mod stopwords_sets_retrieve_all_schema; +pub use self::stopwords_sets_retrieve_all_schema::StopwordsSetsRetrieveAllSchema; pub mod success_status; pub use self::success_status::SuccessStatus; pub mod update_documents_200_response; pub use self::update_documents_200_response::UpdateDocuments200Response; -pub mod update_documents_update_documents_parameters_parameter; -pub use self::update_documents_update_documents_parameters_parameter::UpdateDocumentsUpdateDocumentsParametersParameter; +pub mod update_documents_parameters; +pub use self::update_documents_parameters::UpdateDocumentsParameters; +pub mod voice_query_model_collection_config; +pub use self::voice_query_model_collection_config::VoiceQueryModelCollectionConfig; diff --git a/typesense_codegen/src/models/multi_search_collection_parameters.rs b/typesense_codegen/src/models/multi_search_collection_parameters.rs index 97a99fd..0848b8e 100644 --- a/typesense_codegen/src/models/multi_search_collection_parameters.rs +++ b/typesense_codegen/src/models/multi_search_collection_parameters.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchCollectionParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. @@ -49,7 +52,7 @@ pub struct MultiSearchCollectionParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -58,7 +61,7 @@ pub struct MultiSearchCollectionParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -67,9 +70,12 @@ pub struct MultiSearchCollectionParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] + pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] pub include_fields: Option, @@ -77,108 +83,137 @@ pub struct MultiSearchCollectionParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde( - rename = "highlight_full_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde( - rename = "highlight_affix_num_tokens", - skip_serializing_if = "Option::is_none" - )] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde( - rename = "highlight_start_tag", - skip_serializing_if = "Option::is_none" - )] + /// The start tag used for the highlighted snippets. Default: `` + #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde( - rename = "drop_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] pub drop_tokens_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde( - rename = "typo_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] + pub drop_tokens_mode: Option, + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] pub typo_tokens_threshold: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] + pub enable_typos_for_alpha_numerical_tokens: Option, + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + pub filter_curated_hits: Option, + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] + pub enable_synonyms: Option, + /// Allow synonym resolution on word prefixes in the query. Default: false + #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] + pub synonym_prefix: Option, + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] + pub synonym_num_typos: Option, + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// Comma separated list of tags to trigger the curations rules that match the tags. + #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] + pub override_tags: Option, + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde( - rename = "pre_segmented_query", - skip_serializing_if = "Option::is_none" - )] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde( - rename = "prioritize_exact_match", - skip_serializing_if = "Option::is_none" - )] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] pub prioritize_exact_match: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] + pub prioritize_token_position: Option, + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] + pub prioritize_num_matching_fields: Option, + /// Make Typesense disable typos for numerical tokens. + #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] + pub enable_typos_for_numerical_tokens: Option, + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde( - rename = "remote_embedding_timeout_ms", - skip_serializing_if = "Option::is_none" - )] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde( - rename = "remote_embedding_num_tries", - skip_serializing_if = "Option::is_none" - )] + /// Number of times to retry fetching remote embeddings. + #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] pub remote_embedding_num_tries: Option, - /// The collection to search in. - #[serde(rename = "collection")] - pub collection: String, + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] + pub facet_strategy: Option, + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] + pub stopwords: Option, + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] + pub facet_return_parent: Option, + /// The base64 encoded audio file in 16 khz 16-bit WAV format. + #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] + pub voice_query: Option, + /// Enable conversational search. + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option, + /// The Id of Conversation Model to be used. + #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] + pub conversation_model_id: Option, + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] + pub conversation_id: Option, + /// The collection to search in. + #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] + pub collection: Option, + /// A separate search API key for each search within a multi_search request + #[serde(rename = "x-typesense-api-key", skip_serializing_if = "Option::is_none")] + pub x_typesense_api_key: Option, + /// When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. + #[serde(rename = "rerank_hybrid_matches", skip_serializing_if = "Option::is_none")] + pub rerank_hybrid_matches: Option, } impl MultiSearchCollectionParameters { - pub fn new(collection: String) -> MultiSearchCollectionParameters { + pub fn new() -> MultiSearchCollectionParameters { MultiSearchCollectionParameters { q: None, query_by: None, @@ -200,6 +235,7 @@ impl MultiSearchCollectionParameters { offset: None, group_by: None, group_limit: None, + group_missing_values: None, include_fields: None, exclude_fields: None, highlight_full_fields: None, @@ -208,14 +244,24 @@ impl MultiSearchCollectionParameters { highlight_end_tag: None, snippet_threshold: None, drop_tokens_threshold: None, + drop_tokens_mode: None, typo_tokens_threshold: None, + enable_typos_for_alpha_numerical_tokens: None, + filter_curated_hits: None, + enable_synonyms: None, + synonym_prefix: None, + synonym_num_typos: None, pinned_hits: None, hidden_hits: None, + override_tags: None, highlight_fields: None, pre_segmented_query: None, preset: None, enable_overrides: None, prioritize_exact_match: None, + prioritize_token_position: None, + prioritize_num_matching_fields: None, + enable_typos_for_numerical_tokens: None, exhaustive_search: None, search_cutoff_ms: None, use_cache: None, @@ -225,7 +271,17 @@ impl MultiSearchCollectionParameters { vector_query: None, remote_embedding_timeout_ms: None, remote_embedding_num_tries: None, - collection, + facet_strategy: None, + stopwords: None, + facet_return_parent: None, + voice_query: None, + conversation: None, + conversation_model_id: None, + conversation_id: None, + collection: None, + x_typesense_api_key: None, + rerank_hybrid_matches: None, } } } + diff --git a/typesense_codegen/src/models/multi_search_parameters.rs b/typesense_codegen/src/models/multi_search_parameters.rs index 409cc90..1ec2049 100644 --- a/typesense_codegen/src/models/multi_search_parameters.rs +++ b/typesense_codegen/src/models/multi_search_parameters.rs @@ -3,13 +3,15 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ -/// MultiSearchParameters : Parameters for the multi search API. +use crate::models; +use serde::{Deserialize, Serialize}; +/// MultiSearchParameters : Parameters for the multi search API. #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. @@ -51,7 +53,7 @@ pub struct MultiSearchParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -60,7 +62,7 @@ pub struct MultiSearchParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -69,9 +71,12 @@ pub struct MultiSearchParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] + pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] pub include_fields: Option, @@ -79,105 +84,128 @@ pub struct MultiSearchParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde( - rename = "highlight_full_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde( - rename = "highlight_affix_num_tokens", - skip_serializing_if = "Option::is_none" - )] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde( - rename = "highlight_start_tag", - skip_serializing_if = "Option::is_none" - )] + /// The start tag used for the highlighted snippets. Default: `` + #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde( - rename = "drop_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] pub drop_tokens_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde( - rename = "typo_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] + pub drop_tokens_mode: Option, + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] pub typo_tokens_threshold: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] + pub enable_typos_for_alpha_numerical_tokens: Option, + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + pub filter_curated_hits: Option, + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] + pub enable_synonyms: Option, + /// Allow synonym resolution on word prefixes in the query. Default: false + #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] + pub synonym_prefix: Option, + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] + pub synonym_num_typos: Option, + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// Comma separated list of tags to trigger the curations rules that match the tags. + #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] + pub override_tags: Option, + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde( - rename = "pre_segmented_query", - skip_serializing_if = "Option::is_none" - )] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde( - rename = "prioritize_exact_match", - skip_serializing_if = "Option::is_none" - )] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] pub prioritize_exact_match: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] + pub prioritize_token_position: Option, + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] + pub prioritize_num_matching_fields: Option, + /// Make Typesense disable typos for numerical tokens. + #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] + pub enable_typos_for_numerical_tokens: Option, + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde( - rename = "remote_embedding_timeout_ms", - skip_serializing_if = "Option::is_none" - )] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde( - rename = "remote_embedding_num_tries", - skip_serializing_if = "Option::is_none" - )] + /// Number of times to retry fetching remote embeddings. + #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] pub remote_embedding_num_tries: Option, + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] + pub facet_strategy: Option, + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] + pub stopwords: Option, + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] + pub facet_return_parent: Option, + /// The base64 encoded audio file in 16 khz 16-bit WAV format. + #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] + pub voice_query: Option, + /// Enable conversational search. + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option, + /// The Id of Conversation Model to be used. + #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] + pub conversation_model_id: Option, + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] + pub conversation_id: Option, } impl MultiSearchParameters { - /// Parameters for the multi search API. + /// Parameters for the multi search API. pub fn new() -> MultiSearchParameters { MultiSearchParameters { q: None, @@ -200,6 +228,7 @@ impl MultiSearchParameters { offset: None, group_by: None, group_limit: None, + group_missing_values: None, include_fields: None, exclude_fields: None, highlight_full_fields: None, @@ -208,14 +237,24 @@ impl MultiSearchParameters { highlight_end_tag: None, snippet_threshold: None, drop_tokens_threshold: None, + drop_tokens_mode: None, typo_tokens_threshold: None, + enable_typos_for_alpha_numerical_tokens: None, + filter_curated_hits: None, + enable_synonyms: None, + synonym_prefix: None, + synonym_num_typos: None, pinned_hits: None, hidden_hits: None, + override_tags: None, highlight_fields: None, pre_segmented_query: None, preset: None, enable_overrides: None, prioritize_exact_match: None, + prioritize_token_position: None, + prioritize_num_matching_fields: None, + enable_typos_for_numerical_tokens: None, exhaustive_search: None, search_cutoff_ms: None, use_cache: None, @@ -225,6 +264,14 @@ impl MultiSearchParameters { vector_query: None, remote_embedding_timeout_ms: None, remote_embedding_num_tries: None, + facet_strategy: None, + stopwords: None, + facet_return_parent: None, + voice_query: None, + conversation: None, + conversation_model_id: None, + conversation_id: None, } } } + diff --git a/typesense_codegen/src/models/multi_search_result.rs b/typesense_codegen/src/models/multi_search_result.rs index 1bab924..aa6038e 100644 --- a/typesense_codegen/src/models/multi_search_result.rs +++ b/typesense_codegen/src/models/multi_search_result.rs @@ -3,19 +3,28 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct MultiSearchResult { +pub struct MultiSearchResult { #[serde(rename = "results")] - pub results: Vec>, + pub results: Vec, + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option>, } -impl MultiSearchResult { - pub fn new(results: Vec>) -> Self { - Self { results } +impl MultiSearchResult { + pub fn new(results: Vec) -> MultiSearchResult { + MultiSearchResult { + results, + conversation: None, + } } } + diff --git a/typesense_codegen/src/models/multi_search_result_item.rs b/typesense_codegen/src/models/multi_search_result_item.rs new file mode 100644 index 0000000..c09620a --- /dev/null +++ b/typesense_codegen/src/models/multi_search_result_item.rs @@ -0,0 +1,71 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct MultiSearchResultItem { + #[serde(rename = "facet_counts", skip_serializing_if = "Option::is_none")] + pub facet_counts: Option>, + /// The number of documents found + #[serde(rename = "found", skip_serializing_if = "Option::is_none")] + pub found: Option, + #[serde(rename = "found_docs", skip_serializing_if = "Option::is_none")] + pub found_docs: Option, + /// The number of milliseconds the search took + #[serde(rename = "search_time_ms", skip_serializing_if = "Option::is_none")] + pub search_time_ms: Option, + /// The total number of documents in the collection + #[serde(rename = "out_of", skip_serializing_if = "Option::is_none")] + pub out_of: Option, + /// Whether the search was cut off + #[serde(rename = "search_cutoff", skip_serializing_if = "Option::is_none")] + pub search_cutoff: Option, + /// The search result page number + #[serde(rename = "page", skip_serializing_if = "Option::is_none")] + pub page: Option, + #[serde(rename = "grouped_hits", skip_serializing_if = "Option::is_none")] + pub grouped_hits: Option>, + /// The documents that matched the search query + #[serde(rename = "hits", skip_serializing_if = "Option::is_none")] + pub hits: Option>, + #[serde(rename = "request_params", skip_serializing_if = "Option::is_none")] + pub request_params: Option>, + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option>, + /// HTTP error code + #[serde(rename = "code", skip_serializing_if = "Option::is_none")] + pub code: Option, + /// Error description + #[serde(rename = "error", skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl MultiSearchResultItem { + pub fn new() -> MultiSearchResultItem { + MultiSearchResultItem { + facet_counts: None, + found: None, + found_docs: None, + search_time_ms: None, + out_of: None, + search_cutoff: None, + page: None, + grouped_hits: None, + hits: None, + request_params: None, + conversation: None, + code: None, + error: None, + } + } +} + diff --git a/typesense_codegen/src/models/multi_search_searches_parameter.rs b/typesense_codegen/src/models/multi_search_searches_parameter.rs index 1e11b6e..7d165be 100644 --- a/typesense_codegen/src/models/multi_search_searches_parameter.rs +++ b/typesense_codegen/src/models/multi_search_searches_parameter.rs @@ -3,21 +3,29 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchSearchesParameter { + /// When true, merges the search results from each search query into a single ordered set of hits. + #[serde(rename = "union", skip_serializing_if = "Option::is_none")] + pub union: Option, #[serde(rename = "searches")] - pub searches: Vec, + pub searches: Vec, } impl MultiSearchSearchesParameter { - pub fn new( - searches: Vec, - ) -> MultiSearchSearchesParameter { - MultiSearchSearchesParameter { searches } + pub fn new(searches: Vec) -> MultiSearchSearchesParameter { + MultiSearchSearchesParameter { + union: None, + searches, + } } } + diff --git a/typesense_codegen/src/models/nl_search_model_base.rs b/typesense_codegen/src/models/nl_search_model_base.rs new file mode 100644 index 0000000..bec4058 --- /dev/null +++ b/typesense_codegen/src/models/nl_search_model_base.rs @@ -0,0 +1,96 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct NlSearchModelBase { + /// Name of the NL model to use + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, + /// API key for the NL model service + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Custom API URL for the NL model service + #[serde(rename = "api_url", skip_serializing_if = "Option::is_none")] + pub api_url: Option, + /// Maximum number of bytes to process + #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] + pub max_bytes: Option, + /// Temperature parameter for the NL model + #[serde(rename = "temperature", skip_serializing_if = "Option::is_none")] + pub temperature: Option, + /// System prompt for the NL model + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Top-p parameter for the NL model (Google-specific) + #[serde(rename = "top_p", skip_serializing_if = "Option::is_none")] + pub top_p: Option, + /// Top-k parameter for the NL model (Google-specific) + #[serde(rename = "top_k", skip_serializing_if = "Option::is_none")] + pub top_k: Option, + /// Stop sequences for the NL model (Google-specific) + #[serde(rename = "stop_sequences", skip_serializing_if = "Option::is_none")] + pub stop_sequences: Option>, + /// API version for the NL model service + #[serde(rename = "api_version", skip_serializing_if = "Option::is_none")] + pub api_version: Option, + /// Project ID for GCP Vertex AI + #[serde(rename = "project_id", skip_serializing_if = "Option::is_none")] + pub project_id: Option, + /// Access token for GCP Vertex AI + #[serde(rename = "access_token", skip_serializing_if = "Option::is_none")] + pub access_token: Option, + /// Refresh token for GCP Vertex AI + #[serde(rename = "refresh_token", skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, + /// Client ID for GCP Vertex AI + #[serde(rename = "client_id", skip_serializing_if = "Option::is_none")] + pub client_id: Option, + /// Client secret for GCP Vertex AI + #[serde(rename = "client_secret", skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + /// Region for GCP Vertex AI + #[serde(rename = "region", skip_serializing_if = "Option::is_none")] + pub region: Option, + /// Maximum output tokens for GCP Vertex AI + #[serde(rename = "max_output_tokens", skip_serializing_if = "Option::is_none")] + pub max_output_tokens: Option, + /// Account ID for Cloudflare-specific models + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, +} + +impl NlSearchModelBase { + pub fn new() -> NlSearchModelBase { + NlSearchModelBase { + model_name: None, + api_key: None, + api_url: None, + max_bytes: None, + temperature: None, + system_prompt: None, + top_p: None, + top_k: None, + stop_sequences: None, + api_version: None, + project_id: None, + access_token: None, + refresh_token: None, + client_id: None, + client_secret: None, + region: None, + max_output_tokens: None, + account_id: None, + } + } +} + diff --git a/typesense_codegen/src/models/nl_search_model_create_schema.rs b/typesense_codegen/src/models/nl_search_model_create_schema.rs new file mode 100644 index 0000000..383b456 --- /dev/null +++ b/typesense_codegen/src/models/nl_search_model_create_schema.rs @@ -0,0 +1,100 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct NlSearchModelCreateSchema { + /// Name of the NL model to use + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, + /// API key for the NL model service + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Custom API URL for the NL model service + #[serde(rename = "api_url", skip_serializing_if = "Option::is_none")] + pub api_url: Option, + /// Maximum number of bytes to process + #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] + pub max_bytes: Option, + /// Temperature parameter for the NL model + #[serde(rename = "temperature", skip_serializing_if = "Option::is_none")] + pub temperature: Option, + /// System prompt for the NL model + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Top-p parameter for the NL model (Google-specific) + #[serde(rename = "top_p", skip_serializing_if = "Option::is_none")] + pub top_p: Option, + /// Top-k parameter for the NL model (Google-specific) + #[serde(rename = "top_k", skip_serializing_if = "Option::is_none")] + pub top_k: Option, + /// Stop sequences for the NL model (Google-specific) + #[serde(rename = "stop_sequences", skip_serializing_if = "Option::is_none")] + pub stop_sequences: Option>, + /// API version for the NL model service + #[serde(rename = "api_version", skip_serializing_if = "Option::is_none")] + pub api_version: Option, + /// Project ID for GCP Vertex AI + #[serde(rename = "project_id", skip_serializing_if = "Option::is_none")] + pub project_id: Option, + /// Access token for GCP Vertex AI + #[serde(rename = "access_token", skip_serializing_if = "Option::is_none")] + pub access_token: Option, + /// Refresh token for GCP Vertex AI + #[serde(rename = "refresh_token", skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, + /// Client ID for GCP Vertex AI + #[serde(rename = "client_id", skip_serializing_if = "Option::is_none")] + pub client_id: Option, + /// Client secret for GCP Vertex AI + #[serde(rename = "client_secret", skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + /// Region for GCP Vertex AI + #[serde(rename = "region", skip_serializing_if = "Option::is_none")] + pub region: Option, + /// Maximum output tokens for GCP Vertex AI + #[serde(rename = "max_output_tokens", skip_serializing_if = "Option::is_none")] + pub max_output_tokens: Option, + /// Account ID for Cloudflare-specific models + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// Optional ID for the NL search model + #[serde(rename = "id", skip_serializing_if = "Option::is_none")] + pub id: Option, +} + +impl NlSearchModelCreateSchema { + pub fn new() -> NlSearchModelCreateSchema { + NlSearchModelCreateSchema { + model_name: None, + api_key: None, + api_url: None, + max_bytes: None, + temperature: None, + system_prompt: None, + top_p: None, + top_k: None, + stop_sequences: None, + api_version: None, + project_id: None, + access_token: None, + refresh_token: None, + client_id: None, + client_secret: None, + region: None, + max_output_tokens: None, + account_id: None, + id: None, + } + } +} + diff --git a/typesense_codegen/src/models/nl_search_model_delete_schema.rs b/typesense_codegen/src/models/nl_search_model_delete_schema.rs new file mode 100644 index 0000000..6864ee1 --- /dev/null +++ b/typesense_codegen/src/models/nl_search_model_delete_schema.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct NlSearchModelDeleteSchema { + /// ID of the deleted NL search model + #[serde(rename = "id")] + pub id: String, +} + +impl NlSearchModelDeleteSchema { + pub fn new(id: String) -> NlSearchModelDeleteSchema { + NlSearchModelDeleteSchema { + id, + } + } +} + diff --git a/typesense_codegen/src/models/nl_search_model_schema.rs b/typesense_codegen/src/models/nl_search_model_schema.rs new file mode 100644 index 0000000..22d656e --- /dev/null +++ b/typesense_codegen/src/models/nl_search_model_schema.rs @@ -0,0 +1,100 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct NlSearchModelSchema { + /// Name of the NL model to use + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, + /// API key for the NL model service + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Custom API URL for the NL model service + #[serde(rename = "api_url", skip_serializing_if = "Option::is_none")] + pub api_url: Option, + /// Maximum number of bytes to process + #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] + pub max_bytes: Option, + /// Temperature parameter for the NL model + #[serde(rename = "temperature", skip_serializing_if = "Option::is_none")] + pub temperature: Option, + /// System prompt for the NL model + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Top-p parameter for the NL model (Google-specific) + #[serde(rename = "top_p", skip_serializing_if = "Option::is_none")] + pub top_p: Option, + /// Top-k parameter for the NL model (Google-specific) + #[serde(rename = "top_k", skip_serializing_if = "Option::is_none")] + pub top_k: Option, + /// Stop sequences for the NL model (Google-specific) + #[serde(rename = "stop_sequences", skip_serializing_if = "Option::is_none")] + pub stop_sequences: Option>, + /// API version for the NL model service + #[serde(rename = "api_version", skip_serializing_if = "Option::is_none")] + pub api_version: Option, + /// Project ID for GCP Vertex AI + #[serde(rename = "project_id", skip_serializing_if = "Option::is_none")] + pub project_id: Option, + /// Access token for GCP Vertex AI + #[serde(rename = "access_token", skip_serializing_if = "Option::is_none")] + pub access_token: Option, + /// Refresh token for GCP Vertex AI + #[serde(rename = "refresh_token", skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, + /// Client ID for GCP Vertex AI + #[serde(rename = "client_id", skip_serializing_if = "Option::is_none")] + pub client_id: Option, + /// Client secret for GCP Vertex AI + #[serde(rename = "client_secret", skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + /// Region for GCP Vertex AI + #[serde(rename = "region", skip_serializing_if = "Option::is_none")] + pub region: Option, + /// Maximum output tokens for GCP Vertex AI + #[serde(rename = "max_output_tokens", skip_serializing_if = "Option::is_none")] + pub max_output_tokens: Option, + /// Account ID for Cloudflare-specific models + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// ID of the NL search model + #[serde(rename = "id")] + pub id: String, +} + +impl NlSearchModelSchema { + pub fn new(id: String) -> NlSearchModelSchema { + NlSearchModelSchema { + model_name: None, + api_key: None, + api_url: None, + max_bytes: None, + temperature: None, + system_prompt: None, + top_p: None, + top_k: None, + stop_sequences: None, + api_version: None, + project_id: None, + access_token: None, + refresh_token: None, + client_id: None, + client_secret: None, + region: None, + max_output_tokens: None, + account_id: None, + id, + } + } +} + diff --git a/typesense_codegen/src/models/preset_delete_schema.rs b/typesense_codegen/src/models/preset_delete_schema.rs new file mode 100644 index 0000000..ea52d06 --- /dev/null +++ b/typesense_codegen/src/models/preset_delete_schema.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct PresetDeleteSchema { + #[serde(rename = "name")] + pub name: String, +} + +impl PresetDeleteSchema { + pub fn new(name: String) -> PresetDeleteSchema { + PresetDeleteSchema { + name, + } + } +} + diff --git a/typesense_codegen/src/models/preset_schema.rs b/typesense_codegen/src/models/preset_schema.rs new file mode 100644 index 0000000..7987eb1 --- /dev/null +++ b/typesense_codegen/src/models/preset_schema.rs @@ -0,0 +1,30 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct PresetSchema { + #[serde(rename = "value")] + pub value: Box, + #[serde(rename = "name")] + pub name: String, +} + +impl PresetSchema { + pub fn new(value: models::PresetUpsertSchemaValue, name: String) -> PresetSchema { + PresetSchema { + value: Box::new(value), + name, + } + } +} + diff --git a/typesense_codegen/src/models/preset_upsert_schema.rs b/typesense_codegen/src/models/preset_upsert_schema.rs new file mode 100644 index 0000000..ec7175e --- /dev/null +++ b/typesense_codegen/src/models/preset_upsert_schema.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct PresetUpsertSchema { + #[serde(rename = "value")] + pub value: Box, +} + +impl PresetUpsertSchema { + pub fn new(value: models::PresetUpsertSchemaValue) -> PresetUpsertSchema { + PresetUpsertSchema { + value: Box::new(value), + } + } +} + diff --git a/typesense_codegen/src/models/preset_upsert_schema_value.rs b/typesense_codegen/src/models/preset_upsert_schema_value.rs new file mode 100644 index 0000000..afb9398 --- /dev/null +++ b/typesense_codegen/src/models/preset_upsert_schema_value.rs @@ -0,0 +1,26 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PresetUpsertSchemaValue { + SearchParameters(Box), + MultiSearchSearchesParameter(Box), +} + +impl Default for PresetUpsertSchemaValue { + fn default() -> Self { + Self::SearchParameters(Default::default()) + } +} + diff --git a/typesense_codegen/src/models/presets_retrieve_schema.rs b/typesense_codegen/src/models/presets_retrieve_schema.rs new file mode 100644 index 0000000..22e5b12 --- /dev/null +++ b/typesense_codegen/src/models/presets_retrieve_schema.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct PresetsRetrieveSchema { + #[serde(rename = "presets")] + pub presets: Vec, +} + +impl PresetsRetrieveSchema { + pub fn new(presets: Vec) -> PresetsRetrieveSchema { + PresetsRetrieveSchema { + presets, + } + } +} + diff --git a/typesense_codegen/src/models/schema_change_status.rs b/typesense_codegen/src/models/schema_change_status.rs new file mode 100644 index 0000000..ea0b52a --- /dev/null +++ b/typesense_codegen/src/models/schema_change_status.rs @@ -0,0 +1,36 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SchemaChangeStatus { + /// Name of the collection being modified + #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] + pub collection: Option, + /// Number of documents that have been validated + #[serde(rename = "validated_docs", skip_serializing_if = "Option::is_none")] + pub validated_docs: Option, + /// Number of documents that have been altered + #[serde(rename = "altered_docs", skip_serializing_if = "Option::is_none")] + pub altered_docs: Option, +} + +impl SchemaChangeStatus { + pub fn new() -> SchemaChangeStatus { + SchemaChangeStatus { + collection: None, + validated_docs: None, + altered_docs: None, + } + } +} + diff --git a/typesense_codegen/src/models/scoped_key_parameters.rs b/typesense_codegen/src/models/scoped_key_parameters.rs index 4a88ffd..62a11af 100644 --- a/typesense_codegen/src/models/scoped_key_parameters.rs +++ b/typesense_codegen/src/models/scoped_key_parameters.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ScopedKeyParameters { #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] @@ -24,3 +27,4 @@ impl ScopedKeyParameters { } } } + diff --git a/typesense_codegen/src/models/search_grouped_hit.rs b/typesense_codegen/src/models/search_grouped_hit.rs index b9e19cd..80b53c3 100644 --- a/typesense_codegen/src/models/search_grouped_hit.rs +++ b/typesense_codegen/src/models/search_grouped_hit.rs @@ -3,31 +3,32 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct SearchGroupedHit { +pub struct SearchGroupedHit { #[serde(rename = "found", skip_serializing_if = "Option::is_none")] pub found: Option, #[serde(rename = "group_key")] pub group_key: Vec, /// The documents that matched the search query #[serde(rename = "hits")] - pub hits: Vec>, + pub hits: Vec, } -impl SearchGroupedHit { - pub fn new( - group_key: Vec, - hits: Vec>, - ) -> Self { - Self { +impl SearchGroupedHit { + pub fn new(group_key: Vec, hits: Vec) -> SearchGroupedHit { + SearchGroupedHit { found: None, group_key, hits, } } } + diff --git a/typesense_codegen/src/models/search_highlight.rs b/typesense_codegen/src/models/search_highlight.rs index f5b7e2a..2da96ab 100644 --- a/typesense_codegen/src/models/search_highlight.rs +++ b/typesense_codegen/src/models/search_highlight.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchHighlight { #[serde(rename = "field", skip_serializing_if = "Option::is_none")] @@ -44,3 +47,4 @@ impl SearchHighlight { } } } + diff --git a/typesense_codegen/src/models/search_override.rs b/typesense_codegen/src/models/search_override.rs index ed41718..bd7250f 100644 --- a/typesense_codegen/src/models/search_override.rs +++ b/typesense_codegen/src/models/search_override.rs @@ -3,43 +3,72 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverride { #[serde(rename = "rule")] - pub rule: Box, + pub rule: Box, /// List of document `id`s that should be included in the search results with their corresponding `position`s. #[serde(rename = "includes", skip_serializing_if = "Option::is_none")] - pub includes: Option>, + pub includes: Option>, /// List of document `id`s that should be excluded from the search results. #[serde(rename = "excludes", skip_serializing_if = "Option::is_none")] - pub excludes: Option>, - /// A filter by clause that is applied to any search query that matches the override rule. + pub excludes: Option>, + /// A filter by clause that is applied to any search query that matches the override rule. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, - /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. - #[serde( - rename = "remove_matched_tokens", - skip_serializing_if = "Option::is_none" - )] + /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + #[serde(rename = "remove_matched_tokens", skip_serializing_if = "Option::is_none")] pub remove_matched_tokens: Option, + /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] + pub metadata: Option, + /// A sort by clause that is applied to any search query that matches the override rule. + #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] + pub sort_by: Option, + /// Replaces the current search query with this value, when the search query matches the override rule. + #[serde(rename = "replace_query", skip_serializing_if = "Option::is_none")] + pub replace_query: Option, + /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + pub filter_curated_hits: Option, + /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + #[serde(rename = "effective_from_ts", skip_serializing_if = "Option::is_none")] + pub effective_from_ts: Option, + /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + #[serde(rename = "effective_to_ts", skip_serializing_if = "Option::is_none")] + pub effective_to_ts: Option, + /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + #[serde(rename = "stop_processing", skip_serializing_if = "Option::is_none")] + pub stop_processing: Option, #[serde(rename = "id")] pub id: String, } impl SearchOverride { - pub fn new(rule: crate::models::SearchOverrideRule, id: String) -> SearchOverride { + pub fn new(rule: models::SearchOverrideRule, id: String) -> SearchOverride { SearchOverride { rule: Box::new(rule), includes: None, excludes: None, filter_by: None, remove_matched_tokens: None, + metadata: None, + sort_by: None, + replace_query: None, + filter_curated_hits: None, + effective_from_ts: None, + effective_to_ts: None, + stop_processing: None, id, } } } + diff --git a/typesense_codegen/src/models/search_override_delete_response.rs b/typesense_codegen/src/models/search_override_delete_response.rs new file mode 100644 index 0000000..bc0aeb1 --- /dev/null +++ b/typesense_codegen/src/models/search_override_delete_response.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchOverrideDeleteResponse { + /// The id of the override that was deleted + #[serde(rename = "id")] + pub id: String, +} + +impl SearchOverrideDeleteResponse { + pub fn new(id: String) -> SearchOverrideDeleteResponse { + SearchOverrideDeleteResponse { + id, + } + } +} + diff --git a/typesense_codegen/src/models/search_override_exclude.rs b/typesense_codegen/src/models/search_override_exclude.rs index 1cea902..dddbf43 100644 --- a/typesense_codegen/src/models/search_override_exclude.rs +++ b/typesense_codegen/src/models/search_override_exclude.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideExclude { /// document id that should be excluded from the search results. @@ -17,6 +20,9 @@ pub struct SearchOverrideExclude { impl SearchOverrideExclude { pub fn new(id: String) -> SearchOverrideExclude { - SearchOverrideExclude { id } + SearchOverrideExclude { + id, + } } } + diff --git a/typesense_codegen/src/models/search_override_include.rs b/typesense_codegen/src/models/search_override_include.rs index 3cdbff2..fa10b74 100644 --- a/typesense_codegen/src/models/search_override_include.rs +++ b/typesense_codegen/src/models/search_override_include.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideInclude { /// document id that should be included @@ -20,6 +23,10 @@ pub struct SearchOverrideInclude { impl SearchOverrideInclude { pub fn new(id: String, position: i32) -> SearchOverrideInclude { - SearchOverrideInclude { id, position } + SearchOverrideInclude { + id, + position, + } } } + diff --git a/typesense_codegen/src/models/search_override_rule.rs b/typesense_codegen/src/models/search_override_rule.rs index f5a339b..21d659a 100644 --- a/typesense_codegen/src/models/search_override_rule.rs +++ b/typesense_codegen/src/models/search_override_rule.rs @@ -3,28 +3,41 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideRule { + /// List of tag values to associate with this override rule. + #[serde(rename = "tags", skip_serializing_if = "Option::is_none")] + pub tags: Option>, /// Indicates what search queries should be overridden - #[serde(rename = "query")] - pub query: String, - /// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. - #[serde(rename = "match")] - pub r#match: Match, + #[serde(rename = "query", skip_serializing_if = "Option::is_none")] + pub query: Option, + /// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. + #[serde(rename = "match", skip_serializing_if = "Option::is_none")] + pub r#match: Option, + /// Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). + #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] + pub filter_by: Option, } impl SearchOverrideRule { - pub fn new(query: String, r#match: Match) -> SearchOverrideRule { - SearchOverrideRule { query, r#match } + pub fn new() -> SearchOverrideRule { + SearchOverrideRule { + tags: None, + query: None, + r#match: None, + filter_by: None, + } } } - -/// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. +/// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Match { #[serde(rename = "exact")] @@ -38,3 +51,4 @@ impl Default for Match { Self::Exact } } + diff --git a/typesense_codegen/src/models/search_override_schema.rs b/typesense_codegen/src/models/search_override_schema.rs index 7b3eedb..3f7a04f 100644 --- a/typesense_codegen/src/models/search_override_schema.rs +++ b/typesense_codegen/src/models/search_override_schema.rs @@ -3,40 +3,69 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideSchema { #[serde(rename = "rule")] - pub rule: Box, + pub rule: Box, /// List of document `id`s that should be included in the search results with their corresponding `position`s. #[serde(rename = "includes", skip_serializing_if = "Option::is_none")] - pub includes: Option>, + pub includes: Option>, /// List of document `id`s that should be excluded from the search results. #[serde(rename = "excludes", skip_serializing_if = "Option::is_none")] - pub excludes: Option>, - /// A filter by clause that is applied to any search query that matches the override rule. + pub excludes: Option>, + /// A filter by clause that is applied to any search query that matches the override rule. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, - /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. - #[serde( - rename = "remove_matched_tokens", - skip_serializing_if = "Option::is_none" - )] + /// Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + #[serde(rename = "remove_matched_tokens", skip_serializing_if = "Option::is_none")] pub remove_matched_tokens: Option, + /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] + pub metadata: Option, + /// A sort by clause that is applied to any search query that matches the override rule. + #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] + pub sort_by: Option, + /// Replaces the current search query with this value, when the search query matches the override rule. + #[serde(rename = "replace_query", skip_serializing_if = "Option::is_none")] + pub replace_query: Option, + /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + pub filter_curated_hits: Option, + /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + #[serde(rename = "effective_from_ts", skip_serializing_if = "Option::is_none")] + pub effective_from_ts: Option, + /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + #[serde(rename = "effective_to_ts", skip_serializing_if = "Option::is_none")] + pub effective_to_ts: Option, + /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + #[serde(rename = "stop_processing", skip_serializing_if = "Option::is_none")] + pub stop_processing: Option, } impl SearchOverrideSchema { - pub fn new(rule: crate::models::SearchOverrideRule) -> SearchOverrideSchema { + pub fn new(rule: models::SearchOverrideRule) -> SearchOverrideSchema { SearchOverrideSchema { rule: Box::new(rule), includes: None, excludes: None, filter_by: None, remove_matched_tokens: None, + metadata: None, + sort_by: None, + replace_query: None, + filter_curated_hits: None, + effective_from_ts: None, + effective_to_ts: None, + stop_processing: None, } } } + diff --git a/typesense_codegen/src/models/search_overrides_response.rs b/typesense_codegen/src/models/search_overrides_response.rs index 1c4e49b..50e900b 100644 --- a/typesense_codegen/src/models/search_overrides_response.rs +++ b/typesense_codegen/src/models/search_overrides_response.rs @@ -3,19 +3,25 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverridesResponse { #[serde(rename = "overrides")] - pub overrides: Vec, + pub overrides: Vec, } impl SearchOverridesResponse { - pub fn new(overrides: Vec) -> SearchOverridesResponse { - SearchOverridesResponse { overrides } + pub fn new(overrides: Vec) -> SearchOverridesResponse { + SearchOverridesResponse { + overrides, + } } } + diff --git a/typesense_codegen/src/models/search_parameters.rs b/typesense_codegen/src/models/search_parameters.rs index 3c1fb07..839dfe9 100644 --- a/typesense_codegen/src/models/search_parameters.rs +++ b/typesense_codegen/src/models/search_parameters.rs @@ -3,19 +3,28 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. - #[serde(rename = "q")] - pub q: String, + #[serde(rename = "q", skip_serializing_if = "Option::is_none")] + pub q: Option, /// A list of `string` fields that should be queried against. Multiple fields are separated with a comma. - #[serde(rename = "query_by")] - pub query_by: String, + #[serde(rename = "query_by", skip_serializing_if = "Option::is_none")] + pub query_by: Option, + /// Whether to use natural language processing to parse the query. + #[serde(rename = "nl_query", skip_serializing_if = "Option::is_none")] + pub nl_query: Option, + /// The ID of the natural language model to use. + #[serde(rename = "nl_model_id", skip_serializing_if = "Option::is_none")] + pub nl_model_id: Option, /// The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. #[serde(rename = "query_by_weights", skip_serializing_if = "Option::is_none")] pub query_by_weights: Option, @@ -37,6 +46,9 @@ pub struct SearchParameters { /// Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, + /// Controls the number of similar words that Typesense considers during fuzzy search on filter_by values. Useful for controlling prefix matches like company_name:Acm*. + #[serde(rename = "max_filter_by_candidates", skip_serializing_if = "Option::is_none")] + pub max_filter_by_candidates: Option, /// A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] pub sort_by: Option, @@ -49,7 +61,7 @@ pub struct SearchParameters { /// Facet values that are returned can now be filtered via this parameter. The matching facet text is also highlighted. For example, when faceting by `category`, you can set `facet_query=category:shoe` to return only facet values that contain the prefix \"shoe\". #[serde(rename = "facet_query", skip_serializing_if = "Option::is_none")] pub facet_query: Option, - /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 + /// The number of typographical errors (1 or 2) that would be tolerated. Default: 2 #[serde(rename = "num_typos", skip_serializing_if = "Option::is_none")] pub num_typos: Option, /// Results from this specific page number would be fetched. @@ -58,7 +70,7 @@ pub struct SearchParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -67,9 +79,12 @@ pub struct SearchParameters { /// You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. #[serde(rename = "group_by", skip_serializing_if = "Option::is_none")] pub group_by: Option, - /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 + /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde(rename = "group_missing_values", skip_serializing_if = "Option::is_none")] + pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] pub include_fields: Option, @@ -77,126 +92,142 @@ pub struct SearchParameters { #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] pub exclude_fields: Option, /// List of fields which should be highlighted fully without snippeting - #[serde( - rename = "highlight_full_fields", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "highlight_full_fields", skip_serializing_if = "Option::is_none")] pub highlight_full_fields: Option, - /// The number of tokens that should surround the highlighted text on each side. Default: 4 - #[serde( - rename = "highlight_affix_num_tokens", - skip_serializing_if = "Option::is_none" - )] + /// The number of tokens that should surround the highlighted text on each side. Default: 4 + #[serde(rename = "highlight_affix_num_tokens", skip_serializing_if = "Option::is_none")] pub highlight_affix_num_tokens: Option, - /// The start tag used for the highlighted snippets. Default: `` - #[serde( - rename = "highlight_start_tag", - skip_serializing_if = "Option::is_none" - )] + /// The start tag used for the highlighted snippets. Default: `` + #[serde(rename = "highlight_start_tag", skip_serializing_if = "Option::is_none")] pub highlight_start_tag: Option, - /// The end tag used for the highlighted snippets. Default: `` + /// The end tag used for the highlighted snippets. Default: `` #[serde(rename = "highlight_end_tag", skip_serializing_if = "Option::is_none")] pub highlight_end_tag: Option, - /// Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true - #[serde( - rename = "enable_highlight_v1", - skip_serializing_if = "Option::is_none" - )] + /// Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true + #[serde(rename = "enable_highlight_v1", skip_serializing_if = "Option::is_none")] pub enable_highlight_v1: Option, - /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 + /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 - #[serde( - rename = "drop_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 + #[serde(rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none")] pub drop_tokens_threshold: Option, - /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 - #[serde( - rename = "typo_tokens_threshold", - skip_serializing_if = "Option::is_none" - )] + #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] + pub drop_tokens_mode: Option, + /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 + #[serde(rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none")] pub typo_tokens_threshold: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde(rename = "enable_typos_for_alpha_numerical_tokens", skip_serializing_if = "Option::is_none")] + pub enable_typos_for_alpha_numerical_tokens: Option, + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde(rename = "filter_curated_hits", skip_serializing_if = "Option::is_none")] + pub filter_curated_hits: Option, + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] + pub enable_synonyms: Option, + /// Allow synonym resolution on word prefixes in the query. Default: false + #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] + pub synonym_prefix: Option, + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] + pub synonym_num_typos: Option, + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, - /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// Comma separated list of tags to trigger the curations rules that match the tags. + #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] + pub override_tags: Option, + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. + /// Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. #[serde(rename = "split_join_tokens", skip_serializing_if = "Option::is_none")] pub split_join_tokens: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same - #[serde( - rename = "pre_segmented_query", - skip_serializing_if = "Option::is_none" - )] + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + #[serde(rename = "pre_segmented_query", skip_serializing_if = "Option::is_none")] pub pre_segmented_query: Option, - /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. + /// Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. #[serde(rename = "preset", skip_serializing_if = "Option::is_none")] pub preset: Option, - /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false + /// If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false #[serde(rename = "enable_overrides", skip_serializing_if = "Option::is_none")] pub enable_overrides: Option, - /// Set this parameter to true to ensure that an exact match is ranked above the others - #[serde( - rename = "prioritize_exact_match", - skip_serializing_if = "Option::is_none" - )] + /// Set this parameter to true to ensure that an exact match is ranked above the others + #[serde(rename = "prioritize_exact_match", skip_serializing_if = "Option::is_none")] pub prioritize_exact_match: Option, - /// Control the number of words that Typesense considers for typo and prefix searching. + /// Control the number of words that Typesense considers for typo and prefix searching. #[serde(rename = "max_candidates", skip_serializing_if = "Option::is_none")] pub max_candidates: Option, - /// Make Typesense prioritize documents where the query words appear earlier in the text. - #[serde( - rename = "prioritize_token_position", - skip_serializing_if = "Option::is_none" - )] + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde(rename = "prioritize_token_position", skip_serializing_if = "Option::is_none")] pub prioritize_token_position: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde(rename = "prioritize_num_matching_fields", skip_serializing_if = "Option::is_none")] + pub prioritize_num_matching_fields: Option, + /// Make Typesense disable typos for numerical tokens. + #[serde(rename = "enable_typos_for_numerical_tokens", skip_serializing_if = "Option::is_none")] + pub enable_typos_for_numerical_tokens: Option, + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, - /// Enable server side caching of search query results. By default, caching is disabled. + /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, - /// Vector query expression for fetching documents \"closest\" to a given query/document vector. + /// Vector query expression for fetching documents \"closest\" to a given query/document vector. #[serde(rename = "vector_query", skip_serializing_if = "Option::is_none")] pub vector_query: Option, - /// Timeout (in milliseconds) for fetching remote embeddings. - #[serde( - rename = "remote_embedding_timeout_ms", - skip_serializing_if = "Option::is_none" - )] + /// Timeout (in milliseconds) for fetching remote embeddings. + #[serde(rename = "remote_embedding_timeout_ms", skip_serializing_if = "Option::is_none")] pub remote_embedding_timeout_ms: Option, - /// Number of times to retry fetching remote embeddings. - #[serde( - rename = "remote_embedding_num_tries", - skip_serializing_if = "Option::is_none" - )] + /// Number of times to retry fetching remote embeddings. + #[serde(rename = "remote_embedding_num_tries", skip_serializing_if = "Option::is_none")] pub remote_embedding_num_tries: Option, + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] + pub facet_strategy: Option, + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] + pub stopwords: Option, + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde(rename = "facet_return_parent", skip_serializing_if = "Option::is_none")] + pub facet_return_parent: Option, + /// The base64 encoded audio file in 16 khz 16-bit WAV format. + #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] + pub voice_query: Option, + /// Enable conversational search. + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option, + /// The Id of Conversation Model to be used. + #[serde(rename = "conversation_model_id", skip_serializing_if = "Option::is_none")] + pub conversation_model_id: Option, + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] + pub conversation_id: Option, } impl SearchParameters { - pub fn new(q: String, query_by: String) -> SearchParameters { + pub fn new() -> SearchParameters { SearchParameters { - q, - query_by, + q: None, + query_by: None, + nl_query: None, + nl_model_id: None, query_by_weights: None, text_match_type: None, prefix: None, @@ -204,6 +235,7 @@ impl SearchParameters { max_extra_prefix: None, max_extra_suffix: None, filter_by: None, + max_filter_by_candidates: None, sort_by: None, facet_by: None, max_facet_values: None, @@ -215,6 +247,7 @@ impl SearchParameters { offset: None, group_by: None, group_limit: None, + group_missing_values: None, include_fields: None, exclude_fields: None, highlight_full_fields: None, @@ -224,9 +257,16 @@ impl SearchParameters { enable_highlight_v1: None, snippet_threshold: None, drop_tokens_threshold: None, + drop_tokens_mode: None, typo_tokens_threshold: None, + enable_typos_for_alpha_numerical_tokens: None, + filter_curated_hits: None, + enable_synonyms: None, + synonym_prefix: None, + synonym_num_typos: None, pinned_hits: None, hidden_hits: None, + override_tags: None, highlight_fields: None, split_join_tokens: None, pre_segmented_query: None, @@ -235,6 +275,8 @@ impl SearchParameters { prioritize_exact_match: None, max_candidates: None, prioritize_token_position: None, + prioritize_num_matching_fields: None, + enable_typos_for_numerical_tokens: None, exhaustive_search: None, search_cutoff_ms: None, use_cache: None, @@ -244,6 +286,14 @@ impl SearchParameters { vector_query: None, remote_embedding_timeout_ms: None, remote_embedding_num_tries: None, + facet_strategy: None, + stopwords: None, + facet_return_parent: None, + voice_query: None, + conversation: None, + conversation_model_id: None, + conversation_id: None, } } } + diff --git a/typesense_codegen/src/models/search_result.rs b/typesense_codegen/src/models/search_result.rs index 11527ab..ad5e13f 100644 --- a/typesense_codegen/src/models/search_result.rs +++ b/typesense_codegen/src/models/search_result.rs @@ -3,18 +3,23 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct SearchResult { +pub struct SearchResult { #[serde(rename = "facet_counts", skip_serializing_if = "Option::is_none")] - pub facet_counts: Option>, + pub facet_counts: Option>, /// The number of documents found #[serde(rename = "found", skip_serializing_if = "Option::is_none")] pub found: Option, + #[serde(rename = "found_docs", skip_serializing_if = "Option::is_none")] + pub found_docs: Option, /// The number of milliseconds the search took #[serde(rename = "search_time_ms", skip_serializing_if = "Option::is_none")] pub search_time_ms: Option, @@ -28,19 +33,22 @@ pub struct SearchResult { #[serde(rename = "page", skip_serializing_if = "Option::is_none")] pub page: Option, #[serde(rename = "grouped_hits", skip_serializing_if = "Option::is_none")] - pub grouped_hits: Option>>, + pub grouped_hits: Option>, /// The documents that matched the search query #[serde(rename = "hits", skip_serializing_if = "Option::is_none")] - pub hits: Option>>, + pub hits: Option>, #[serde(rename = "request_params", skip_serializing_if = "Option::is_none")] - pub request_params: Option>, + pub request_params: Option>, + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option>, } -impl SearchResult { - pub fn new() -> Self { - Self { +impl SearchResult { + pub fn new() -> SearchResult { + SearchResult { facet_counts: None, found: None, + found_docs: None, search_time_ms: None, out_of: None, search_cutoff: None, @@ -48,6 +56,8 @@ impl SearchResult { grouped_hits: None, hits: None, request_params: None, + conversation: None, } } } + diff --git a/typesense_codegen/src/models/search_result_conversation.rs b/typesense_codegen/src/models/search_result_conversation.rs new file mode 100644 index 0000000..fc3b51a --- /dev/null +++ b/typesense_codegen/src/models/search_result_conversation.rs @@ -0,0 +1,36 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchResultConversation { + #[serde(rename = "answer")] + pub answer: String, + #[serde(rename = "conversation_history")] + pub conversation_history: Vec, + #[serde(rename = "conversation_id")] + pub conversation_id: String, + #[serde(rename = "query")] + pub query: String, +} + +impl SearchResultConversation { + pub fn new(answer: String, conversation_history: Vec, conversation_id: String, query: String) -> SearchResultConversation { + SearchResultConversation { + answer, + conversation_history, + conversation_id, + query, + } + } +} + diff --git a/typesense_codegen/src/models/search_result_hit.rs b/typesense_codegen/src/models/search_result_hit.rs index d637e65..6ba8770 100644 --- a/typesense_codegen/src/models/search_result_hit.rs +++ b/typesense_codegen/src/models/search_result_hit.rs @@ -3,44 +3,48 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct SearchResultHit { +pub struct SearchResultHit { /// (Deprecated) Contains highlighted portions of the search fields #[serde(rename = "highlights", skip_serializing_if = "Option::is_none")] - pub highlights: Option>, + pub highlights: Option>, /// Highlighted version of the matching document #[serde(rename = "highlight", skip_serializing_if = "Option::is_none")] - pub highlight: Option<::std::collections::HashMap>, + pub highlight: Option>, /// Can be any key-value pair #[serde(rename = "document", skip_serializing_if = "Option::is_none")] - pub document: Option, + pub document: Option, #[serde(rename = "text_match", skip_serializing_if = "Option::is_none")] pub text_match: Option, + #[serde(rename = "text_match_info", skip_serializing_if = "Option::is_none")] + pub text_match_info: Option>, /// Can be any key-value pair - #[serde( - rename = "geo_distance_meters", - skip_serializing_if = "Option::is_none" - )] - pub geo_distance_meters: Option<::std::collections::HashMap>, + #[serde(rename = "geo_distance_meters", skip_serializing_if = "Option::is_none")] + pub geo_distance_meters: Option>, /// Distance between the query vector and matching document's vector value #[serde(rename = "vector_distance", skip_serializing_if = "Option::is_none")] pub vector_distance: Option, } -impl SearchResultHit { - pub fn new() -> Self { - Self { +impl SearchResultHit { + pub fn new() -> SearchResultHit { + SearchResultHit { highlights: None, highlight: None, document: None, text_match: None, + text_match_info: None, geo_distance_meters: None, vector_distance: None, } } } + diff --git a/typesense_codegen/src/models/search_result_hit_text_match_info.rs b/typesense_codegen/src/models/search_result_hit_text_match_info.rs new file mode 100644 index 0000000..c1a7d1f --- /dev/null +++ b/typesense_codegen/src/models/search_result_hit_text_match_info.rs @@ -0,0 +1,45 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchResultHitTextMatchInfo { + #[serde(rename = "best_field_score", skip_serializing_if = "Option::is_none")] + pub best_field_score: Option, + #[serde(rename = "best_field_weight", skip_serializing_if = "Option::is_none")] + pub best_field_weight: Option, + #[serde(rename = "fields_matched", skip_serializing_if = "Option::is_none")] + pub fields_matched: Option, + #[serde(rename = "num_tokens_dropped", skip_serializing_if = "Option::is_none")] + pub num_tokens_dropped: Option, + #[serde(rename = "score", skip_serializing_if = "Option::is_none")] + pub score: Option, + #[serde(rename = "tokens_matched", skip_serializing_if = "Option::is_none")] + pub tokens_matched: Option, + #[serde(rename = "typo_prefix_score", skip_serializing_if = "Option::is_none")] + pub typo_prefix_score: Option, +} + +impl SearchResultHitTextMatchInfo { + pub fn new() -> SearchResultHitTextMatchInfo { + SearchResultHitTextMatchInfo { + best_field_score: None, + best_field_weight: None, + fields_matched: None, + num_tokens_dropped: None, + score: None, + tokens_matched: None, + typo_prefix_score: None, + } + } +} + diff --git a/typesense_codegen/src/models/search_result_request_params.rs b/typesense_codegen/src/models/search_result_request_params.rs index 94e323b..73f6294 100644 --- a/typesense_codegen/src/models/search_result_request_params.rs +++ b/typesense_codegen/src/models/search_result_request_params.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchResultRequestParams { #[serde(rename = "collection_name")] @@ -16,6 +19,8 @@ pub struct SearchResultRequestParams { pub q: String, #[serde(rename = "per_page")] pub per_page: i32, + #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] + pub voice_query: Option>, } impl SearchResultRequestParams { @@ -24,6 +29,8 @@ impl SearchResultRequestParams { collection_name, q, per_page, + voice_query: None, } } } + diff --git a/typesense_codegen/src/models/search_result_request_params_voice_query.rs b/typesense_codegen/src/models/search_result_request_params_voice_query.rs new file mode 100644 index 0000000..87ce57b --- /dev/null +++ b/typesense_codegen/src/models/search_result_request_params_voice_query.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchResultRequestParamsVoiceQuery { + #[serde(rename = "transcribed_query", skip_serializing_if = "Option::is_none")] + pub transcribed_query: Option, +} + +impl SearchResultRequestParamsVoiceQuery { + pub fn new() -> SearchResultRequestParamsVoiceQuery { + SearchResultRequestParamsVoiceQuery { + transcribed_query: None, + } + } +} + diff --git a/typesense_codegen/src/models/search_synonym.rs b/typesense_codegen/src/models/search_synonym.rs index acf9fd8..18d53fd 100644 --- a/typesense_codegen/src/models/search_synonym.rs +++ b/typesense_codegen/src/models/search_synonym.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchSynonym { /// For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. @@ -16,6 +19,12 @@ pub struct SearchSynonym { /// Array of words that should be considered as synonyms. #[serde(rename = "synonyms")] pub synonyms: Vec, + /// Locale for the synonym, leave blank to use the standard tokenizer. + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, + /// By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. + #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] + pub symbols_to_index: Option>, #[serde(rename = "id")] pub id: String, } @@ -25,7 +34,10 @@ impl SearchSynonym { SearchSynonym { root: None, synonyms, + locale: None, + symbols_to_index: None, id, } } } + diff --git a/typesense_codegen/src/models/search_synonym_delete_response.rs b/typesense_codegen/src/models/search_synonym_delete_response.rs new file mode 100644 index 0000000..06ff769 --- /dev/null +++ b/typesense_codegen/src/models/search_synonym_delete_response.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchSynonymDeleteResponse { + /// The id of the synonym that was deleted + #[serde(rename = "id")] + pub id: String, +} + +impl SearchSynonymDeleteResponse { + pub fn new(id: String) -> SearchSynonymDeleteResponse { + SearchSynonymDeleteResponse { + id, + } + } +} + diff --git a/typesense_codegen/src/models/search_synonym_schema.rs b/typesense_codegen/src/models/search_synonym_schema.rs index eab5596..548d405 100644 --- a/typesense_codegen/src/models/search_synonym_schema.rs +++ b/typesense_codegen/src/models/search_synonym_schema.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchSynonymSchema { /// For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. @@ -16,6 +19,12 @@ pub struct SearchSynonymSchema { /// Array of words that should be considered as synonyms. #[serde(rename = "synonyms")] pub synonyms: Vec, + /// Locale for the synonym, leave blank to use the standard tokenizer. + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, + /// By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. + #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] + pub symbols_to_index: Option>, } impl SearchSynonymSchema { @@ -23,6 +32,9 @@ impl SearchSynonymSchema { SearchSynonymSchema { root: None, synonyms, + locale: None, + symbols_to_index: None, } } } + diff --git a/typesense_codegen/src/models/search_synonyms_response.rs b/typesense_codegen/src/models/search_synonyms_response.rs index a3fefdf..d791123 100644 --- a/typesense_codegen/src/models/search_synonyms_response.rs +++ b/typesense_codegen/src/models/search_synonyms_response.rs @@ -3,19 +3,25 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchSynonymsResponse { #[serde(rename = "synonyms")] - pub synonyms: Vec, + pub synonyms: Vec, } impl SearchSynonymsResponse { - pub fn new(synonyms: Vec) -> SearchSynonymsResponse { - SearchSynonymsResponse { synonyms } + pub fn new(synonyms: Vec) -> SearchSynonymsResponse { + SearchSynonymsResponse { + synonyms, + } } } + diff --git a/typesense_codegen/src/models/snapshot_parameters.rs b/typesense_codegen/src/models/snapshot_parameters.rs index aa2c6a5..4a989ad 100644 --- a/typesense_codegen/src/models/snapshot_parameters.rs +++ b/typesense_codegen/src/models/snapshot_parameters.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SnapshotParameters { #[serde(rename = "snapshot_path", skip_serializing_if = "Option::is_none")] @@ -21,3 +24,4 @@ impl SnapshotParameters { } } } + diff --git a/typesense_codegen/src/models/stemming_dictionary.rs b/typesense_codegen/src/models/stemming_dictionary.rs new file mode 100644 index 0000000..78d997f --- /dev/null +++ b/typesense_codegen/src/models/stemming_dictionary.rs @@ -0,0 +1,32 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StemmingDictionary { + /// Unique identifier for the dictionary + #[serde(rename = "id")] + pub id: String, + /// List of word mappings in the dictionary + #[serde(rename = "words")] + pub words: Vec, +} + +impl StemmingDictionary { + pub fn new(id: String, words: Vec) -> StemmingDictionary { + StemmingDictionary { + id, + words, + } + } +} + diff --git a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs new file mode 100644 index 0000000..3afafab --- /dev/null +++ b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs @@ -0,0 +1,32 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StemmingDictionaryWordsInner { + /// The word form to be stemmed + #[serde(rename = "word")] + pub word: String, + /// The root form of the word + #[serde(rename = "root")] + pub root: String, +} + +impl StemmingDictionaryWordsInner { + pub fn new(word: String, root: String) -> StemmingDictionaryWordsInner { + StemmingDictionaryWordsInner { + word, + root, + } + } +} + diff --git a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs new file mode 100644 index 0000000..d4ec0c8 --- /dev/null +++ b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StopwordsSetRetrieveSchema { + #[serde(rename = "stopwords")] + pub stopwords: Box, +} + +impl StopwordsSetRetrieveSchema { + pub fn new(stopwords: models::StopwordsSetSchema) -> StopwordsSetRetrieveSchema { + StopwordsSetRetrieveSchema { + stopwords: Box::new(stopwords), + } + } +} + diff --git a/typesense_codegen/src/models/stopwords_set_schema.rs b/typesense_codegen/src/models/stopwords_set_schema.rs new file mode 100644 index 0000000..a515ce4 --- /dev/null +++ b/typesense_codegen/src/models/stopwords_set_schema.rs @@ -0,0 +1,33 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StopwordsSetSchema { + #[serde(rename = "id")] + pub id: String, + #[serde(rename = "stopwords")] + pub stopwords: Vec, + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, +} + +impl StopwordsSetSchema { + pub fn new(id: String, stopwords: Vec) -> StopwordsSetSchema { + StopwordsSetSchema { + id, + stopwords, + locale: None, + } + } +} + diff --git a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs new file mode 100644 index 0000000..9a9add2 --- /dev/null +++ b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs @@ -0,0 +1,30 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StopwordsSetUpsertSchema { + #[serde(rename = "stopwords")] + pub stopwords: Vec, + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, +} + +impl StopwordsSetUpsertSchema { + pub fn new(stopwords: Vec) -> StopwordsSetUpsertSchema { + StopwordsSetUpsertSchema { + stopwords, + locale: None, + } + } +} + diff --git a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs new file mode 100644 index 0000000..06344c6 --- /dev/null +++ b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StopwordsSetsRetrieveAllSchema { + #[serde(rename = "stopwords")] + pub stopwords: Vec, +} + +impl StopwordsSetsRetrieveAllSchema { + pub fn new(stopwords: Vec) -> StopwordsSetsRetrieveAllSchema { + StopwordsSetsRetrieveAllSchema { + stopwords, + } + } +} + diff --git a/typesense_codegen/src/models/success_status.rs b/typesense_codegen/src/models/success_status.rs index b7d3724..ee2ad94 100644 --- a/typesense_codegen/src/models/success_status.rs +++ b/typesense_codegen/src/models/success_status.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SuccessStatus { #[serde(rename = "success")] @@ -16,6 +19,9 @@ pub struct SuccessStatus { impl SuccessStatus { pub fn new(success: bool) -> SuccessStatus { - SuccessStatus { success } + SuccessStatus { + success, + } } } + diff --git a/typesense_codegen/src/models/update_documents_200_response.rs b/typesense_codegen/src/models/update_documents_200_response.rs index eff0990..e4be1a3 100644 --- a/typesense_codegen/src/models/update_documents_200_response.rs +++ b/typesense_codegen/src/models/update_documents_200_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct UpdateDocuments200Response { /// The number of documents that have been updated @@ -17,6 +20,9 @@ pub struct UpdateDocuments200Response { impl UpdateDocuments200Response { pub fn new(num_updated: i32) -> UpdateDocuments200Response { - UpdateDocuments200Response { num_updated } + UpdateDocuments200Response { + num_updated, + } } } + diff --git a/typesense_codegen/src/models/update_documents_parameters.rs b/typesense_codegen/src/models/update_documents_parameters.rs new file mode 100644 index 0000000..a4ff053 --- /dev/null +++ b/typesense_codegen/src/models/update_documents_parameters.rs @@ -0,0 +1,27 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct UpdateDocumentsParameters { + #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] + pub filter_by: Option, +} + +impl UpdateDocumentsParameters { + pub fn new() -> UpdateDocumentsParameters { + UpdateDocumentsParameters { + filter_by: None, + } + } +} + diff --git a/typesense_codegen/src/models/update_documents_update_documents_parameters_parameter.rs b/typesense_codegen/src/models/update_documents_update_documents_parameters_parameter.rs index aacf476..6eb1b10 100644 --- a/typesense_codegen/src/models/update_documents_update_documents_parameters_parameter.rs +++ b/typesense_codegen/src/models/update_documents_update_documents_parameters_parameter.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 - * + * The version of the OpenAPI document: 28.0 + * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct UpdateDocumentsUpdateDocumentsParametersParameter { #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] @@ -16,6 +19,9 @@ pub struct UpdateDocumentsUpdateDocumentsParametersParameter { impl UpdateDocumentsUpdateDocumentsParametersParameter { pub fn new() -> UpdateDocumentsUpdateDocumentsParametersParameter { - UpdateDocumentsUpdateDocumentsParametersParameter { filter_by: None } + UpdateDocumentsUpdateDocumentsParametersParameter { + filter_by: None, + } } } + diff --git a/typesense_codegen/src/models/voice_query_model_collection_config.rs b/typesense_codegen/src/models/voice_query_model_collection_config.rs new file mode 100644 index 0000000..0e97ec0 --- /dev/null +++ b/typesense_codegen/src/models/voice_query_model_collection_config.rs @@ -0,0 +1,29 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 28.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// VoiceQueryModelCollectionConfig : Configuration for the voice query model +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct VoiceQueryModelCollectionConfig { + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, +} + +impl VoiceQueryModelCollectionConfig { + /// Configuration for the voice query model + pub fn new() -> VoiceQueryModelCollectionConfig { + VoiceQueryModelCollectionConfig { + model_name: None, + } + } +} + diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml new file mode 100644 index 0000000..a394748 --- /dev/null +++ b/xtask/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "xtask" +version = "0.1.0" +edition = "2021" + +[dependencies] +reqwest = { version = "0.11", features = ["blocking"] } # "blocking" is simpler for scripts +anyhow = "1.0" +clap = { version = "4.0", features = ["derive"] } +serde = { version = "1.0", features = ["derive"] } +serde_yaml = "0.9" diff --git a/xtask/src/main.rs b/xtask/src/main.rs new file mode 100644 index 0000000..12be673 --- /dev/null +++ b/xtask/src/main.rs @@ -0,0 +1,136 @@ +use anyhow::{Context, Result}; +use clap::{Parser, ValueEnum}; +use std::env; +use std::fs; +use std::process::Command; +mod preprocess_openapi; +use preprocess_openapi::preprocess_openapi_file; + +const SPEC_URL: &str = + "https://raw.githubusercontent.com/typesense/typesense-api-spec/master/openapi.yml"; + +// Input spec file, expected in the project root. +const INPUT_SPEC_FILE: &str = "openapi.yml"; +const OUTPUT_PREPROCESSED_FILE: &str = "./preprocessed_openapi.yml"; + +// Output directory for the generated code. +const OUTPUT_DIR: &str = "typesense_codegen"; + +// 1. Define the command-line interface using clap's derive macros +#[derive(Parser)] +#[command( + author, + version, + about = "A task runner for the typesense-rust project" +)] +struct Cli { + /// The list of tasks to run in sequence. + #[arg(required = true, value_enum)] + tasks: Vec, +} + +// 2. Define the available tasks as a simple enum +#[derive(ValueEnum, Clone, Debug)] +#[clap(rename_all = "kebab-case")] // Allows user to type `code-gen` instead of `CodeGen` +enum Task { + /// Fetches the latest OpenAPI spec from the Typesense repository. + Fetch, + /// Generates client code from the spec file using the Docker container. + CodeGen, +} + +fn main() -> Result<()> { + let cli = Cli::parse(); + + for task in cli.tasks { + println!("▶️ Running task: {:?}", task); + match task { + Task::Fetch => task_fetch_api_spec()?, + Task::CodeGen => task_codegen()?, + } + } + Ok(()) +} + +fn task_fetch_api_spec() -> Result<()> { + println!("▶️ Running codegen task..."); + + println!(" - Downloading spec from {}", SPEC_URL); + let response = + reqwest::blocking::get(SPEC_URL).context("Failed to download OpenAPI spec file")?; + + if !response.status().is_success() { + anyhow::bail!("Failed to download spec: HTTP {}", response.status()); + } + + let spec_content = response.text()?; + fs::write(INPUT_SPEC_FILE, spec_content) + .context(format!("Failed to write spec to {}", INPUT_SPEC_FILE))?; + println!(" - Spec saved to {}", INPUT_SPEC_FILE); + + println!("✅ Fetch API spec task finished successfully."); + + Ok(()) +} + +/// Task to generate client code from the OpenAPI spec using a Docker container. +fn task_codegen() -> Result<()> { + println!("▶️ Running codegen task via Docker..."); + + println!("Preprocessing the Open API spec file..."); + preprocess_openapi_file(INPUT_SPEC_FILE, OUTPUT_PREPROCESSED_FILE) + .expect("Preprocess failed, aborting!"); + // 1. Get the absolute path to the project's root directory. + // std::env::current_dir() gives us the directory from which `cargo xtask` was run. + let project_root = env::current_dir().context("Failed to get current directory")?; + + // Check if the input spec file exists before trying to run Docker. + let input_spec_path = project_root.join(INPUT_SPEC_FILE); + if !input_spec_path.exists() { + anyhow::bail!( + "Input spec '{}' not found in project root. Please add it before running.", + INPUT_SPEC_FILE + ); + } + + // 2. Construct the volume mount string for Docker. + // Docker needs an absolute path for the volume mount source. + // to_string_lossy() is used to handle potential non-UTF8 paths gracefully. + let volume_mount = format!("{}:/local", project_root.to_string_lossy()); + println!(" - Using volume mount: {}", volume_mount); + + // 4. Set up and run the Docker command. + println!(" - Starting Docker container..."); + let status = Command::new("docker") + .arg("run") + .arg("--rm") // Remove the container after it exits + .arg("-v") + .arg(volume_mount) // Mount the project root to /local in the container + .arg("openapitools/openapi-generator-cli") + .arg("generate") + .arg("-i") + .arg(format!("/local/{}", OUTPUT_PREPROCESSED_FILE)) // Input path inside the container + .arg("-g") + .arg("rust") + .arg("-o") + .arg(format!("/local/{}", OUTPUT_DIR)) // Output path inside the container + .arg("--additional-properties") + .arg("library=reqwest") + .arg("--additional-properties") + .arg("supportMiddleware=true") + .arg("--additional-properties") + .arg("useSingleRequestParameter=true") + // .arg("--additional-properties") + // .arg("useBonBuilder=true") + .status() + .context("Failed to execute Docker command. Is Docker installed and running?")?; + + // 5. Check if the command was successful. + if !status.success() { + anyhow::bail!("Docker command failed with status: {}", status); + } + + println!("✅ Codegen task finished successfully."); + println!(" Generated code is available in '{}'", OUTPUT_DIR); + Ok(()) +} diff --git a/xtask/src/preprocess_openapi.rs b/xtask/src/preprocess_openapi.rs new file mode 100644 index 0000000..e7524a7 --- /dev/null +++ b/xtask/src/preprocess_openapi.rs @@ -0,0 +1,256 @@ +use serde_yaml::{Mapping, Value}; +use std::fs; + +// --- Main function to orchestrate the file reading, processing, and writing --- +pub fn preprocess_openapi_file( + input_path: &str, + output_path: &str, +) -> Result<(), Box> { + // --- Step 1: Read the OpenAPI spec from the input file --- + println!("Reading OpenAPI spec from {}...", input_path); + let input_content = fs::read_to_string(input_path) + .map_err(|e| format!("Failed to read {}: {}", input_path, e))?; + let mut doc: Value = serde_yaml::from_str(&input_content)?; + + // Ensure the root is a mutable mapping + let doc_root = doc + .as_mapping_mut() + .ok_or("OpenAPI spec root is not a YAML map")?; + + // --- Step 2: Apply all the required transformations --- + println!("Preprocessing the spec..."); + unwrap_search_parameters(doc_root)?; + unwrap_multi_search_parameters(doc_root)?; + unwrap_parameters_by_path( + doc_root, + "/collections/{collectionName}/documents/import", + "post", + "importDocumentsParameters", + Some("ImportDocumentsParameters"), // Copy schema to components + )?; + unwrap_parameters_by_path( + doc_root, + "/collections/{collectionName}/documents/export", + "get", + "exportDocumentsParameters", + Some("ExportDocumentsParameters"), // Copy schema to components + )?; + unwrap_parameters_by_path( + doc_root, + "/collections/{collectionName}/documents", + "patch", + "updateDocumentsParameters", + Some("UpdateDocumentsParameters"), // Copy schema to components + )?; + unwrap_parameters_by_path( + doc_root, + "/collections/{collectionName}/documents", + "delete", + "deleteDocumentsParameters", + Some("DeleteDocumentsParameters"), // Copy schema to components + )?; + remove_additional_properties_from_search_hit(doc_root)?; + println!("Preprocessing complete."); + + // --- Step 3: Serialize the modified spec and write to the output file --- + println!("Writing processed spec to {}...", output_path); + let output_yaml = serde_yaml::to_string(&doc)?; + fs::write(output_path, output_yaml) + .map_err(|e| format!("Failed to write {}: {}", output_path, e))?; + + println!("Successfully created {}.", output_path); + Ok(()) +} + +/// A generic function to: +/// 1. (Optional) Copy an inline parameter schema to `components/schemas`. +/// 2. Unwrap that parameter object into individual query parameters within the `paths` definition. +fn unwrap_parameters_by_path( + doc: &mut Mapping, + path: &str, + method: &str, + param_name_to_unwrap: &str, + new_component_name: Option<&str>, +) -> Result<(), String> { + // --- Step 1 (Optional): Copy the inline schema to components --- + if let Some(component_name) = new_component_name { + println!( + "- Copying inline schema for '{}' to components.schemas.{}...", + param_name_to_unwrap, component_name + ); + + // Find the parameter with the inline schema to copy using a read-only borrow + let params_for_copy = doc + .get("paths") + .and_then(|p| p.get(path)) + .and_then(|p| p.get(method)) + .and_then(|op| op.get("parameters")) + .and_then(|params| params.as_sequence()) + .ok_or_else(|| format!("Could not find parameters for {} {}", method, path))?; + + let param_to_copy = params_for_copy + .iter() + .find(|p| p.get("name").and_then(|n| n.as_str()) == Some(param_name_to_unwrap)) + .ok_or_else(|| format!("Parameter '{}' not found for copying", param_name_to_unwrap))?; + + let inline_schema = param_to_copy + .get("schema") + .cloned() // Clone the schema to avoid borrowing issues + .ok_or_else(|| format!("No schema found for '{}'", param_name_to_unwrap))?; + + // Get a mutable borrow to insert the cloned schema into components + let schemas = doc + .get_mut("components") + .and_then(|c| c.get_mut("schemas")) + .and_then(|s| s.as_mapping_mut()) + .ok_or_else(|| "Could not find components/schemas section".to_string())?; + + schemas.insert(component_name.into(), inline_schema); + } + + // --- Step 2: Unwrap the parameter object into individual parameters --- + println!( + "- Unwrapping parameter object '{}'...", + param_name_to_unwrap + ); + + // Navigate down to the operation's parameters list (mutable) + let params_for_unwrap = doc + .get_mut("paths") + .and_then(|p| p.get_mut(path)) + .and_then(|p| p.get_mut(method)) + .and_then(|op| op.get_mut("parameters")) + .and_then(|params| params.as_sequence_mut()) + .ok_or_else(|| format!("Could not find parameters for {} {}", method, path))?; + + let param_index = params_for_unwrap + .iter() + .position(|p| p.get("name").and_then(|n| n.as_str()) == Some(param_name_to_unwrap)) + .ok_or_else(|| format!("Parameter '{}' not found in {}", param_name_to_unwrap, path))?; + + let param_object = params_for_unwrap.remove(param_index); + let properties = param_object + .get("schema") + .and_then(|s| s.get("properties")) + .and_then(|p| p.as_mapping()) + .ok_or_else(|| { + format!( + "Could not extract properties from '{}'", + param_name_to_unwrap + ) + })?; + + for (key, value) in properties { + let mut new_param = Mapping::new(); + new_param.insert("name".into(), key.clone()); + new_param.insert("in".into(), "query".into()); + new_param.insert("schema".into(), value.clone()); + params_for_unwrap.push(new_param.into()); + } + + Ok(()) +} + +/// Special handler for unwrapping search parameters from `components/schemas`. +fn unwrap_search_parameters(doc: &mut Mapping) -> Result<(), String> { + println!("- Unwrapping searchParameters..."); + // Get the definition of SearchParameters from components + let search_params_props = doc + .get("components") + .and_then(|c| c.get("schemas")) + .and_then(|s| s.get("SearchParameters")) + .and_then(|sp| sp.get("properties")) + .and_then(|p| p.as_mapping()) + .cloned() // Clone to avoid borrowing issues + .ok_or_else(|| "Could not find schema for SearchParameters".to_string())?; + + // Navigate to the operation's parameters list + let params = doc + .get_mut("paths") + .and_then(|p| p.get_mut("/collections/{collectionName}/documents/search")) + .and_then(|p| p.get_mut("get")) + .and_then(|op| op.get_mut("parameters")) + .and_then(|params| params.as_sequence_mut()) + .ok_or_else(|| { + "Could not find parameters for /collections/{collectionName}/documents/search" + .to_string() + })?; + + // Find and remove the old parameter object. + let param_index = params + .iter() + .position(|p| p.get("name").and_then(|n| n.as_str()) == Some("searchParameters")) + .ok_or_else(|| "searchParameters object not found".to_string())?; + params.remove(param_index); + + // Add the new individual parameters. + for (key, value) in search_params_props { + let mut new_param = Mapping::new(); + new_param.insert("name".into(), key.clone()); + new_param.insert("in".into(), "query".into()); + new_param.insert("schema".into(), value.clone()); + params.push(new_param.into()); + } + + Ok(()) +} + +/// Special handler for unwrapping multi-search parameters from `components/schemas`. +fn unwrap_multi_search_parameters(doc: &mut Mapping) -> Result<(), String> { + println!("- Unwrapping multiSearchParameters..."); + // Get the definition of MultiSearchParameters from components + let search_params_props: Mapping = doc + .get("components") + .and_then(|c| c.get("schemas")) + .and_then(|s| s.get("MultiSearchParameters")) + .and_then(|sp| sp.get("properties")) + .and_then(|p| p.as_mapping()) + .cloned() + .ok_or_else(|| "Could not find schema for MultiSearchParameters".to_string())?; + + // Navigate to the operation's parameters list + let params = doc + .get_mut("paths") + .and_then(|p| p.get_mut("/multi_search")) + .and_then(|p| p.get_mut("post")) + .and_then(|op| op.get_mut("parameters")) + .and_then(|params| params.as_sequence_mut()) + .ok_or_else(|| "Could not find parameters for /multi_search".to_string())?; + + // Find and remove the old parameter object. + let param_index = params + .iter() + .position(|p| p.get("name").and_then(|n| n.as_str()) == Some("multiSearchParameters")) + .ok_or_else(|| "multiSearchParameters object not found".to_string())?; + params.remove(param_index); + + // Add the new individual parameters. + for (key, value) in search_params_props { + let mut new_param = Mapping::new(); + new_param.insert("name".into(), key.clone()); + new_param.insert("in".into(), "query".into()); + new_param.insert("schema".into(), value.clone()); + params.push(new_param.into()); + } + + Ok(()) +} + +/// Modifies the SearchResultHit schema to remove `additionalProperties` from the `document` field. +fn remove_additional_properties_from_search_hit(doc: &mut Mapping) -> Result<(), String> { + let document_prop = doc + .get_mut("components") + .and_then(|c| c.get_mut("schemas")) + .and_then(|s| s.get_mut("SearchResultHit")) + .and_then(|srh| srh.get_mut("properties")) + .and_then(|props| props.get_mut("document")) + .and_then(|doc_val| doc_val.as_mapping_mut()) + .ok_or_else(|| "Could not find document property in SearchResultHit schema".to_string())?; + + // Remove the 'additionalProperties' key + if document_prop.remove("additionalProperties").is_some() { + println!("- Removed additionalProperties from SearchResultHit.document"); + } + + Ok(()) +}