From f4d38afc8d37bd666f2893e49c38e979d925cec0 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sat, 29 Nov 2025 20:56:34 +0700 Subject: [PATCH 01/21] pull latest open api changes; migrate from Swagger Code-gen to OpenAPI Generator --- README.md | 2 +- .../Typesense/Models/APIStatsResponse.swift | 80 + Sources/Typesense/Models/AnalyticsEvent.swift | 42 + .../Models/AnalyticsEventCreateResponse.swift | 19 +- .../Models/AnalyticsEventCreateSchema.swift | 18 - .../Typesense/Models/AnalyticsEventData.swift | 49 + .../Models/AnalyticsEventsResponse.swift | 32 + .../AnalyticsEventsResponseEventsInner.swift | 60 + Sources/Typesense/Models/AnalyticsRule.swift | 58 + .../Models/AnalyticsRuleCreate.swift | 58 + .../Models/AnalyticsRuleCreateParams.swift | 56 + .../Models/AnalyticsRuleDeleteResponse.swift | 21 - .../Models/AnalyticsRuleParameters.swift | 33 - .../AnalyticsRuleParametersDestination.swift | 27 - .../AnalyticsRuleParametersSource.swift | 23 - .../AnalyticsRuleParametersSourceEvents.swift | 25 - .../Models/AnalyticsRuleSchema.swift | 23 - .../Models/AnalyticsRuleUpdate.swift | 41 + .../Models/AnalyticsRuleUpsertSchema.swift | 28 - .../Models/AnalyticsRulesRetrieveSchema.swift | 21 - .../Typesense/Models/AnalyticsStatus.swift | 56 + Sources/Typesense/Models/ApiKey.swift | 38 +- .../Models/ApiKeyDeleteResponse.swift | 33 + Sources/Typesense/Models/ApiKeySchema.swift | 30 +- .../Typesense/Models/ApiKeysResponse.swift | 19 +- Sources/Typesense/Models/ApiResponse.swift | 19 +- .../Typesense/Models/CollectionAlias.swift | 19 +- .../Models/CollectionAliasSchema.swift | 18 +- .../Models/CollectionAliasesResponse.swift | 19 +- .../Typesense/Models/CollectionResponse.swift | 53 +- .../Typesense/Models/CollectionSchema.swift | 42 +- .../Models/CollectionUpdateSchema.swift | 31 +- .../ConversationModelCreateSchema.swift | 42 +- .../Models/ConversationModelSchema.swift | 46 +- .../ConversationModelUpdateSchema.swift | 40 +- .../CreateAnalyticsRule200Response.swift | 38 + ...teAnalyticsRule200ResponseOneOfInner.swift | 62 + ...lyticsRule200ResponseOneOfInnerAnyOf.swift | 32 + .../Models/CreateAnalyticsRuleRequest.swift | 38 + .../Typesense/Models/CurationExclude.swift | 33 + .../Typesense/Models/CurationInclude.swift | 38 + .../Models/CurationItemCreateSchema.swift | 92 + .../Models/CurationItemDeleteSchema.swift | 33 + .../Typesense/Models/CurationItemSchema.swift | 91 + Sources/Typesense/Models/CurationRule.swift | 52 + .../Models/CurationSetCreateSchema.swift | 38 + .../Models/CurationSetDeleteSchema.swift | 33 + .../Typesense/Models/CurationSetSchema.swift | 42 + .../Typesense/Models/Debug200Response.swift | 32 + .../Models/DebugRetrieveSchema.swift | 16 - .../Models/DeleteDocuments200Response.swift | 32 + ...tsDeleteDocumentsParametersParameter.swift | 46 + .../Models/DeleteDocumentsParameters.swift | 31 - .../Models/DeleteDocumentsResponse.swift | 17 - .../DeleteStopwordsSet200Response.swift | 32 + Sources/Typesense/Models/DirtyValues.swift | 18 + .../Models/DocumentIndexParameters.swift | 17 - Sources/Typesense/Models/DropTokensMode.swift | 18 + ...tsExportDocumentsParametersParameter.swift | 43 + .../Models/ExportDocumentsParameters.swift | 33 - Sources/Typesense/Models/FacetCounts.swift | 24 +- .../Typesense/Models/FacetCountsCounts.swift | 25 - .../Models/FacetCountsCountsInner.swift | 44 + .../Typesense/Models/FacetCountsStats.swift | 22 +- Sources/Typesense/Models/Field.swift | 69 +- Sources/Typesense/Models/FieldEmbed.swift | 19 +- .../Models/FieldEmbedModelConfig.swift | 41 +- ...onsGetCollectionsParametersParameter.swift | 43 + Sources/Typesense/Models/HealthStatus.swift | 19 +- ...tsImportDocumentsParametersParameter.swift | 53 + .../Models/ImportDocumentsParameters.swift | 39 - Sources/Typesense/Models/IndexAction.swift | 18 + .../Typesense/Models/InlineResponse2002.swift | 21 - .../ListStemmingDictionaries200Response.swift | 32 + .../Typesense/Models/ModelErrorResponse.swift | 21 - .../MultiSearchCollectionParameters.swift | 187 +- .../Models/MultiSearchParameters.swift | 162 +- .../Typesense/Models/MultiSearchResult.swift | 27 +- .../Models/MultiSearchResultItem.swift | 98 + .../Models/MultiSearchSearchesParameter.swift | 27 +- .../Typesense/Models/NLSearchModelBase.swift | 118 + .../Models/NLSearchModelCreateSchema.swift | 123 + .../Models/NLSearchModelDeleteSchema.swift | 33 + .../Models/NLSearchModelSchema.swift | 123 + .../Typesense/Models/PresetDeleteSchema.swift | 19 +- Sources/Typesense/Models/PresetSchema.swift | 31 +- .../Typesense/Models/PresetUpsertSchema.swift | 26 +- .../Models/PresetUpsertSchemaValue.swift | 38 + Sources/Typesense/Models/PresetValue.swift | 28 - .../Models/PresetsRetrieveSchema.swift | 22 +- .../Typesense/Models/SchemaChangeStatus.swift | 43 + .../Models/ScopedKeyParameters.swift | 27 - .../Typesense/Models/SearchGroupedHit.swift | 19 +- .../Typesense/Models/SearchHighlight.swift | 28 +- Sources/Typesense/Models/SearchOverride.swift | 71 - .../Models/SearchOverrideDeleteResponse.swift | 25 - .../Models/SearchOverrideExclude.swift | 25 - .../Models/SearchOverrideInclude.swift | 29 - .../Typesense/Models/SearchOverrideRule.swift | 41 - .../Models/SearchOverrideSchema.swift | 68 - .../Models/SearchOverridesResponse.swift | 21 - .../Typesense/Models/SearchParameters.swift | 179 +- .../Models/SearchRequestParams.swift | 44 + .../SearchRequestParamsVoiceQuery.swift | 32 + Sources/Typesense/Models/SearchResult.swift | 47 +- .../Models/SearchResultConversation.swift | 25 +- .../Typesense/Models/SearchResultHit.swift | 61 +- .../SearchResultHitHybridSearchInfo.swift | 34 + .../Models/SearchResultHitTextMatchInfo.swift | 56 + .../Models/SearchResultRequestParams.swift | 33 - .../SearchResultRequestParamsVoiceQuery.swift | 24 - Sources/Typesense/Models/SearchSynonym.swift | 32 +- .../Models/SearchSynonymDeleteResponse.swift | 33 + .../Models/SearchSynonymSchema.swift | 23 +- .../Models/SearchSynonymsResponse.swift | 19 +- .../Typesense/Models/SnapshotParameters.swift | 24 - .../Typesense/Models/StemmingDictionary.swift | 38 + .../Models/StemmingDictionaryWordsInner.swift | 38 + .../Models/StopwordsSetDeleteSchema.swift | 16 - .../Models/StopwordsSetRetrieveSchema.swift | 19 +- .../Typesense/Models/StopwordsSetSchema.swift | 28 +- .../Models/StopwordsSetUpsertSchema.swift | 21 +- .../StopwordsSetsRetrieveAllSchema.swift | 19 +- Sources/Typesense/Models/SuccessStatus.swift | 19 +- .../Models/SynonymItemDeleteSchema.swift | 33 + .../Typesense/Models/SynonymItemSchema.swift | 53 + .../Models/SynonymSetCreateSchema.swift | 33 + .../Models/SynonymSetDeleteSchema.swift | 33 + .../Typesense/Models/SynonymSetSchema.swift | 38 + .../Models/SynonymSetsRetrieveSchema.swift | 33 + .../Models/ToggleSlowRequestLogRequest.swift | 32 + .../Models/UpdateByFilterResponse.swift | 25 - .../Models/UpdateDocuments200Response.swift | 33 + .../UpdateDocumentsByFilterParameters.swift | 24 - ...tsUpdateDocumentsParametersParameter.swift | 32 + .../VoiceQueryModelCollectionConfig.swift | 18 +- get-models.sh | 26 +- openapi.yml | 4613 +++++++++++++++++ 138 files changed, 8710 insertions(+), 1307 deletions(-) create mode 100644 Sources/Typesense/Models/APIStatsResponse.swift create mode 100644 Sources/Typesense/Models/AnalyticsEvent.swift delete mode 100644 Sources/Typesense/Models/AnalyticsEventCreateSchema.swift create mode 100644 Sources/Typesense/Models/AnalyticsEventData.swift create mode 100644 Sources/Typesense/Models/AnalyticsEventsResponse.swift create mode 100644 Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift create mode 100644 Sources/Typesense/Models/AnalyticsRule.swift create mode 100644 Sources/Typesense/Models/AnalyticsRuleCreate.swift create mode 100644 Sources/Typesense/Models/AnalyticsRuleCreateParams.swift delete mode 100644 Sources/Typesense/Models/AnalyticsRuleDeleteResponse.swift delete mode 100644 Sources/Typesense/Models/AnalyticsRuleParameters.swift delete mode 100644 Sources/Typesense/Models/AnalyticsRuleParametersDestination.swift delete mode 100644 Sources/Typesense/Models/AnalyticsRuleParametersSource.swift delete mode 100644 Sources/Typesense/Models/AnalyticsRuleParametersSourceEvents.swift delete mode 100644 Sources/Typesense/Models/AnalyticsRuleSchema.swift create mode 100644 Sources/Typesense/Models/AnalyticsRuleUpdate.swift delete mode 100644 Sources/Typesense/Models/AnalyticsRuleUpsertSchema.swift delete mode 100644 Sources/Typesense/Models/AnalyticsRulesRetrieveSchema.swift create mode 100644 Sources/Typesense/Models/AnalyticsStatus.swift create mode 100644 Sources/Typesense/Models/ApiKeyDeleteResponse.swift create mode 100644 Sources/Typesense/Models/CreateAnalyticsRule200Response.swift create mode 100644 Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInner.swift create mode 100644 Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift create mode 100644 Sources/Typesense/Models/CreateAnalyticsRuleRequest.swift create mode 100644 Sources/Typesense/Models/CurationExclude.swift create mode 100644 Sources/Typesense/Models/CurationInclude.swift create mode 100644 Sources/Typesense/Models/CurationItemCreateSchema.swift create mode 100644 Sources/Typesense/Models/CurationItemDeleteSchema.swift create mode 100644 Sources/Typesense/Models/CurationItemSchema.swift create mode 100644 Sources/Typesense/Models/CurationRule.swift create mode 100644 Sources/Typesense/Models/CurationSetCreateSchema.swift create mode 100644 Sources/Typesense/Models/CurationSetDeleteSchema.swift create mode 100644 Sources/Typesense/Models/CurationSetSchema.swift create mode 100644 Sources/Typesense/Models/Debug200Response.swift delete mode 100644 Sources/Typesense/Models/DebugRetrieveSchema.swift create mode 100644 Sources/Typesense/Models/DeleteDocuments200Response.swift create mode 100644 Sources/Typesense/Models/DeleteDocumentsDeleteDocumentsParametersParameter.swift delete mode 100644 Sources/Typesense/Models/DeleteDocumentsParameters.swift delete mode 100644 Sources/Typesense/Models/DeleteDocumentsResponse.swift create mode 100644 Sources/Typesense/Models/DeleteStopwordsSet200Response.swift create mode 100644 Sources/Typesense/Models/DirtyValues.swift delete mode 100644 Sources/Typesense/Models/DocumentIndexParameters.swift create mode 100644 Sources/Typesense/Models/DropTokensMode.swift create mode 100644 Sources/Typesense/Models/ExportDocumentsExportDocumentsParametersParameter.swift delete mode 100644 Sources/Typesense/Models/ExportDocumentsParameters.swift delete mode 100644 Sources/Typesense/Models/FacetCountsCounts.swift create mode 100644 Sources/Typesense/Models/FacetCountsCountsInner.swift create mode 100644 Sources/Typesense/Models/GetCollectionsGetCollectionsParametersParameter.swift create mode 100644 Sources/Typesense/Models/ImportDocumentsImportDocumentsParametersParameter.swift delete mode 100644 Sources/Typesense/Models/ImportDocumentsParameters.swift create mode 100644 Sources/Typesense/Models/IndexAction.swift delete mode 100644 Sources/Typesense/Models/InlineResponse2002.swift create mode 100644 Sources/Typesense/Models/ListStemmingDictionaries200Response.swift delete mode 100644 Sources/Typesense/Models/ModelErrorResponse.swift create mode 100644 Sources/Typesense/Models/MultiSearchResultItem.swift create mode 100644 Sources/Typesense/Models/NLSearchModelBase.swift create mode 100644 Sources/Typesense/Models/NLSearchModelCreateSchema.swift create mode 100644 Sources/Typesense/Models/NLSearchModelDeleteSchema.swift create mode 100644 Sources/Typesense/Models/NLSearchModelSchema.swift create mode 100644 Sources/Typesense/Models/PresetUpsertSchemaValue.swift delete mode 100644 Sources/Typesense/Models/PresetValue.swift create mode 100644 Sources/Typesense/Models/SchemaChangeStatus.swift delete mode 100644 Sources/Typesense/Models/ScopedKeyParameters.swift delete mode 100644 Sources/Typesense/Models/SearchOverride.swift delete mode 100644 Sources/Typesense/Models/SearchOverrideDeleteResponse.swift delete mode 100644 Sources/Typesense/Models/SearchOverrideExclude.swift delete mode 100644 Sources/Typesense/Models/SearchOverrideInclude.swift delete mode 100644 Sources/Typesense/Models/SearchOverrideRule.swift delete mode 100644 Sources/Typesense/Models/SearchOverrideSchema.swift delete mode 100644 Sources/Typesense/Models/SearchOverridesResponse.swift create mode 100644 Sources/Typesense/Models/SearchRequestParams.swift create mode 100644 Sources/Typesense/Models/SearchRequestParamsVoiceQuery.swift create mode 100644 Sources/Typesense/Models/SearchResultHitHybridSearchInfo.swift create mode 100644 Sources/Typesense/Models/SearchResultHitTextMatchInfo.swift delete mode 100644 Sources/Typesense/Models/SearchResultRequestParams.swift delete mode 100644 Sources/Typesense/Models/SearchResultRequestParamsVoiceQuery.swift create mode 100644 Sources/Typesense/Models/SearchSynonymDeleteResponse.swift delete mode 100644 Sources/Typesense/Models/SnapshotParameters.swift create mode 100644 Sources/Typesense/Models/StemmingDictionary.swift create mode 100644 Sources/Typesense/Models/StemmingDictionaryWordsInner.swift delete mode 100644 Sources/Typesense/Models/StopwordsSetDeleteSchema.swift create mode 100644 Sources/Typesense/Models/SynonymItemDeleteSchema.swift create mode 100644 Sources/Typesense/Models/SynonymItemSchema.swift create mode 100644 Sources/Typesense/Models/SynonymSetCreateSchema.swift create mode 100644 Sources/Typesense/Models/SynonymSetDeleteSchema.swift create mode 100644 Sources/Typesense/Models/SynonymSetSchema.swift create mode 100644 Sources/Typesense/Models/SynonymSetsRetrieveSchema.swift create mode 100644 Sources/Typesense/Models/ToggleSlowRequestLogRequest.swift delete mode 100644 Sources/Typesense/Models/UpdateByFilterResponse.swift create mode 100644 Sources/Typesense/Models/UpdateDocuments200Response.swift delete mode 100644 Sources/Typesense/Models/UpdateDocumentsByFilterParameters.swift create mode 100644 Sources/Typesense/Models/UpdateDocumentsUpdateDocumentsParametersParameter.swift mode change 100644 => 100755 get-models.sh create mode 100644 openapi.yml diff --git a/README.md b/README.md index 6fe5918..17b8fcf 100644 --- a/README.md +++ b/README.md @@ -390,7 +390,7 @@ let (data, response) = try await client.operations().snapshot(path: "/tmp/typese ## Contributing -Issues and pull requests are welcome on GitHub at [Typesense Swift](https://github.com/typesense/typesense-swift). Do note that the Models used in the Swift client are generated by [Swagger-Codegen](https://github.com/swagger-api/swagger-codegen) and are automated to be modified in order to prevent major errors. So please do use the shell script that is provided in the repo to generate the models: +Issues and pull requests are welcome on GitHub at [Typesense Swift](https://github.com/typesense/typesense-swift). Do note that the Models used in the Swift client are generated by [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator) and are automated to be modified in order to prevent major errors. So please do use the shell script that is provided in the repo to generate the models: ```shell sh get-models.sh diff --git a/Sources/Typesense/Models/APIStatsResponse.swift b/Sources/Typesense/Models/APIStatsResponse.swift new file mode 100644 index 0000000..3a718a0 --- /dev/null +++ b/Sources/Typesense/Models/APIStatsResponse.swift @@ -0,0 +1,80 @@ +// +// APIStatsResponse.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct APIStatsResponse: Codable { + + public var deleteLatencyMs: Double? + public var deleteRequestsPerSecond: Double? + public var importLatencyMs: Double? + public var importRequestsPerSecond: Double? + public var latencyMs: AnyCodable? + public var overloadedRequestsPerSecond: Double? + public var pendingWriteBatches: Double? + public var requestsPerSecond: AnyCodable? + public var searchLatencyMs: Double? + public var searchRequestsPerSecond: Double? + public var totalRequestsPerSecond: Double? + public var writeLatencyMs: Double? + public var writeRequestsPerSecond: Double? + + public init(deleteLatencyMs: Double? = nil, deleteRequestsPerSecond: Double? = nil, importLatencyMs: Double? = nil, importRequestsPerSecond: Double? = nil, latencyMs: AnyCodable? = nil, overloadedRequestsPerSecond: Double? = nil, pendingWriteBatches: Double? = nil, requestsPerSecond: AnyCodable? = nil, searchLatencyMs: Double? = nil, searchRequestsPerSecond: Double? = nil, totalRequestsPerSecond: Double? = nil, writeLatencyMs: Double? = nil, writeRequestsPerSecond: Double? = nil) { + self.deleteLatencyMs = deleteLatencyMs + self.deleteRequestsPerSecond = deleteRequestsPerSecond + self.importLatencyMs = importLatencyMs + self.importRequestsPerSecond = importRequestsPerSecond + self.latencyMs = latencyMs + self.overloadedRequestsPerSecond = overloadedRequestsPerSecond + self.pendingWriteBatches = pendingWriteBatches + self.requestsPerSecond = requestsPerSecond + self.searchLatencyMs = searchLatencyMs + self.searchRequestsPerSecond = searchRequestsPerSecond + self.totalRequestsPerSecond = totalRequestsPerSecond + self.writeLatencyMs = writeLatencyMs + self.writeRequestsPerSecond = writeRequestsPerSecond + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case deleteLatencyMs = "delete_latency_ms" + case deleteRequestsPerSecond = "delete_requests_per_second" + case importLatencyMs = "import_latency_ms" + case importRequestsPerSecond = "import_requests_per_second" + case latencyMs = "latency_ms" + case overloadedRequestsPerSecond = "overloaded_requests_per_second" + case pendingWriteBatches = "pending_write_batches" + case requestsPerSecond = "requests_per_second" + case searchLatencyMs = "search_latency_ms" + case searchRequestsPerSecond = "search_requests_per_second" + case totalRequestsPerSecond = "total_requests_per_second" + case writeLatencyMs = "write_latency_ms" + case writeRequestsPerSecond = "write_requests_per_second" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(deleteLatencyMs, forKey: .deleteLatencyMs) + try container.encodeIfPresent(deleteRequestsPerSecond, forKey: .deleteRequestsPerSecond) + try container.encodeIfPresent(importLatencyMs, forKey: .importLatencyMs) + try container.encodeIfPresent(importRequestsPerSecond, forKey: .importRequestsPerSecond) + try container.encodeIfPresent(latencyMs, forKey: .latencyMs) + try container.encodeIfPresent(overloadedRequestsPerSecond, forKey: .overloadedRequestsPerSecond) + try container.encodeIfPresent(pendingWriteBatches, forKey: .pendingWriteBatches) + try container.encodeIfPresent(requestsPerSecond, forKey: .requestsPerSecond) + try container.encodeIfPresent(searchLatencyMs, forKey: .searchLatencyMs) + try container.encodeIfPresent(searchRequestsPerSecond, forKey: .searchRequestsPerSecond) + try container.encodeIfPresent(totalRequestsPerSecond, forKey: .totalRequestsPerSecond) + try container.encodeIfPresent(writeLatencyMs, forKey: .writeLatencyMs) + try container.encodeIfPresent(writeRequestsPerSecond, forKey: .writeRequestsPerSecond) + } +} + diff --git a/Sources/Typesense/Models/AnalyticsEvent.swift b/Sources/Typesense/Models/AnalyticsEvent.swift new file mode 100644 index 0000000..04ce95e --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsEvent.swift @@ -0,0 +1,42 @@ +// +// AnalyticsEvent.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AnalyticsEvent: Codable { + + /** Name of the analytics rule this event corresponds to */ + public var name: String + /** Type of event (e.g., click, conversion, query, visit) */ + public var eventType: String + public var data: AnalyticsEventData + + public init(name: String, eventType: String, data: AnalyticsEventData) { + self.name = name + self.eventType = eventType + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case eventType = "event_type" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(eventType, forKey: .eventType) + try container.encode(data, forKey: .data) + } +} + diff --git a/Sources/Typesense/Models/AnalyticsEventCreateResponse.swift b/Sources/Typesense/Models/AnalyticsEventCreateResponse.swift index f810735..74ece77 100644 --- a/Sources/Typesense/Models/AnalyticsEventCreateResponse.swift +++ b/Sources/Typesense/Models/AnalyticsEventCreateResponse.swift @@ -1,13 +1,14 @@ // // AnalyticsEventCreateResponse.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct AnalyticsEventCreateResponse: Codable { @@ -17,5 +18,15 @@ public struct AnalyticsEventCreateResponse: Codable { self.ok = ok } + public enum CodingKeys: String, CodingKey, CaseIterable { + case ok + } + + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(ok, forKey: .ok) + } } + diff --git a/Sources/Typesense/Models/AnalyticsEventCreateSchema.swift b/Sources/Typesense/Models/AnalyticsEventCreateSchema.swift deleted file mode 100644 index 46ea05e..0000000 --- a/Sources/Typesense/Models/AnalyticsEventCreateSchema.swift +++ /dev/null @@ -1,18 +0,0 @@ -import Foundation - - - -public struct AnalyticsEventCreateSchema: Encodable { - - public var type: String - public var name: String - public var data: T - - public init(type: String, name: String, data: T) { - self.type = type - self.name = name - self.data = data - } - - -} diff --git a/Sources/Typesense/Models/AnalyticsEventData.swift b/Sources/Typesense/Models/AnalyticsEventData.swift new file mode 100644 index 0000000..23d6d3d --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsEventData.swift @@ -0,0 +1,49 @@ +// +// AnalyticsEventData.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Event payload */ +public struct AnalyticsEventData: Codable { + + public var userId: String? + public var docId: String? + public var docIds: [String]? + public var q: String? + public var analyticsTag: String? + + public init(userId: String? = nil, docId: String? = nil, docIds: [String]? = nil, q: String? = nil, analyticsTag: String? = nil) { + self.userId = userId + self.docId = docId + self.docIds = docIds + self.q = q + self.analyticsTag = analyticsTag + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case userId = "user_id" + case docId = "doc_id" + case docIds = "doc_ids" + case q + case analyticsTag = "analytics_tag" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(userId, forKey: .userId) + try container.encodeIfPresent(docId, forKey: .docId) + try container.encodeIfPresent(docIds, forKey: .docIds) + try container.encodeIfPresent(q, forKey: .q) + try container.encodeIfPresent(analyticsTag, forKey: .analyticsTag) + } +} + diff --git a/Sources/Typesense/Models/AnalyticsEventsResponse.swift b/Sources/Typesense/Models/AnalyticsEventsResponse.swift new file mode 100644 index 0000000..a25fe97 --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsEventsResponse.swift @@ -0,0 +1,32 @@ +// +// AnalyticsEventsResponse.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AnalyticsEventsResponse: Codable { + + public var events: [AnalyticsEventsResponseEventsInner] + + public init(events: [AnalyticsEventsResponseEventsInner]) { + self.events = events + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case events + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(events, forKey: .events) + } +} + diff --git a/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift b/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift new file mode 100644 index 0000000..75b867a --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift @@ -0,0 +1,60 @@ +// +// AnalyticsEventsResponseEventsInner.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AnalyticsEventsResponseEventsInner: Codable { + + public var name: String? + public var eventType: String? + public var collection: String? + public var timestamp: Int64? + public var userId: String? + public var docId: String? + public var docIds: [String]? + public var query: String? + + public init(name: String? = nil, eventType: String? = nil, collection: String? = nil, timestamp: Int64? = nil, userId: String? = nil, docId: String? = nil, docIds: [String]? = nil, query: String? = nil) { + self.name = name + self.eventType = eventType + self.collection = collection + self.timestamp = timestamp + self.userId = userId + self.docId = docId + self.docIds = docIds + self.query = query + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case eventType = "event_type" + case collection + case timestamp + case userId = "user_id" + case docId = "doc_id" + case docIds = "doc_ids" + case query + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(eventType, forKey: .eventType) + try container.encodeIfPresent(collection, forKey: .collection) + try container.encodeIfPresent(timestamp, forKey: .timestamp) + try container.encodeIfPresent(userId, forKey: .userId) + try container.encodeIfPresent(docId, forKey: .docId) + try container.encodeIfPresent(docIds, forKey: .docIds) + try container.encodeIfPresent(query, forKey: .query) + } +} + diff --git a/Sources/Typesense/Models/AnalyticsRule.swift b/Sources/Typesense/Models/AnalyticsRule.swift new file mode 100644 index 0000000..a9b5650 --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsRule.swift @@ -0,0 +1,58 @@ +// +// AnalyticsRule.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AnalyticsRule: Codable { + + public enum ModelType: String, Codable, CaseIterable { + case popularQueries = "popular_queries" + case nohitsQueries = "nohits_queries" + case counter = "counter" + case log = "log" + } + public var name: String + public var type: ModelType + public var collection: String + public var eventType: String + public var ruleTag: String? + public var params: AnalyticsRuleCreateParams? + + public init(name: String, type: ModelType, collection: String, eventType: String, ruleTag: String? = nil, params: AnalyticsRuleCreateParams? = nil) { + self.name = name + self.type = type + self.collection = collection + self.eventType = eventType + self.ruleTag = ruleTag + self.params = params + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case type + case collection + case eventType = "event_type" + case ruleTag = "rule_tag" + case params + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(type, forKey: .type) + try container.encode(collection, forKey: .collection) + try container.encode(eventType, forKey: .eventType) + try container.encodeIfPresent(ruleTag, forKey: .ruleTag) + try container.encodeIfPresent(params, forKey: .params) + } +} + diff --git a/Sources/Typesense/Models/AnalyticsRuleCreate.swift b/Sources/Typesense/Models/AnalyticsRuleCreate.swift new file mode 100644 index 0000000..c772d13 --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsRuleCreate.swift @@ -0,0 +1,58 @@ +// +// AnalyticsRuleCreate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AnalyticsRuleCreate: Codable { + + public enum ModelType: String, Codable, CaseIterable { + case popularQueries = "popular_queries" + case nohitsQueries = "nohits_queries" + case counter = "counter" + case log = "log" + } + public var name: String + public var type: ModelType + public var collection: String + public var eventType: String + public var ruleTag: String? + public var params: AnalyticsRuleCreateParams? + + public init(name: String, type: ModelType, collection: String, eventType: String, ruleTag: String? = nil, params: AnalyticsRuleCreateParams? = nil) { + self.name = name + self.type = type + self.collection = collection + self.eventType = eventType + self.ruleTag = ruleTag + self.params = params + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case type + case collection + case eventType = "event_type" + case ruleTag = "rule_tag" + case params + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(type, forKey: .type) + try container.encode(collection, forKey: .collection) + try container.encode(eventType, forKey: .eventType) + try container.encodeIfPresent(ruleTag, forKey: .ruleTag) + try container.encodeIfPresent(params, forKey: .params) + } +} + diff --git a/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift b/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift new file mode 100644 index 0000000..3bc547a --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift @@ -0,0 +1,56 @@ +// +// AnalyticsRuleCreateParams.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AnalyticsRuleCreateParams: Codable { + + public var destinationCollection: String? + public var limit: Int? + public var captureSearchRequests: Bool? + public var metaFields: [String]? + public var expandQuery: Bool? + public var counterField: String? + public var weight: Int? + + public init(destinationCollection: String? = nil, limit: Int? = nil, captureSearchRequests: Bool? = nil, metaFields: [String]? = nil, expandQuery: Bool? = nil, counterField: String? = nil, weight: Int? = nil) { + self.destinationCollection = destinationCollection + self.limit = limit + self.captureSearchRequests = captureSearchRequests + self.metaFields = metaFields + self.expandQuery = expandQuery + self.counterField = counterField + self.weight = weight + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case destinationCollection = "destination_collection" + case limit + case captureSearchRequests = "capture_search_requests" + case metaFields = "meta_fields" + case expandQuery = "expand_query" + case counterField = "counter_field" + case weight + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(destinationCollection, forKey: .destinationCollection) + try container.encodeIfPresent(limit, forKey: .limit) + try container.encodeIfPresent(captureSearchRequests, forKey: .captureSearchRequests) + try container.encodeIfPresent(metaFields, forKey: .metaFields) + try container.encodeIfPresent(expandQuery, forKey: .expandQuery) + try container.encodeIfPresent(counterField, forKey: .counterField) + try container.encodeIfPresent(weight, forKey: .weight) + } +} + diff --git a/Sources/Typesense/Models/AnalyticsRuleDeleteResponse.swift b/Sources/Typesense/Models/AnalyticsRuleDeleteResponse.swift deleted file mode 100644 index 4d43b72..0000000 --- a/Sources/Typesense/Models/AnalyticsRuleDeleteResponse.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// AnalyticsRuleDeleteResponse.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct AnalyticsRuleDeleteResponse: Codable { - - public var name: String - - public init(name: String) { - self.name = name - } - - -} diff --git a/Sources/Typesense/Models/AnalyticsRuleParameters.swift b/Sources/Typesense/Models/AnalyticsRuleParameters.swift deleted file mode 100644 index f15cd71..0000000 --- a/Sources/Typesense/Models/AnalyticsRuleParameters.swift +++ /dev/null @@ -1,33 +0,0 @@ -// -// AnalyticsRuleParameters.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct AnalyticsRuleParameters: Codable { - - public var source: AnalyticsRuleParametersSource - public var destination: AnalyticsRuleParametersDestination - public var limit: Int? - public var expandQuery: Bool? - - public init(source: AnalyticsRuleParametersSource, destination: AnalyticsRuleParametersDestination, limit: Int? = nil, expandQuery: Bool? = nil) { - self.source = source - self.destination = destination - self.limit = limit - self.expandQuery = expandQuery - } - - public enum CodingKeys: String, CodingKey { - case source - case destination - case limit - case expandQuery = "expand_query" - } - -} diff --git a/Sources/Typesense/Models/AnalyticsRuleParametersDestination.swift b/Sources/Typesense/Models/AnalyticsRuleParametersDestination.swift deleted file mode 100644 index f16529e..0000000 --- a/Sources/Typesense/Models/AnalyticsRuleParametersDestination.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// AnalyticsRuleParametersDestination.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct AnalyticsRuleParametersDestination: Codable { - - public var collection: String - public var counterField: String? - - public init(collection: String, counterField: String? = nil) { - self.collection = collection - self.counterField = counterField - } - - public enum CodingKeys: String, CodingKey { - case collection - case counterField = "counter_field" - } - -} diff --git a/Sources/Typesense/Models/AnalyticsRuleParametersSource.swift b/Sources/Typesense/Models/AnalyticsRuleParametersSource.swift deleted file mode 100644 index 3cc093a..0000000 --- a/Sources/Typesense/Models/AnalyticsRuleParametersSource.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// AnalyticsRuleParametersSource.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct AnalyticsRuleParametersSource: Codable { - - public var collections: [String] - public var events: [AnalyticsRuleParametersSourceEvents]? - - public init(collections: [String], events: [AnalyticsRuleParametersSourceEvents]? = nil) { - self.collections = collections - self.events = events - } - - -} diff --git a/Sources/Typesense/Models/AnalyticsRuleParametersSourceEvents.swift b/Sources/Typesense/Models/AnalyticsRuleParametersSourceEvents.swift deleted file mode 100644 index 382648e..0000000 --- a/Sources/Typesense/Models/AnalyticsRuleParametersSourceEvents.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// AnalyticsRuleParametersSourceEvents.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct AnalyticsRuleParametersSourceEvents: Codable { - - public var type: String - public var weight: Float - public var name: String - - public init(type: String, weight: Float, name: String) { - self.type = type - self.weight = weight - self.name = name - } - - -} diff --git a/Sources/Typesense/Models/AnalyticsRuleSchema.swift b/Sources/Typesense/Models/AnalyticsRuleSchema.swift deleted file mode 100644 index 6f16f9c..0000000 --- a/Sources/Typesense/Models/AnalyticsRuleSchema.swift +++ /dev/null @@ -1,23 +0,0 @@ -import Foundation - - - -public struct AnalyticsRuleSchema: Codable { - - public enum RuleType: String, Codable { - case popularQueries = "popular_queries" - case nohitsQueries = "nohits_queries" - case counter = "counter" - } - public var name: String - public var type: RuleType - public var params: AnalyticsRuleParameters - - public init(name: String, type: RuleType, params: AnalyticsRuleParameters) { - self.name = name - self.type = type - self.params = params - } - - -} diff --git a/Sources/Typesense/Models/AnalyticsRuleUpdate.swift b/Sources/Typesense/Models/AnalyticsRuleUpdate.swift new file mode 100644 index 0000000..ecb8a93 --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsRuleUpdate.swift @@ -0,0 +1,41 @@ +// +// AnalyticsRuleUpdate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Fields allowed to update on an analytics rule */ +public struct AnalyticsRuleUpdate: Codable { + + public var name: String? + public var ruleTag: String? + public var params: AnalyticsRuleCreateParams? + + public init(name: String? = nil, ruleTag: String? = nil, params: AnalyticsRuleCreateParams? = nil) { + self.name = name + self.ruleTag = ruleTag + self.params = params + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case ruleTag = "rule_tag" + case params + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(ruleTag, forKey: .ruleTag) + try container.encodeIfPresent(params, forKey: .params) + } +} + diff --git a/Sources/Typesense/Models/AnalyticsRuleUpsertSchema.swift b/Sources/Typesense/Models/AnalyticsRuleUpsertSchema.swift deleted file mode 100644 index 771cc2c..0000000 --- a/Sources/Typesense/Models/AnalyticsRuleUpsertSchema.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// AnalyticsRuleUpsertSchema.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct AnalyticsRuleUpsertSchema: Codable { - - public enum ModelType: String, Codable { - case popularQueries = "popular_queries" - case nohitsQueries = "nohits_queries" - case counter = "counter" - } - public var type: ModelType - public var params: AnalyticsRuleParameters - - public init(type: ModelType, params: AnalyticsRuleParameters) { - self.type = type - self.params = params - } - - -} diff --git a/Sources/Typesense/Models/AnalyticsRulesRetrieveSchema.swift b/Sources/Typesense/Models/AnalyticsRulesRetrieveSchema.swift deleted file mode 100644 index 802236d..0000000 --- a/Sources/Typesense/Models/AnalyticsRulesRetrieveSchema.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// AnalyticsRulesRetrieveSchema.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct AnalyticsRulesRetrieveSchema: Codable { - - public var rules: [AnalyticsRuleSchema]? - - public init(rules: [AnalyticsRuleSchema]? = nil) { - self.rules = rules - } - - -} diff --git a/Sources/Typesense/Models/AnalyticsStatus.swift b/Sources/Typesense/Models/AnalyticsStatus.swift new file mode 100644 index 0000000..875c910 --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsStatus.swift @@ -0,0 +1,56 @@ +// +// AnalyticsStatus.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AnalyticsStatus: Codable { + + public var popularPrefixQueries: Int? + public var nohitsPrefixQueries: Int? + public var logPrefixQueries: Int? + public var queryLogEvents: Int? + public var queryCounterEvents: Int? + public var docLogEvents: Int? + public var docCounterEvents: Int? + + public init(popularPrefixQueries: Int? = nil, nohitsPrefixQueries: Int? = nil, logPrefixQueries: Int? = nil, queryLogEvents: Int? = nil, queryCounterEvents: Int? = nil, docLogEvents: Int? = nil, docCounterEvents: Int? = nil) { + self.popularPrefixQueries = popularPrefixQueries + self.nohitsPrefixQueries = nohitsPrefixQueries + self.logPrefixQueries = logPrefixQueries + self.queryLogEvents = queryLogEvents + self.queryCounterEvents = queryCounterEvents + self.docLogEvents = docLogEvents + self.docCounterEvents = docCounterEvents + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case popularPrefixQueries = "popular_prefix_queries" + case nohitsPrefixQueries = "nohits_prefix_queries" + case logPrefixQueries = "log_prefix_queries" + case queryLogEvents = "query_log_events" + case queryCounterEvents = "query_counter_events" + case docLogEvents = "doc_log_events" + case docCounterEvents = "doc_counter_events" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(popularPrefixQueries, forKey: .popularPrefixQueries) + try container.encodeIfPresent(nohitsPrefixQueries, forKey: .nohitsPrefixQueries) + try container.encodeIfPresent(logPrefixQueries, forKey: .logPrefixQueries) + try container.encodeIfPresent(queryLogEvents, forKey: .queryLogEvents) + try container.encodeIfPresent(queryCounterEvents, forKey: .queryCounterEvents) + try container.encodeIfPresent(docLogEvents, forKey: .docLogEvents) + try container.encodeIfPresent(docCounterEvents, forKey: .docCounterEvents) + } +} + diff --git a/Sources/Typesense/Models/ApiKey.swift b/Sources/Typesense/Models/ApiKey.swift index 12755da..55f37c3 100644 --- a/Sources/Typesense/Models/ApiKey.swift +++ b/Sources/Typesense/Models/ApiKey.swift @@ -1,42 +1,56 @@ // // ApiKey.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ApiKey: Codable { public var value: String? - public var _description: String + public var description: String public var actions: [String] public var collections: [String] public var expiresAt: Int64? - public var _id: Int + public var id: Int64? public var valuePrefix: String? - public init(value: String? = nil, _description: String, actions: [String], collections: [String], expiresAt: Int64? = nil, _id: Int, valuePrefix: String? = nil) { + public init(value: String? = nil, description: String, actions: [String], collections: [String], expiresAt: Int64? = nil, id: Int64? = nil, valuePrefix: String? = nil) { self.value = value - self._description = _description + self.description = description self.actions = actions self.collections = collections self.expiresAt = expiresAt - self._id = _id + self.id = id self.valuePrefix = valuePrefix } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case value - case _description = "description" + case description case actions case collections case expiresAt = "expires_at" - case _id = "id" + case id case valuePrefix = "value_prefix" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(value, forKey: .value) + try container.encode(description, forKey: .description) + try container.encode(actions, forKey: .actions) + try container.encode(collections, forKey: .collections) + try container.encodeIfPresent(expiresAt, forKey: .expiresAt) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(valuePrefix, forKey: .valuePrefix) + } } + diff --git a/Sources/Typesense/Models/ApiKeyDeleteResponse.swift b/Sources/Typesense/Models/ApiKeyDeleteResponse.swift new file mode 100644 index 0000000..1be4627 --- /dev/null +++ b/Sources/Typesense/Models/ApiKeyDeleteResponse.swift @@ -0,0 +1,33 @@ +// +// ApiKeyDeleteResponse.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ApiKeyDeleteResponse: Codable { + + /** The id of the API key that was deleted */ + public var id: Int64 + + public init(id: Int64) { + self.id = id + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + } +} + diff --git a/Sources/Typesense/Models/ApiKeySchema.swift b/Sources/Typesense/Models/ApiKeySchema.swift index 8f3e754..40eccb6 100644 --- a/Sources/Typesense/Models/ApiKeySchema.swift +++ b/Sources/Typesense/Models/ApiKeySchema.swift @@ -1,36 +1,48 @@ // // ApiKeySchema.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ApiKeySchema: Codable { public var value: String? - public var _description: String + public var description: String public var actions: [String] public var collections: [String] public var expiresAt: Int64? - public init(value: String? = nil, _description: String, actions: [String], collections: [String], expiresAt: Int64? = nil) { + public init(value: String? = nil, description: String, actions: [String], collections: [String], expiresAt: Int64? = nil) { self.value = value - self._description = _description + self.description = description self.actions = actions self.collections = collections self.expiresAt = expiresAt } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case value - case _description = "description" + case description case actions case collections case expiresAt = "expires_at" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(value, forKey: .value) + try container.encode(description, forKey: .description) + try container.encode(actions, forKey: .actions) + try container.encode(collections, forKey: .collections) + try container.encodeIfPresent(expiresAt, forKey: .expiresAt) + } } + diff --git a/Sources/Typesense/Models/ApiKeysResponse.swift b/Sources/Typesense/Models/ApiKeysResponse.swift index f65d42f..27e2e96 100644 --- a/Sources/Typesense/Models/ApiKeysResponse.swift +++ b/Sources/Typesense/Models/ApiKeysResponse.swift @@ -1,13 +1,14 @@ // // ApiKeysResponse.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ApiKeysResponse: Codable { @@ -17,5 +18,15 @@ public struct ApiKeysResponse: Codable { self.keys = keys } + public enum CodingKeys: String, CodingKey, CaseIterable { + case keys + } + + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(keys, forKey: .keys) + } } + diff --git a/Sources/Typesense/Models/ApiResponse.swift b/Sources/Typesense/Models/ApiResponse.swift index 3e2c4c2..96caa34 100644 --- a/Sources/Typesense/Models/ApiResponse.swift +++ b/Sources/Typesense/Models/ApiResponse.swift @@ -1,13 +1,14 @@ // // ApiResponse.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ApiResponse: Codable { @@ -17,5 +18,15 @@ public struct ApiResponse: Codable { self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { + case message + } + + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(message, forKey: .message) + } } + diff --git a/Sources/Typesense/Models/CollectionAlias.swift b/Sources/Typesense/Models/CollectionAlias.swift index ddaa55a..08f9bbe 100644 --- a/Sources/Typesense/Models/CollectionAlias.swift +++ b/Sources/Typesense/Models/CollectionAlias.swift @@ -1,13 +1,14 @@ // // CollectionAlias.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct CollectionAlias: Codable { @@ -21,9 +22,17 @@ public struct CollectionAlias: Codable { self.collectionName = collectionName } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case name case collectionName = "collection_name" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(collectionName, forKey: .collectionName) + } } + diff --git a/Sources/Typesense/Models/CollectionAliasSchema.swift b/Sources/Typesense/Models/CollectionAliasSchema.swift index 0e6626e..e51ece9 100644 --- a/Sources/Typesense/Models/CollectionAliasSchema.swift +++ b/Sources/Typesense/Models/CollectionAliasSchema.swift @@ -1,13 +1,14 @@ // // CollectionAliasSchema.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct CollectionAliasSchema: Codable { @@ -18,8 +19,15 @@ public struct CollectionAliasSchema: Codable { self.collectionName = collectionName } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case collectionName = "collection_name" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(collectionName, forKey: .collectionName) + } } + diff --git a/Sources/Typesense/Models/CollectionAliasesResponse.swift b/Sources/Typesense/Models/CollectionAliasesResponse.swift index 0c5caf7..d96b299 100644 --- a/Sources/Typesense/Models/CollectionAliasesResponse.swift +++ b/Sources/Typesense/Models/CollectionAliasesResponse.swift @@ -1,13 +1,14 @@ // // CollectionAliasesResponse.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct CollectionAliasesResponse: Codable { @@ -17,5 +18,15 @@ public struct CollectionAliasesResponse: Codable { self.aliases = aliases } + public enum CodingKeys: String, CodingKey, CaseIterable { + case aliases + } + + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(aliases, forKey: .aliases) + } } + diff --git a/Sources/Typesense/Models/CollectionResponse.swift b/Sources/Typesense/Models/CollectionResponse.swift index b11c22d..f1ec6ab 100644 --- a/Sources/Typesense/Models/CollectionResponse.swift +++ b/Sources/Typesense/Models/CollectionResponse.swift @@ -1,13 +1,14 @@ // // CollectionResponse.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct CollectionResponse: Codable { @@ -16,42 +17,66 @@ public struct CollectionResponse: Codable { /** A list of fields for querying, filtering and faceting */ public var fields: [Field] /** 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. */ - public var defaultSortingField: String? - /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ + public var defaultSortingField: String? = "" + /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ public var tokenSeparators: [String]? - /** 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. */ - public var enableNestedFields: Bool? + /** List of synonym set names to associate with this collection */ + public var synonymSets: [String]? + /** 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. */ + public var enableNestedFields: Bool? = false /** List of symbols or special characters to be indexed. */ public var symbolsToIndex: [String]? + public var voiceQueryModel: VoiceQueryModelCollectionConfig? + /** Optional details about the collection, e.g., when it was created, who created it etc. */ + public var metadata: AnyCodable? /** Number of documents in the collection */ public var numDocuments: Int64 /** Timestamp of when the collection was created (Unix epoch in seconds) */ public var createdAt: Int64 - public var voiceQueryModel: VoiceQueryModelCollectionConfig? - - public init(name: String, fields: [Field], defaultSortingField: String? = nil, tokenSeparators: [String]? = nil, enableNestedFields: Bool? = nil, symbolsToIndex: [String]? = nil, numDocuments: Int64, createdAt: Int64, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil) { + public init(name: String, fields: [Field], defaultSortingField: String? = "", tokenSeparators: [String]? = nil, synonymSets: [String]? = nil, enableNestedFields: Bool? = false, symbolsToIndex: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil, metadata: AnyCodable? = nil, numDocuments: Int64, createdAt: Int64) { self.name = name self.fields = fields self.defaultSortingField = defaultSortingField self.tokenSeparators = tokenSeparators + self.synonymSets = synonymSets self.enableNestedFields = enableNestedFields self.symbolsToIndex = symbolsToIndex + self.voiceQueryModel = voiceQueryModel + self.metadata = metadata self.numDocuments = numDocuments self.createdAt = createdAt - self.voiceQueryModel = voiceQueryModel } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case name case fields case defaultSortingField = "default_sorting_field" case tokenSeparators = "token_separators" + case synonymSets = "synonym_sets" case enableNestedFields = "enable_nested_fields" case symbolsToIndex = "symbols_to_index" + case voiceQueryModel = "voice_query_model" + case metadata case numDocuments = "num_documents" case createdAt = "created_at" - case voiceQueryModel = "voice_query_model" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(fields, forKey: .fields) + try container.encodeIfPresent(defaultSortingField, forKey: .defaultSortingField) + try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) + try container.encodeIfPresent(synonymSets, forKey: .synonymSets) + try container.encodeIfPresent(enableNestedFields, forKey: .enableNestedFields) + try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) + try container.encodeIfPresent(voiceQueryModel, forKey: .voiceQueryModel) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encode(numDocuments, forKey: .numDocuments) + try container.encode(createdAt, forKey: .createdAt) + } } + diff --git a/Sources/Typesense/Models/CollectionSchema.swift b/Sources/Typesense/Models/CollectionSchema.swift index 0366a24..a436050 100644 --- a/Sources/Typesense/Models/CollectionSchema.swift +++ b/Sources/Typesense/Models/CollectionSchema.swift @@ -1,13 +1,14 @@ // // CollectionSchema.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct CollectionSchema: Codable { @@ -16,33 +17,56 @@ public struct CollectionSchema: Codable { /** A list of fields for querying, filtering and faceting */ public var fields: [Field] /** 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. */ - public var defaultSortingField: String? + public var defaultSortingField: String? = "" /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ public var tokenSeparators: [String]? - /** 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. */ - public var enableNestedFields: Bool? + /** List of synonym set names to associate with this collection */ + public var synonymSets: [String]? + /** 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. */ + public var enableNestedFields: Bool? = false /** List of symbols or special characters to be indexed. */ public var symbolsToIndex: [String]? public var voiceQueryModel: VoiceQueryModelCollectionConfig? + /** Optional details about the collection, e.g., when it was created, who created it etc. */ + public var metadata: AnyCodable? - public init(name: String, fields: [Field], defaultSortingField: String? = nil, tokenSeparators: [String]? = nil, enableNestedFields: Bool? = nil, symbolsToIndex: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil) { + public init(name: String, fields: [Field], defaultSortingField: String? = "", tokenSeparators: [String]? = nil, synonymSets: [String]? = nil, enableNestedFields: Bool? = false, symbolsToIndex: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil, metadata: AnyCodable? = nil) { self.name = name self.fields = fields self.defaultSortingField = defaultSortingField self.tokenSeparators = tokenSeparators + self.synonymSets = synonymSets self.enableNestedFields = enableNestedFields self.symbolsToIndex = symbolsToIndex self.voiceQueryModel = voiceQueryModel + self.metadata = metadata } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case name case fields case defaultSortingField = "default_sorting_field" case tokenSeparators = "token_separators" + case synonymSets = "synonym_sets" case enableNestedFields = "enable_nested_fields" case symbolsToIndex = "symbols_to_index" case voiceQueryModel = "voice_query_model" + case metadata } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(fields, forKey: .fields) + try container.encodeIfPresent(defaultSortingField, forKey: .defaultSortingField) + try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) + try container.encodeIfPresent(synonymSets, forKey: .synonymSets) + try container.encodeIfPresent(enableNestedFields, forKey: .enableNestedFields) + try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) + try container.encodeIfPresent(voiceQueryModel, forKey: .voiceQueryModel) + try container.encodeIfPresent(metadata, forKey: .metadata) + } } + diff --git a/Sources/Typesense/Models/CollectionUpdateSchema.swift b/Sources/Typesense/Models/CollectionUpdateSchema.swift index c230434..66dcbcd 100644 --- a/Sources/Typesense/Models/CollectionUpdateSchema.swift +++ b/Sources/Typesense/Models/CollectionUpdateSchema.swift @@ -1,22 +1,43 @@ // // CollectionUpdateSchema.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct CollectionUpdateSchema: Codable { /** A list of fields for querying, filtering and faceting */ public var fields: [Field] + /** List of synonym set names to associate with this collection */ + public var synonymSets: [String]? + /** Optional details about the collection, e.g., when it was created, who created it etc. */ + public var metadata: AnyCodable? - public init(fields: [Field]) { + public init(fields: [Field], synonymSets: [String]? = nil, metadata: AnyCodable? = nil) { self.fields = fields + self.synonymSets = synonymSets + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case fields + case synonymSets = "synonym_sets" + case metadata } + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(fields, forKey: .fields) + try container.encodeIfPresent(synonymSets, forKey: .synonymSets) + try container.encodeIfPresent(metadata, forKey: .metadata) + } } + diff --git a/Sources/Typesense/Models/ConversationModelCreateSchema.swift b/Sources/Typesense/Models/ConversationModelCreateSchema.swift index b9f98d2..e4b8030 100644 --- a/Sources/Typesense/Models/ConversationModelCreateSchema.swift +++ b/Sources/Typesense/Models/ConversationModelCreateSchema.swift @@ -1,37 +1,38 @@ // // ConversationModelCreateSchema.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ConversationModelCreateSchema: Codable { /** An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. */ - public var _id: String? + public var id: String? /** Name of the LLM model offered by OpenAI, Cloudflare or vLLM */ public var modelName: String - /** The LLM service's API Key */ + /** The LLM service's API Key */ public var apiKey: String? /** Typesense collection that stores the historical conversations */ - public var historyCollection: String? - /** LLM service's account ID (only applicable for Cloudflare) */ + public var historyCollection: String + /** LLM service's account ID (only applicable for Cloudflare) */ public var accountId: String? /** The system prompt that contains special instructions to the LLM */ public var systemPrompt: String? /** Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) */ public var ttl: Int? - /** 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. */ + /** 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. */ public var maxBytes: Int /** URL of vLLM service */ public var vllmUrl: String? - public init(_id: String? = nil, modelName: String, apiKey: String? = nil, historyCollection: String? = nil, accountId: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, maxBytes: Int, vllmUrl: String? = nil) { - self._id = _id + public init(id: String? = nil, modelName: String, apiKey: String? = nil, historyCollection: String, accountId: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, maxBytes: Int, vllmUrl: String? = nil) { + self.id = id self.modelName = modelName self.apiKey = apiKey self.historyCollection = historyCollection @@ -42,8 +43,8 @@ public struct ConversationModelCreateSchema: Codable { self.vllmUrl = vllmUrl } - public enum CodingKeys: String, CodingKey { - case _id = "id" + public enum CodingKeys: String, CodingKey, CaseIterable { + case id case modelName = "model_name" case apiKey = "api_key" case historyCollection = "history_collection" @@ -54,4 +55,19 @@ public struct ConversationModelCreateSchema: Codable { case vllmUrl = "vllm_url" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(modelName, forKey: .modelName) + try container.encodeIfPresent(apiKey, forKey: .apiKey) + try container.encode(historyCollection, forKey: .historyCollection) + try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) + try container.encodeIfPresent(ttl, forKey: .ttl) + try container.encode(maxBytes, forKey: .maxBytes) + try container.encodeIfPresent(vllmUrl, forKey: .vllmUrl) + } } + diff --git a/Sources/Typesense/Models/ConversationModelSchema.swift b/Sources/Typesense/Models/ConversationModelSchema.swift index 6a129af..c4389c9 100644 --- a/Sources/Typesense/Models/ConversationModelSchema.swift +++ b/Sources/Typesense/Models/ConversationModelSchema.swift @@ -1,37 +1,38 @@ // // ConversationModelSchema.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ConversationModelSchema: Codable { /** An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. */ - public var _id: String + public var id: String /** Name of the LLM model offered by OpenAI, Cloudflare or vLLM */ - public var modelName: String? - /** The LLM service's API Key */ + public var modelName: String + /** The LLM service's API Key */ public var apiKey: String? /** Typesense collection that stores the historical conversations */ - public var historyCollection: String? - /** LLM service's account ID (only applicable for Cloudflare) */ + public var historyCollection: String + /** LLM service's account ID (only applicable for Cloudflare) */ public var accountId: String? /** The system prompt that contains special instructions to the LLM */ public var systemPrompt: String? /** Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) */ public var ttl: Int? - /** 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. */ - public var maxBytes: Int? + /** 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. */ + public var maxBytes: Int /** URL of vLLM service */ public var vllmUrl: String? - public init(_id: String, modelName: String? = nil, apiKey: String? = nil, historyCollection: String? = nil, accountId: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, maxBytes: Int? = nil, vllmUrl: String? = nil) { - self._id = _id + public init(id: String, modelName: String, apiKey: String? = nil, historyCollection: String, accountId: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, maxBytes: Int, vllmUrl: String? = nil) { + self.id = id self.modelName = modelName self.apiKey = apiKey self.historyCollection = historyCollection @@ -42,8 +43,8 @@ public struct ConversationModelSchema: Codable { self.vllmUrl = vllmUrl } - public enum CodingKeys: String, CodingKey { - case _id = "id" + public enum CodingKeys: String, CodingKey, CaseIterable { + case id case modelName = "model_name" case apiKey = "api_key" case historyCollection = "history_collection" @@ -54,4 +55,19 @@ public struct ConversationModelSchema: Codable { case vllmUrl = "vllm_url" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(modelName, forKey: .modelName) + try container.encodeIfPresent(apiKey, forKey: .apiKey) + try container.encode(historyCollection, forKey: .historyCollection) + try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) + try container.encodeIfPresent(ttl, forKey: .ttl) + try container.encode(maxBytes, forKey: .maxBytes) + try container.encodeIfPresent(vllmUrl, forKey: .vllmUrl) + } } + diff --git a/Sources/Typesense/Models/ConversationModelUpdateSchema.swift b/Sources/Typesense/Models/ConversationModelUpdateSchema.swift index 214dcb3..05a764c 100644 --- a/Sources/Typesense/Models/ConversationModelUpdateSchema.swift +++ b/Sources/Typesense/Models/ConversationModelUpdateSchema.swift @@ -1,37 +1,38 @@ // // ConversationModelUpdateSchema.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct ConversationModelUpdateSchema: Codable { /** An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. */ - public var _id: String? + public var id: String? /** Name of the LLM model offered by OpenAI, Cloudflare or vLLM */ public var modelName: String? - /** The LLM service's API Key */ + /** The LLM service's API Key */ public var apiKey: String? /** Typesense collection that stores the historical conversations */ public var historyCollection: String? - /** LLM service's account ID (only applicable for Cloudflare) */ + /** LLM service's account ID (only applicable for Cloudflare) */ public var accountId: String? /** The system prompt that contains special instructions to the LLM */ public var systemPrompt: String? /** Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) */ public var ttl: Int? - /** 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. */ + /** 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. */ public var maxBytes: Int? /** URL of vLLM service */ public var vllmUrl: String? - public init(_id: String? = nil, modelName: String? = nil, apiKey: String? = nil, historyCollection: String? = nil, accountId: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, maxBytes: Int? = nil, vllmUrl: String? = nil) { - self._id = _id + public init(id: String? = nil, modelName: String? = nil, apiKey: String? = nil, historyCollection: String? = nil, accountId: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, maxBytes: Int? = nil, vllmUrl: String? = nil) { + self.id = id self.modelName = modelName self.apiKey = apiKey self.historyCollection = historyCollection @@ -42,8 +43,8 @@ public struct ConversationModelUpdateSchema: Codable { self.vllmUrl = vllmUrl } - public enum CodingKeys: String, CodingKey { - case _id = "id" + public enum CodingKeys: String, CodingKey, CaseIterable { + case id case modelName = "model_name" case apiKey = "api_key" case historyCollection = "history_collection" @@ -54,4 +55,19 @@ public struct ConversationModelUpdateSchema: Codable { case vllmUrl = "vllm_url" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(apiKey, forKey: .apiKey) + try container.encodeIfPresent(historyCollection, forKey: .historyCollection) + try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) + try container.encodeIfPresent(ttl, forKey: .ttl) + try container.encodeIfPresent(maxBytes, forKey: .maxBytes) + try container.encodeIfPresent(vllmUrl, forKey: .vllmUrl) + } } + diff --git a/Sources/Typesense/Models/CreateAnalyticsRule200Response.swift b/Sources/Typesense/Models/CreateAnalyticsRule200Response.swift new file mode 100644 index 0000000..57120e6 --- /dev/null +++ b/Sources/Typesense/Models/CreateAnalyticsRule200Response.swift @@ -0,0 +1,38 @@ +// +// CreateAnalyticsRule200Response.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum CreateAnalyticsRule200Response: Codable, JSONEncodable { + case typeAnalyticsRule(AnalyticsRule) + case type[CreateAnalyticsRule200ResponseOneOfInner]([CreateAnalyticsRule200ResponseOneOfInner]) + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .typeAnalyticsRule(let value): + try container.encode(value) + case .type[CreateAnalyticsRule200ResponseOneOfInner](let value): + try container.encode(value) + } + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if let value = try? container.decode(AnalyticsRule.self) { + self = .typeAnalyticsRule(value) + } else if let value = try? container.decode([CreateAnalyticsRule200ResponseOneOfInner].self) { + self = .type[CreateAnalyticsRule200ResponseOneOfInner](value) + } else { + throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of CreateAnalyticsRule200Response")) + } + } +} + diff --git a/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInner.swift b/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInner.swift new file mode 100644 index 0000000..c631685 --- /dev/null +++ b/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInner.swift @@ -0,0 +1,62 @@ +// +// CreateAnalyticsRule200ResponseOneOfInner.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CreateAnalyticsRule200ResponseOneOfInner: Codable { + + public enum ModelType: String, Codable, CaseIterable { + case popularQueries = "popular_queries" + case nohitsQueries = "nohits_queries" + case counter = "counter" + case log = "log" + } + public var name: String + public var type: ModelType + public var collection: String + public var eventType: String + public var ruleTag: String? + public var params: AnalyticsRuleCreateParams? + public var error: String? + + public init(name: String, type: ModelType, collection: String, eventType: String, ruleTag: String? = nil, params: AnalyticsRuleCreateParams? = nil, error: String? = nil) { + self.name = name + self.type = type + self.collection = collection + self.eventType = eventType + self.ruleTag = ruleTag + self.params = params + self.error = error + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case type + case collection + case eventType = "event_type" + case ruleTag = "rule_tag" + case params + case error + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(type, forKey: .type) + try container.encode(collection, forKey: .collection) + try container.encode(eventType, forKey: .eventType) + try container.encodeIfPresent(ruleTag, forKey: .ruleTag) + try container.encodeIfPresent(params, forKey: .params) + try container.encodeIfPresent(error, forKey: .error) + } +} + diff --git a/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift b/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift new file mode 100644 index 0000000..1f63acb --- /dev/null +++ b/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift @@ -0,0 +1,32 @@ +// +// CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CreateAnalyticsRule200ResponseOneOfInnerAnyOf: Codable { + + public var error: String? + + public init(error: String? = nil) { + self.error = error + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case error + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(error, forKey: .error) + } +} + diff --git a/Sources/Typesense/Models/CreateAnalyticsRuleRequest.swift b/Sources/Typesense/Models/CreateAnalyticsRuleRequest.swift new file mode 100644 index 0000000..025873c --- /dev/null +++ b/Sources/Typesense/Models/CreateAnalyticsRuleRequest.swift @@ -0,0 +1,38 @@ +// +// CreateAnalyticsRuleRequest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum CreateAnalyticsRuleRequest: Codable, JSONEncodable { + case typeAnalyticsRuleCreate(AnalyticsRuleCreate) + case type[AnalyticsRuleCreate]([AnalyticsRuleCreate]) + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .typeAnalyticsRuleCreate(let value): + try container.encode(value) + case .type[AnalyticsRuleCreate](let value): + try container.encode(value) + } + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if let value = try? container.decode(AnalyticsRuleCreate.self) { + self = .typeAnalyticsRuleCreate(value) + } else if let value = try? container.decode([AnalyticsRuleCreate].self) { + self = .type[AnalyticsRuleCreate](value) + } else { + throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of CreateAnalyticsRuleRequest")) + } + } +} + diff --git a/Sources/Typesense/Models/CurationExclude.swift b/Sources/Typesense/Models/CurationExclude.swift new file mode 100644 index 0000000..615783e --- /dev/null +++ b/Sources/Typesense/Models/CurationExclude.swift @@ -0,0 +1,33 @@ +// +// CurationExclude.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CurationExclude: Codable { + + /** document id that should be excluded from the search results. */ + public var id: String + + public init(id: String) { + self.id = id + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + } +} + diff --git a/Sources/Typesense/Models/CurationInclude.swift b/Sources/Typesense/Models/CurationInclude.swift new file mode 100644 index 0000000..d9a52d3 --- /dev/null +++ b/Sources/Typesense/Models/CurationInclude.swift @@ -0,0 +1,38 @@ +// +// CurationInclude.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CurationInclude: Codable { + + /** document id that should be included */ + public var id: String + /** position number where document should be included in the search results */ + public var position: Int + + public init(id: String, position: Int) { + self.id = id + self.position = position + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case position + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(position, forKey: .position) + } +} + diff --git a/Sources/Typesense/Models/CurationItemCreateSchema.swift b/Sources/Typesense/Models/CurationItemCreateSchema.swift new file mode 100644 index 0000000..59f666f --- /dev/null +++ b/Sources/Typesense/Models/CurationItemCreateSchema.swift @@ -0,0 +1,92 @@ +// +// CurationItemCreateSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CurationItemCreateSchema: Codable { + + public var rule: CurationRule + /** List of document `id`s that should be included in the search results with their corresponding `position`s. */ + public var includes: [CurationInclude]? + /** List of document `id`s that should be excluded from the search results. */ + public var excludes: [CurationExclude]? + /** A filter by clause that is applied to any search query that matches the curation rule. */ + public var filterBy: String? + /** Indicates whether search query tokens that exist in the curation's rule should be removed from the search query. */ + public var removeMatchedTokens: Bool? + /** 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. */ + public var metadata: AnyCodable? + /** A sort by clause that is applied to any search query that matches the curation rule. */ + public var sortBy: String? + /** Replaces the current search query with this value, when the search query matches the curation rule. */ + public var replaceQuery: String? + /** When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. */ + public var filterCuratedHits: Bool? + /** A Unix timestamp that indicates the date/time from which the curation will be active. You can use this to create rules that start applying from a future point in time. */ + public var effectiveFromTs: Int? + /** A Unix timestamp that indicates the date/time until which the curation will be active. You can use this to create rules that stop applying after a period of time. */ + public var effectiveToTs: Int? + /** When set to true, curation processing will stop at the first matching rule. When set to false curation processing will continue and multiple curation actions will be triggered in sequence. Curations are processed in the lexical sort order of their id field. */ + public var stopProcessing: Bool? + /** ID of the curation item */ + public var id: String? + + public init(rule: CurationRule, includes: [CurationInclude]? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, removeMatchedTokens: Bool? = nil, metadata: AnyCodable? = nil, sortBy: String? = nil, replaceQuery: String? = nil, filterCuratedHits: Bool? = nil, effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, stopProcessing: Bool? = nil, id: String? = nil) { + self.rule = rule + self.includes = includes + self.excludes = excludes + self.filterBy = filterBy + self.removeMatchedTokens = removeMatchedTokens + self.metadata = metadata + self.sortBy = sortBy + self.replaceQuery = replaceQuery + self.filterCuratedHits = filterCuratedHits + self.effectiveFromTs = effectiveFromTs + self.effectiveToTs = effectiveToTs + self.stopProcessing = stopProcessing + self.id = id + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case rule + case includes + case excludes + case filterBy = "filter_by" + case removeMatchedTokens = "remove_matched_tokens" + case metadata + case sortBy = "sort_by" + case replaceQuery = "replace_query" + case filterCuratedHits = "filter_curated_hits" + case effectiveFromTs = "effective_from_ts" + case effectiveToTs = "effective_to_ts" + case stopProcessing = "stop_processing" + case id + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(rule, forKey: .rule) + try container.encodeIfPresent(includes, forKey: .includes) + try container.encodeIfPresent(excludes, forKey: .excludes) + try container.encodeIfPresent(filterBy, forKey: .filterBy) + try container.encodeIfPresent(removeMatchedTokens, forKey: .removeMatchedTokens) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(replaceQuery, forKey: .replaceQuery) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) + try container.encodeIfPresent(effectiveFromTs, forKey: .effectiveFromTs) + try container.encodeIfPresent(effectiveToTs, forKey: .effectiveToTs) + try container.encodeIfPresent(stopProcessing, forKey: .stopProcessing) + try container.encodeIfPresent(id, forKey: .id) + } +} + diff --git a/Sources/Typesense/Models/CurationItemDeleteSchema.swift b/Sources/Typesense/Models/CurationItemDeleteSchema.swift new file mode 100644 index 0000000..3df278b --- /dev/null +++ b/Sources/Typesense/Models/CurationItemDeleteSchema.swift @@ -0,0 +1,33 @@ +// +// CurationItemDeleteSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CurationItemDeleteSchema: Codable { + + /** ID of the deleted curation item */ + public var id: String + + public init(id: String) { + self.id = id + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + } +} + diff --git a/Sources/Typesense/Models/CurationItemSchema.swift b/Sources/Typesense/Models/CurationItemSchema.swift new file mode 100644 index 0000000..63a5cfc --- /dev/null +++ b/Sources/Typesense/Models/CurationItemSchema.swift @@ -0,0 +1,91 @@ +// +// CurationItemSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CurationItemSchema: Codable { + + public var rule: CurationRule + /** List of document `id`s that should be included in the search results with their corresponding `position`s. */ + public var includes: [CurationInclude]? + /** List of document `id`s that should be excluded from the search results. */ + public var excludes: [CurationExclude]? + /** A filter by clause that is applied to any search query that matches the curation rule. */ + public var filterBy: String? + /** Indicates whether search query tokens that exist in the curation's rule should be removed from the search query. */ + public var removeMatchedTokens: Bool? + /** 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. */ + public var metadata: AnyCodable? + /** A sort by clause that is applied to any search query that matches the curation rule. */ + public var sortBy: String? + /** Replaces the current search query with this value, when the search query matches the curation rule. */ + public var replaceQuery: String? + /** When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. */ + public var filterCuratedHits: Bool? + /** A Unix timestamp that indicates the date/time from which the curation will be active. You can use this to create rules that start applying from a future point in time. */ + public var effectiveFromTs: Int? + /** A Unix timestamp that indicates the date/time until which the curation will be active. You can use this to create rules that stop applying after a period of time. */ + public var effectiveToTs: Int? + /** When set to true, curation processing will stop at the first matching rule. When set to false curation processing will continue and multiple curation actions will be triggered in sequence. Curations are processed in the lexical sort order of their id field. */ + public var stopProcessing: Bool? + public var id: String + + public init(rule: CurationRule, includes: [CurationInclude]? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, removeMatchedTokens: Bool? = nil, metadata: AnyCodable? = nil, sortBy: String? = nil, replaceQuery: String? = nil, filterCuratedHits: Bool? = nil, effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, stopProcessing: Bool? = nil, id: String) { + self.rule = rule + self.includes = includes + self.excludes = excludes + self.filterBy = filterBy + self.removeMatchedTokens = removeMatchedTokens + self.metadata = metadata + self.sortBy = sortBy + self.replaceQuery = replaceQuery + self.filterCuratedHits = filterCuratedHits + self.effectiveFromTs = effectiveFromTs + self.effectiveToTs = effectiveToTs + self.stopProcessing = stopProcessing + self.id = id + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case rule + case includes + case excludes + case filterBy = "filter_by" + case removeMatchedTokens = "remove_matched_tokens" + case metadata + case sortBy = "sort_by" + case replaceQuery = "replace_query" + case filterCuratedHits = "filter_curated_hits" + case effectiveFromTs = "effective_from_ts" + case effectiveToTs = "effective_to_ts" + case stopProcessing = "stop_processing" + case id + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(rule, forKey: .rule) + try container.encodeIfPresent(includes, forKey: .includes) + try container.encodeIfPresent(excludes, forKey: .excludes) + try container.encodeIfPresent(filterBy, forKey: .filterBy) + try container.encodeIfPresent(removeMatchedTokens, forKey: .removeMatchedTokens) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(replaceQuery, forKey: .replaceQuery) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) + try container.encodeIfPresent(effectiveFromTs, forKey: .effectiveFromTs) + try container.encodeIfPresent(effectiveToTs, forKey: .effectiveToTs) + try container.encodeIfPresent(stopProcessing, forKey: .stopProcessing) + try container.encode(id, forKey: .id) + } +} + diff --git a/Sources/Typesense/Models/CurationRule.swift b/Sources/Typesense/Models/CurationRule.swift new file mode 100644 index 0000000..64245d7 --- /dev/null +++ b/Sources/Typesense/Models/CurationRule.swift @@ -0,0 +1,52 @@ +// +// CurationRule.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CurationRule: Codable { + + public enum Match: String, Codable, CaseIterable { + case exact = "exact" + case contains = "contains" + } + /** List of tag values to associate with this curation rule. */ + public var tags: [String]? + /** Indicates what search queries should be curated */ + public var 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. */ + public var match: Match? + /** Indicates that the curation should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). */ + public var filterBy: String? + + public init(tags: [String]? = nil, query: String? = nil, match: Match? = nil, filterBy: String? = nil) { + self.tags = tags + self.query = query + self.match = match + self.filterBy = filterBy + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case tags + case query + case match + case filterBy = "filter_by" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(query, forKey: .query) + try container.encodeIfPresent(match, forKey: .match) + try container.encodeIfPresent(filterBy, forKey: .filterBy) + } +} + diff --git a/Sources/Typesense/Models/CurationSetCreateSchema.swift b/Sources/Typesense/Models/CurationSetCreateSchema.swift new file mode 100644 index 0000000..2663c86 --- /dev/null +++ b/Sources/Typesense/Models/CurationSetCreateSchema.swift @@ -0,0 +1,38 @@ +// +// CurationSetCreateSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CurationSetCreateSchema: Codable { + + /** Array of curation items */ + public var items: [CurationItemCreateSchema] + /** Optional description for the curation set */ + public var description: String? + + public init(items: [CurationItemCreateSchema], description: String? = nil) { + self.items = items + self.description = description + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case items + case description + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(items, forKey: .items) + try container.encodeIfPresent(description, forKey: .description) + } +} + diff --git a/Sources/Typesense/Models/CurationSetDeleteSchema.swift b/Sources/Typesense/Models/CurationSetDeleteSchema.swift new file mode 100644 index 0000000..df7a073 --- /dev/null +++ b/Sources/Typesense/Models/CurationSetDeleteSchema.swift @@ -0,0 +1,33 @@ +// +// CurationSetDeleteSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CurationSetDeleteSchema: Codable { + + /** Name of the deleted curation set */ + public var name: String + + public init(name: String) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + } +} + diff --git a/Sources/Typesense/Models/CurationSetSchema.swift b/Sources/Typesense/Models/CurationSetSchema.swift new file mode 100644 index 0000000..b1edd35 --- /dev/null +++ b/Sources/Typesense/Models/CurationSetSchema.swift @@ -0,0 +1,42 @@ +// +// CurationSetSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CurationSetSchema: Codable { + + /** Array of curation items */ + public var items: [CurationItemCreateSchema] + /** Optional description for the curation set */ + public var description: String? + public var name: String + + public init(items: [CurationItemCreateSchema], description: String? = nil, name: String) { + self.items = items + self.description = description + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case items + case description + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(items, forKey: .items) + try container.encodeIfPresent(description, forKey: .description) + try container.encode(name, forKey: .name) + } +} + diff --git a/Sources/Typesense/Models/Debug200Response.swift b/Sources/Typesense/Models/Debug200Response.swift new file mode 100644 index 0000000..8b825fd --- /dev/null +++ b/Sources/Typesense/Models/Debug200Response.swift @@ -0,0 +1,32 @@ +// +// Debug200Response.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Debug200Response: Codable { + + public var version: String? + + public init(version: String? = nil) { + self.version = version + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case version + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(version, forKey: .version) + } +} + diff --git a/Sources/Typesense/Models/DebugRetrieveSchema.swift b/Sources/Typesense/Models/DebugRetrieveSchema.swift deleted file mode 100644 index 6c25698..0000000 --- a/Sources/Typesense/Models/DebugRetrieveSchema.swift +++ /dev/null @@ -1,16 +0,0 @@ -import Foundation - - - -public struct DebugRetrieveSchema: Codable { - - public var state: Int - public var version: String - - public init(state: Int, version: String) { - self.state = state - self.version = version - } - - -} diff --git a/Sources/Typesense/Models/DeleteDocuments200Response.swift b/Sources/Typesense/Models/DeleteDocuments200Response.swift new file mode 100644 index 0000000..c992b56 --- /dev/null +++ b/Sources/Typesense/Models/DeleteDocuments200Response.swift @@ -0,0 +1,32 @@ +// +// DeleteDocuments200Response.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DeleteDocuments200Response: Codable { + + public var numDeleted: Int + + public init(numDeleted: Int) { + self.numDeleted = numDeleted + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case numDeleted = "num_deleted" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(numDeleted, forKey: .numDeleted) + } +} + diff --git a/Sources/Typesense/Models/DeleteDocumentsDeleteDocumentsParametersParameter.swift b/Sources/Typesense/Models/DeleteDocumentsDeleteDocumentsParametersParameter.swift new file mode 100644 index 0000000..509463a --- /dev/null +++ b/Sources/Typesense/Models/DeleteDocumentsDeleteDocumentsParametersParameter.swift @@ -0,0 +1,46 @@ +// +// DeleteDocumentsDeleteDocumentsParametersParameter.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DeleteDocumentsDeleteDocumentsParametersParameter: Codable { + + public var filterBy: 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. */ + public var batchSize: Int? + public var ignoreNotFound: Bool? + /** When true, removes all documents from the collection while preserving the collection and its schema. */ + public var truncate: Bool? + + public init(filterBy: String, batchSize: Int? = nil, ignoreNotFound: Bool? = nil, truncate: Bool? = nil) { + self.filterBy = filterBy + self.batchSize = batchSize + self.ignoreNotFound = ignoreNotFound + self.truncate = truncate + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case filterBy = "filter_by" + case batchSize = "batch_size" + case ignoreNotFound = "ignore_not_found" + case truncate + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(filterBy, forKey: .filterBy) + try container.encodeIfPresent(batchSize, forKey: .batchSize) + try container.encodeIfPresent(ignoreNotFound, forKey: .ignoreNotFound) + try container.encodeIfPresent(truncate, forKey: .truncate) + } +} + diff --git a/Sources/Typesense/Models/DeleteDocumentsParameters.swift b/Sources/Typesense/Models/DeleteDocumentsParameters.swift deleted file mode 100644 index ed22c2a..0000000 --- a/Sources/Typesense/Models/DeleteDocumentsParameters.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// DeleteDocumentsParameters.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct DeleteDocumentsParameters: Codable { - - public var filterBy: 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. */ - public var batchSize: Int? - public var ignoreNotFound: Bool? - - public init(filterBy: String, batchSize: Int? = nil, ignoreNotFound: Bool? = nil) { - self.filterBy = filterBy - self.batchSize = batchSize - self.ignoreNotFound = ignoreNotFound - } - - public enum CodingKeys: String, CodingKey { - case filterBy = "filter_by" - case batchSize = "batch_size" - case ignoreNotFound = "ignore_not_found" - } - -} diff --git a/Sources/Typesense/Models/DeleteDocumentsResponse.swift b/Sources/Typesense/Models/DeleteDocumentsResponse.swift deleted file mode 100644 index 4c0ef26..0000000 --- a/Sources/Typesense/Models/DeleteDocumentsResponse.swift +++ /dev/null @@ -1,17 +0,0 @@ -import Foundation - - - -public struct DeleteDocumentsResponse: Codable { - - public var numDeleted: Int - - public init(numDeleted: Int) { - self.numDeleted = numDeleted - } - - public enum CodingKeys: String, CodingKey { - case numDeleted = "num_deleted" - } - -} diff --git a/Sources/Typesense/Models/DeleteStopwordsSet200Response.swift b/Sources/Typesense/Models/DeleteStopwordsSet200Response.swift new file mode 100644 index 0000000..4a2a3a5 --- /dev/null +++ b/Sources/Typesense/Models/DeleteStopwordsSet200Response.swift @@ -0,0 +1,32 @@ +// +// DeleteStopwordsSet200Response.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DeleteStopwordsSet200Response: Codable { + + public var id: String + + public init(id: String) { + self.id = id + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + } +} + diff --git a/Sources/Typesense/Models/DirtyValues.swift b/Sources/Typesense/Models/DirtyValues.swift new file mode 100644 index 0000000..9d9fa27 --- /dev/null +++ b/Sources/Typesense/Models/DirtyValues.swift @@ -0,0 +1,18 @@ +// +// DirtyValues.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum DirtyValues: String, Codable, CaseIterable { + case coerceOrReject = "coerce_or_reject" + case coerceOrDrop = "coerce_or_drop" + case drop = "drop" + case reject = "reject" +} diff --git a/Sources/Typesense/Models/DocumentIndexParameters.swift b/Sources/Typesense/Models/DocumentIndexParameters.swift deleted file mode 100644 index 49bda1b..0000000 --- a/Sources/Typesense/Models/DocumentIndexParameters.swift +++ /dev/null @@ -1,17 +0,0 @@ -import Foundation - - - -public struct DocumentIndexParameters: Codable { - - public var dirtyValues: DirtyValues? - - public init(dirtyValues: DirtyValues? = nil) { - self.dirtyValues = dirtyValues - } - - public enum CodingKeys: String, CodingKey { - case dirtyValues = "dirty_values" - } - -} diff --git a/Sources/Typesense/Models/DropTokensMode.swift b/Sources/Typesense/Models/DropTokensMode.swift new file mode 100644 index 0000000..57fe537 --- /dev/null +++ b/Sources/Typesense/Models/DropTokensMode.swift @@ -0,0 +1,18 @@ +// +// DropTokensMode.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** 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 up to 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 */ +public enum DropTokensMode: String, Codable, CaseIterable { + case rightToLeft = "right_to_left" + case leftToRight = "left_to_right" + case bothSides3 = "both_sides:3" +} diff --git a/Sources/Typesense/Models/ExportDocumentsExportDocumentsParametersParameter.swift b/Sources/Typesense/Models/ExportDocumentsExportDocumentsParametersParameter.swift new file mode 100644 index 0000000..7977a1b --- /dev/null +++ b/Sources/Typesense/Models/ExportDocumentsExportDocumentsParametersParameter.swift @@ -0,0 +1,43 @@ +// +// ExportDocumentsExportDocumentsParametersParameter.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ExportDocumentsExportDocumentsParametersParameter: Codable { + + /** Filter conditions for refining your search results. Separate multiple conditions with &&. */ + public var filterBy: String? + /** List of fields from the document to include in the search result */ + public var includeFields: String? + /** List of fields from the document to exclude in the search result */ + public var excludeFields: String? + + public init(filterBy: String? = nil, includeFields: String? = nil, excludeFields: String? = nil) { + self.filterBy = filterBy + self.includeFields = includeFields + self.excludeFields = excludeFields + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case filterBy = "filter_by" + case includeFields = "include_fields" + case excludeFields = "exclude_fields" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(filterBy, forKey: .filterBy) + try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(excludeFields, forKey: .excludeFields) + } +} + diff --git a/Sources/Typesense/Models/ExportDocumentsParameters.swift b/Sources/Typesense/Models/ExportDocumentsParameters.swift deleted file mode 100644 index a4d2a27..0000000 --- a/Sources/Typesense/Models/ExportDocumentsParameters.swift +++ /dev/null @@ -1,33 +0,0 @@ -// -// ExportDocumentsParameters.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct ExportDocumentsParameters: Codable { - - /** Filter conditions for refining your search results. Separate multiple conditions with &&. */ - public var filterBy: String? - /** List of fields from the document to include in the search result */ - public var includeFields: String? - /** List of fields from the document to exclude in the search result */ - public var excludeFields: String? - - public init(filterBy: String? = nil, includeFields: String? = nil, excludeFields: String? = nil) { - self.filterBy = filterBy - self.includeFields = includeFields - self.excludeFields = excludeFields - } - - public enum CodingKeys: String, CodingKey { - case filterBy = "filter_by" - case includeFields = "include_fields" - case excludeFields = "exclude_fields" - } - -} diff --git a/Sources/Typesense/Models/FacetCounts.swift b/Sources/Typesense/Models/FacetCounts.swift index 4471f35..b2b8500 100644 --- a/Sources/Typesense/Models/FacetCounts.swift +++ b/Sources/Typesense/Models/FacetCounts.swift @@ -1,30 +1,40 @@ // // FacetCounts.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FacetCounts: Codable { - public var counts: [FacetCountsCounts]? + public var counts: [FacetCountsCountsInner]? public var fieldName: String? public var stats: FacetCountsStats? - public init(counts: [FacetCountsCounts]? = nil, fieldName: String? = nil, stats: FacetCountsStats? = nil) { + public init(counts: [FacetCountsCountsInner]? = nil, fieldName: String? = nil, stats: FacetCountsStats? = nil) { self.counts = counts self.fieldName = fieldName self.stats = stats } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case counts case fieldName = "field_name" case stats } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(counts, forKey: .counts) + try container.encodeIfPresent(fieldName, forKey: .fieldName) + try container.encodeIfPresent(stats, forKey: .stats) + } } + diff --git a/Sources/Typesense/Models/FacetCountsCounts.swift b/Sources/Typesense/Models/FacetCountsCounts.swift deleted file mode 100644 index 4392569..0000000 --- a/Sources/Typesense/Models/FacetCountsCounts.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// FacetCountsCounts.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct FacetCountsCounts: Codable { - - public var count: Int? - public var highlighted: String? - public var value: String? - - public init(count: Int? = nil, highlighted: String? = nil, value: String? = nil) { - self.count = count - self.highlighted = highlighted - self.value = value - } - - -} diff --git a/Sources/Typesense/Models/FacetCountsCountsInner.swift b/Sources/Typesense/Models/FacetCountsCountsInner.swift new file mode 100644 index 0000000..6228cfe --- /dev/null +++ b/Sources/Typesense/Models/FacetCountsCountsInner.swift @@ -0,0 +1,44 @@ +// +// FacetCountsCountsInner.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct FacetCountsCountsInner: Codable { + + public var count: Int? + public var highlighted: String? + public var value: String? + public var parent: AnyCodable? + + public init(count: Int? = nil, highlighted: String? = nil, value: String? = nil, parent: AnyCodable? = nil) { + self.count = count + self.highlighted = highlighted + self.value = value + self.parent = parent + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case count + case highlighted + case value + case parent + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(count, forKey: .count) + try container.encodeIfPresent(highlighted, forKey: .highlighted) + try container.encodeIfPresent(value, forKey: .value) + try container.encodeIfPresent(parent, forKey: .parent) + } +} + diff --git a/Sources/Typesense/Models/FacetCountsStats.swift b/Sources/Typesense/Models/FacetCountsStats.swift index 92a09db..780ba5c 100644 --- a/Sources/Typesense/Models/FacetCountsStats.swift +++ b/Sources/Typesense/Models/FacetCountsStats.swift @@ -1,13 +1,14 @@ // // FacetCountsStats.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FacetCountsStats: Codable { @@ -25,7 +26,7 @@ public struct FacetCountsStats: Codable { self.avg = avg } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case max case min case sum @@ -33,4 +34,15 @@ public struct FacetCountsStats: Codable { case avg } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(max, forKey: .max) + try container.encodeIfPresent(min, forKey: .min) + try container.encodeIfPresent(sum, forKey: .sum) + try container.encodeIfPresent(totalValues, forKey: .totalValues) + try container.encodeIfPresent(avg, forKey: .avg) + } } + diff --git a/Sources/Typesense/Models/Field.swift b/Sources/Typesense/Models/Field.swift index f0d7ac1..6244553 100644 --- a/Sources/Typesense/Models/Field.swift +++ b/Sources/Typesense/Models/Field.swift @@ -1,13 +1,14 @@ // // Field.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct Field: Codable { @@ -15,18 +16,31 @@ public struct Field: Codable { public var type: String public var _optional: Bool? public var facet: Bool? - public var index: Bool? + public var index: Bool? = true public var locale: String? public var sort: Bool? - public var _infix: Bool? + public var _infix: Bool? = false + /** Name of a field in another collection that should be linked to this collection so that it can be joined during query. */ public var reference: String? public var numDim: Int? public var drop: Bool? - /** Whether to store the image on disk. */ + /** When set to false, the field value will not be stored on disk. Default: true. */ public var store: Bool? + /** The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. */ + public var vecDist: String? + /** Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. */ + public var rangeIndex: Bool? + /** Values are stemmed before indexing in-memory. Default: false. */ + public var stem: Bool? + /** Name of the stemming dictionary to use for this field */ + public var stemDictionary: String? + /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ + public var tokenSeparators: [String]? + /** List of symbols or special characters to be indexed. */ + public var symbolsToIndex: [String]? public var embed: FieldEmbed? - public init(name: String, type: String, _optional: Bool? = nil, facet: Bool? = nil, index: Bool? = nil, locale: String? = nil, sort: Bool? = nil, _infix: Bool? = nil, reference: String? = nil, numDim: Int? = nil, drop: Bool? = nil, store: Bool? = nil, embed: FieldEmbed? = nil) { + public init(name: String, type: String, _optional: Bool? = nil, facet: Bool? = nil, index: Bool? = true, locale: String? = nil, sort: Bool? = nil, _infix: Bool? = false, reference: String? = nil, numDim: Int? = nil, drop: Bool? = nil, store: Bool? = nil, vecDist: String? = nil, rangeIndex: Bool? = nil, stem: Bool? = nil, stemDictionary: String? = nil, tokenSeparators: [String]? = nil, symbolsToIndex: [String]? = nil, embed: FieldEmbed? = nil) { self.name = name self.type = type self._optional = _optional @@ -39,10 +53,16 @@ public struct Field: Codable { self.numDim = numDim self.drop = drop self.store = store + self.vecDist = vecDist + self.rangeIndex = rangeIndex + self.stem = stem + self.stemDictionary = stemDictionary + self.tokenSeparators = tokenSeparators + self.symbolsToIndex = symbolsToIndex self.embed = embed } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case name case type case _optional = "optional" @@ -55,7 +75,38 @@ public struct Field: Codable { case numDim = "num_dim" case drop case store + case vecDist = "vec_dist" + case rangeIndex = "range_index" + case stem + case stemDictionary = "stem_dictionary" + case tokenSeparators = "token_separators" + case symbolsToIndex = "symbols_to_index" case embed } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(type, forKey: .type) + try container.encodeIfPresent(_optional, forKey: ._optional) + try container.encodeIfPresent(facet, forKey: .facet) + try container.encodeIfPresent(index, forKey: .index) + try container.encodeIfPresent(locale, forKey: .locale) + try container.encodeIfPresent(sort, forKey: .sort) + try container.encodeIfPresent(_infix, forKey: ._infix) + try container.encodeIfPresent(reference, forKey: .reference) + try container.encodeIfPresent(numDim, forKey: .numDim) + try container.encodeIfPresent(drop, forKey: .drop) + try container.encodeIfPresent(store, forKey: .store) + try container.encodeIfPresent(vecDist, forKey: .vecDist) + try container.encodeIfPresent(rangeIndex, forKey: .rangeIndex) + try container.encodeIfPresent(stem, forKey: .stem) + try container.encodeIfPresent(stemDictionary, forKey: .stemDictionary) + try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) + try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) + try container.encodeIfPresent(embed, forKey: .embed) + } } + diff --git a/Sources/Typesense/Models/FieldEmbed.swift b/Sources/Typesense/Models/FieldEmbed.swift index b15a0aa..bf3d00a 100644 --- a/Sources/Typesense/Models/FieldEmbed.swift +++ b/Sources/Typesense/Models/FieldEmbed.swift @@ -1,13 +1,14 @@ // // FieldEmbed.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FieldEmbed: Codable { @@ -19,9 +20,17 @@ public struct FieldEmbed: Codable { self.modelConfig = modelConfig } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case from case modelConfig = "model_config" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(from, forKey: .from) + try container.encode(modelConfig, forKey: .modelConfig) + } } + diff --git a/Sources/Typesense/Models/FieldEmbedModelConfig.swift b/Sources/Typesense/Models/FieldEmbedModelConfig.swift index 053dad3..d521f47 100644 --- a/Sources/Typesense/Models/FieldEmbedModelConfig.swift +++ b/Sources/Typesense/Models/FieldEmbedModelConfig.swift @@ -1,39 +1,68 @@ // // FieldEmbedModelConfig.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct FieldEmbedModelConfig: Codable { public var modelName: String public var apiKey: String? + public var url: String? public var accessToken: String? + public var refreshToken: String? public var clientId: String? public var clientSecret: String? public var projectId: String? + public var indexingPrefix: String? + public var queryPrefix: String? - public init(modelName: String, apiKey: String? = nil, accessToken: String? = nil, clientId: String? = nil, clientSecret: String? = nil, projectId: String? = nil) { + public init(modelName: String, apiKey: String? = nil, url: String? = nil, accessToken: String? = nil, refreshToken: String? = nil, clientId: String? = nil, clientSecret: String? = nil, projectId: String? = nil, indexingPrefix: String? = nil, queryPrefix: String? = nil) { self.modelName = modelName self.apiKey = apiKey + self.url = url self.accessToken = accessToken + self.refreshToken = refreshToken self.clientId = clientId self.clientSecret = clientSecret self.projectId = projectId + self.indexingPrefix = indexingPrefix + self.queryPrefix = queryPrefix } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case modelName = "model_name" case apiKey = "api_key" + case url case accessToken = "access_token" + case refreshToken = "refresh_token" case clientId = "client_id" case clientSecret = "client_secret" case projectId = "project_id" + case indexingPrefix = "indexing_prefix" + case queryPrefix = "query_prefix" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(modelName, forKey: .modelName) + try container.encodeIfPresent(apiKey, forKey: .apiKey) + try container.encodeIfPresent(url, forKey: .url) + try container.encodeIfPresent(accessToken, forKey: .accessToken) + try container.encodeIfPresent(refreshToken, forKey: .refreshToken) + try container.encodeIfPresent(clientId, forKey: .clientId) + try container.encodeIfPresent(clientSecret, forKey: .clientSecret) + try container.encodeIfPresent(projectId, forKey: .projectId) + try container.encodeIfPresent(indexingPrefix, forKey: .indexingPrefix) + try container.encodeIfPresent(queryPrefix, forKey: .queryPrefix) + } } + diff --git a/Sources/Typesense/Models/GetCollectionsGetCollectionsParametersParameter.swift b/Sources/Typesense/Models/GetCollectionsGetCollectionsParametersParameter.swift new file mode 100644 index 0000000..4ee1266 --- /dev/null +++ b/Sources/Typesense/Models/GetCollectionsGetCollectionsParametersParameter.swift @@ -0,0 +1,43 @@ +// +// GetCollectionsGetCollectionsParametersParameter.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct GetCollectionsGetCollectionsParametersParameter: Codable { + + /** Comma-separated list of fields from the collection to exclude from the response */ + public var excludeFields: String? + /** Number of collections to fetch. Default: returns all collections. */ + public var limit: Int? + /** Identifies the starting point to return collections when paginating. */ + public var offset: Int? + + public init(excludeFields: String? = nil, limit: Int? = nil, offset: Int? = nil) { + self.excludeFields = excludeFields + self.limit = limit + self.offset = offset + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case excludeFields = "exclude_fields" + case limit + case offset + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(excludeFields, forKey: .excludeFields) + try container.encodeIfPresent(limit, forKey: .limit) + try container.encodeIfPresent(offset, forKey: .offset) + } +} + diff --git a/Sources/Typesense/Models/HealthStatus.swift b/Sources/Typesense/Models/HealthStatus.swift index 3bfa211..168ea87 100644 --- a/Sources/Typesense/Models/HealthStatus.swift +++ b/Sources/Typesense/Models/HealthStatus.swift @@ -1,13 +1,14 @@ // // HealthStatus.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct HealthStatus: Codable { @@ -17,5 +18,15 @@ public struct HealthStatus: Codable { self.ok = ok } + public enum CodingKeys: String, CodingKey, CaseIterable { + case ok + } + + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(ok, forKey: .ok) + } } + diff --git a/Sources/Typesense/Models/ImportDocumentsImportDocumentsParametersParameter.swift b/Sources/Typesense/Models/ImportDocumentsImportDocumentsParametersParameter.swift new file mode 100644 index 0000000..0b8342f --- /dev/null +++ b/Sources/Typesense/Models/ImportDocumentsImportDocumentsParametersParameter.swift @@ -0,0 +1,53 @@ +// +// ImportDocumentsImportDocumentsParametersParameter.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ImportDocumentsImportDocumentsParametersParameter: Codable { + + public var batchSize: Int? + /** 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. */ + public var returnId: Bool? + public var remoteEmbeddingBatchSize: Int? + public var returnDoc: Bool? + public var action: IndexAction? + public var dirtyValues: DirtyValues? + + public init(batchSize: Int? = nil, returnId: Bool? = nil, remoteEmbeddingBatchSize: Int? = nil, returnDoc: Bool? = nil, action: IndexAction? = nil, dirtyValues: DirtyValues? = nil) { + self.batchSize = batchSize + self.returnId = returnId + self.remoteEmbeddingBatchSize = remoteEmbeddingBatchSize + self.returnDoc = returnDoc + self.action = action + self.dirtyValues = dirtyValues + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case batchSize = "batch_size" + case returnId = "return_id" + case remoteEmbeddingBatchSize = "remote_embedding_batch_size" + case returnDoc = "return_doc" + case action + case dirtyValues = "dirty_values" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(batchSize, forKey: .batchSize) + try container.encodeIfPresent(returnId, forKey: .returnId) + try container.encodeIfPresent(remoteEmbeddingBatchSize, forKey: .remoteEmbeddingBatchSize) + try container.encodeIfPresent(returnDoc, forKey: .returnDoc) + try container.encodeIfPresent(action, forKey: .action) + try container.encodeIfPresent(dirtyValues, forKey: .dirtyValues) + } +} + diff --git a/Sources/Typesense/Models/ImportDocumentsParameters.swift b/Sources/Typesense/Models/ImportDocumentsParameters.swift deleted file mode 100644 index f925975..0000000 --- a/Sources/Typesense/Models/ImportDocumentsParameters.swift +++ /dev/null @@ -1,39 +0,0 @@ -// -// ImportDocumentsParameters.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct ImportDocumentsParameters: Codable { - - public var action: IndexAction? - public var batchSize: Int? - public var dirtyValues: DirtyValues? - public var remoteEmbeddingBatchSize: Int? - public var returnDoc: Bool? - public var returnId: Bool? - - public init(action: IndexAction? = nil, batchSize: Int? = nil, dirtyValues: DirtyValues? = nil, remoteEmbeddingBatchSize: Int? = nil, returnDoc: Bool? = nil, returnId: Bool? = nil) { - self.action = action - self.batchSize = batchSize - self.dirtyValues = dirtyValues - self.remoteEmbeddingBatchSize = remoteEmbeddingBatchSize - self.returnDoc = returnDoc - self.returnId = returnId - } - - public enum CodingKeys: String, CodingKey { - case action - case batchSize = "batch_size" - case dirtyValues = "dirty_values" - case remoteEmbeddingBatchSize = "remote_embedding_batch_size" - case returnDoc = "return_doc" - case returnId = "return_id" - } - -} diff --git a/Sources/Typesense/Models/IndexAction.swift b/Sources/Typesense/Models/IndexAction.swift new file mode 100644 index 0000000..e6d66bd --- /dev/null +++ b/Sources/Typesense/Models/IndexAction.swift @@ -0,0 +1,18 @@ +// +// IndexAction.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum IndexAction: String, Codable, CaseIterable { + case create = "create" + case update = "update" + case upsert = "upsert" + case emplace = "emplace" +} diff --git a/Sources/Typesense/Models/InlineResponse2002.swift b/Sources/Typesense/Models/InlineResponse2002.swift deleted file mode 100644 index f81d08a..0000000 --- a/Sources/Typesense/Models/InlineResponse2002.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// InlineResponse2002.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct InlineResponse2002: Codable { - - public var version: String? - - public init(version: String? = nil) { - self.version = version - } - - -} diff --git a/Sources/Typesense/Models/ListStemmingDictionaries200Response.swift b/Sources/Typesense/Models/ListStemmingDictionaries200Response.swift new file mode 100644 index 0000000..296dcd1 --- /dev/null +++ b/Sources/Typesense/Models/ListStemmingDictionaries200Response.swift @@ -0,0 +1,32 @@ +// +// ListStemmingDictionaries200Response.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ListStemmingDictionaries200Response: Codable { + + public var dictionaries: [String]? + + public init(dictionaries: [String]? = nil) { + self.dictionaries = dictionaries + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case dictionaries + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(dictionaries, forKey: .dictionaries) + } +} + diff --git a/Sources/Typesense/Models/ModelErrorResponse.swift b/Sources/Typesense/Models/ModelErrorResponse.swift deleted file mode 100644 index 134e8a4..0000000 --- a/Sources/Typesense/Models/ModelErrorResponse.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// ModelErrorResponse.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct ModelErrorResponse: Codable { - - public var message: String? - - public init(message: String? = nil) { - self.message = message - } - - -} diff --git a/Sources/Typesense/Models/MultiSearchCollectionParameters.swift b/Sources/Typesense/Models/MultiSearchCollectionParameters.swift index 5b7bf1a..1cebef9 100644 --- a/Sources/Typesense/Models/MultiSearchCollectionParameters.swift +++ b/Sources/Typesense/Models/MultiSearchCollectionParameters.swift @@ -1,41 +1,42 @@ // // MultiSearchCollectionParameters.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MultiSearchCollectionParameters: Codable { /** 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. */ public var q: String? - /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ + /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ public var queryBy: 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. */ + /** 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. */ public var queryByWeights: 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. */ public var textMatchType: 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. */ public var _prefix: String? - /** 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 */ + /** 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 */ public var _infix: String? - /** 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. */ + /** 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. */ public var maxExtraPrefix: Int? - /** 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. */ + /** 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. */ public var maxExtraSuffix: Int? - /** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */ + /** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */ public var filterBy: 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` */ + /** 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` */ public var sortBy: String? /** A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. */ public var facetBy: String? /** Maximum number of facet values to be returned. */ public var maxFacetValues: Int? - /** 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\". */ + /** 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\". */ public var facetQuery: String? /** The number of typographical errors (1 or 2) that would be tolerated. Default: 2 */ public var numTypos: String? @@ -47,9 +48,9 @@ public struct MultiSearchCollectionParameters: Codable { public var limit: Int? /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ public var offset: Int? - /** 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. */ + /** 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. */ public var groupBy: String? - /** 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 */ public var groupLimit: Int? /** 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 */ public var groupMissingValues: Bool? @@ -61,38 +62,51 @@ public struct MultiSearchCollectionParameters: Codable { public var highlightFullFields: String? /** The number of tokens that should surround the highlighted text on each side. Default: 4 */ public var highlightAffixNumTokens: Int? - /** The start tag used for the highlighted snippets. Default: `<mark>` */ + /** The start tag used for the highlighted snippets. Default: `` */ public var highlightStartTag: String? - /** The end tag used for the highlighted snippets. Default: `</mark>` */ + /** The end tag used for the highlighted snippets. Default: `` */ public var highlightEndTag: String? /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ public var snippetThreshold: Int? /** 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 */ public var dropTokensThreshold: Int? + public var dropTokensMode: DropTokensMode? /** 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 */ public var typoTokensThreshold: Int? - /** 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. */ + public var enableTyposForAlphaNumericalTokens: 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 */ + public var filterCuratedHits: 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 */ + public var enableSynonyms: Bool? + /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ + public var enableAnalytics: Bool? = true + /** Allow synonym resolution on word prefixes in the query. Default: false */ + public var synonymPrefix: Bool? + /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ + public var synonymNumTypos: Int? + /** 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`. */ public var pinnedHits: 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`. */ + /** 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`. */ public var hiddenHits: String? /** Comma separated list of tags to trigger the curations rules that match the tags. */ public var overrideTags: String? - /** A list of custom fields that must be highlighted even if you don't query for them */ + /** A list of custom fields that must be highlighted even if you don't query for them */ public var highlightFields: String? /** 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 */ - public var preSegmentedQuery: Bool? + public var preSegmentedQuery: Bool? = false /** Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. */ public var preset: String? /** 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 */ - public var enableOverrides: Bool? + public var enableOverrides: Bool? = false /** Set this parameter to true to ensure that an exact match is ranked above the others */ - public var prioritizeExactMatch: Bool? + public var prioritizeExactMatch: Bool? = true /** Make Typesense prioritize documents where the query words appear earlier in the text. */ - public var prioritizeTokenPosition: Bool? + public var prioritizeTokenPosition: Bool? = false /** Make Typesense prioritize documents where the query words appear in more number of fields. */ - public var prioritizeNumMatchingFields: Bool? + public var prioritizeNumMatchingFields: Bool? = true /** Make Typesense disable typos for numerical tokens. */ - public var enableTyposForNumericalTokens: Bool? + public var enableTyposForNumericalTokens: Bool? = true /** 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). */ public var exhaustiveSearch: Bool? /** 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. */ @@ -105,14 +119,12 @@ public struct MultiSearchCollectionParameters: Codable { public var minLen1typo: Int? /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ public var minLen2typo: Int? - /** 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. */ public var vectorQuery: String? /** Timeout (in milliseconds) for fetching remote embeddings. */ public var remoteEmbeddingTimeoutMs: Int? /** Number of times to retry fetching remote embeddings. */ public var remoteEmbeddingNumTries: Int? - /** The collection to search in. */ - public var collection: String? /** Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). */ public var facetStrategy: String? /** Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. */ @@ -121,12 +133,20 @@ public struct MultiSearchCollectionParameters: Codable { public var facetReturnParent: String? /** The base64 encoded audio file in 16 khz 16-bit WAV format. */ public var voiceQuery: String? - /** Whether to rerank hybrid matches. */ - public var rerankHybridMatches: Bool? - /** API key for the request. */ + /** Enable conversational search. */ + public var conversation: Bool? + /** The Id of Conversation Model to be used. */ + public var conversationModelId: String? + /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ + public var conversationId: String? + /** The collection to search in. */ + public var collection: String? + /** A separate search API key for each search within a multi_search request */ public var xTypesenseApiKey: String? + /** 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. */ + public var rerankHybridMatches: Bool? = false - public init(q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, textMatchType: String? = nil, _prefix: String? = nil, _infix: String? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, filterBy: String? = nil, sortBy: String? = nil, facetBy: String? = nil, maxFacetValues: Int? = nil, facetQuery: String? = nil, numTypos: String? = nil, page: Int? = nil, perPage: Int? = nil, limit: Int? = nil, offset: Int? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, includeFields: String? = nil, excludeFields: String? = nil, highlightFullFields: String? = nil, highlightAffixNumTokens: Int? = nil, highlightStartTag: String? = nil, highlightEndTag: String? = nil, snippetThreshold: Int? = nil, dropTokensThreshold: Int? = nil, typoTokensThreshold: Int? = nil, pinnedHits: String? = nil, hiddenHits: String? = nil, overrideTags: String? = nil, highlightFields: String? = nil, preSegmentedQuery: Bool? = nil, preset: String? = nil, enableOverrides: Bool? = nil, prioritizeExactMatch: Bool? = nil, prioritizeTokenPosition: Bool? = nil, prioritizeNumMatchingFields: Bool? = nil, enableTyposForNumericalTokens: Bool? = nil, exhaustiveSearch: Bool? = nil, searchCutoffMs: Int? = nil, useCache: Bool? = nil, cacheTtl: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, vectorQuery: String? = nil, remoteEmbeddingTimeoutMs: Int? = nil, remoteEmbeddingNumTries: Int? = nil, collection: String? = nil, facetStrategy: String? = nil, stopwords: String? = nil, facetReturnParent: String? = nil, voiceQuery: String? = nil, rerankHybridMatches: Bool? = nil, xTypesenseApiKey: String? = nil) { + public init(q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, textMatchType: String? = nil, _prefix: String? = nil, _infix: String? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, filterBy: String? = nil, sortBy: String? = nil, facetBy: String? = nil, maxFacetValues: Int? = nil, facetQuery: String? = nil, numTypos: String? = nil, page: Int? = nil, perPage: Int? = nil, limit: Int? = nil, offset: Int? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, includeFields: String? = nil, excludeFields: String? = nil, highlightFullFields: String? = nil, highlightAffixNumTokens: Int? = nil, highlightStartTag: String? = nil, highlightEndTag: String? = nil, snippetThreshold: Int? = nil, dropTokensThreshold: Int? = nil, dropTokensMode: DropTokensMode? = nil, typoTokensThreshold: Int? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, filterCuratedHits: Bool? = nil, enableSynonyms: Bool? = nil, enableAnalytics: Bool? = true, synonymPrefix: Bool? = nil, synonymNumTypos: Int? = nil, pinnedHits: String? = nil, hiddenHits: String? = nil, overrideTags: String? = nil, highlightFields: String? = nil, preSegmentedQuery: Bool? = false, preset: String? = nil, enableOverrides: Bool? = false, prioritizeExactMatch: Bool? = true, prioritizeTokenPosition: Bool? = false, prioritizeNumMatchingFields: Bool? = true, enableTyposForNumericalTokens: Bool? = true, exhaustiveSearch: Bool? = nil, searchCutoffMs: Int? = nil, useCache: Bool? = nil, cacheTtl: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, vectorQuery: String? = nil, remoteEmbeddingTimeoutMs: Int? = nil, remoteEmbeddingNumTries: Int? = nil, facetStrategy: String? = nil, stopwords: String? = nil, facetReturnParent: String? = nil, voiceQuery: String? = nil, conversation: Bool? = nil, conversationModelId: String? = nil, conversationId: String? = nil, collection: String? = nil, xTypesenseApiKey: String? = nil, rerankHybridMatches: Bool? = false) { self.q = q self.queryBy = queryBy self.queryByWeights = queryByWeights @@ -156,7 +176,14 @@ public struct MultiSearchCollectionParameters: Codable { self.highlightEndTag = highlightEndTag self.snippetThreshold = snippetThreshold self.dropTokensThreshold = dropTokensThreshold + self.dropTokensMode = dropTokensMode self.typoTokensThreshold = typoTokensThreshold + self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens + self.filterCuratedHits = filterCuratedHits + self.enableSynonyms = enableSynonyms + self.enableAnalytics = enableAnalytics + self.synonymPrefix = synonymPrefix + self.synonymNumTypos = synonymNumTypos self.pinnedHits = pinnedHits self.hiddenHits = hiddenHits self.overrideTags = overrideTags @@ -177,17 +204,19 @@ public struct MultiSearchCollectionParameters: Codable { self.vectorQuery = vectorQuery self.remoteEmbeddingTimeoutMs = remoteEmbeddingTimeoutMs self.remoteEmbeddingNumTries = remoteEmbeddingNumTries - self.collection = collection self.facetStrategy = facetStrategy self.stopwords = stopwords self.facetReturnParent = facetReturnParent self.voiceQuery = voiceQuery - self.rerankHybridMatches = rerankHybridMatches + self.conversation = conversation + self.conversationModelId = conversationModelId + self.conversationId = conversationId + self.collection = collection self.xTypesenseApiKey = xTypesenseApiKey + self.rerankHybridMatches = rerankHybridMatches } - public enum CodingKeys: String, CodingKey { - case collection + public enum CodingKeys: String, CodingKey, CaseIterable { case q case queryBy = "query_by" case queryByWeights = "query_by_weights" @@ -217,7 +246,14 @@ public struct MultiSearchCollectionParameters: Codable { case highlightEndTag = "highlight_end_tag" case snippetThreshold = "snippet_threshold" case dropTokensThreshold = "drop_tokens_threshold" + case dropTokensMode = "drop_tokens_mode" case typoTokensThreshold = "typo_tokens_threshold" + case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" + case filterCuratedHits = "filter_curated_hits" + case enableSynonyms = "enable_synonyms" + case enableAnalytics = "enable_analytics" + case synonymPrefix = "synonym_prefix" + case synonymNumTypos = "synonym_num_typos" case pinnedHits = "pinned_hits" case hiddenHits = "hidden_hits" case overrideTags = "override_tags" @@ -242,8 +278,85 @@ public struct MultiSearchCollectionParameters: Codable { case stopwords case facetReturnParent = "facet_return_parent" case voiceQuery = "voice_query" - case rerankHybridMatches = "rerank_hybrid_matches" + case conversation + case conversationModelId = "conversation_model_id" + case conversationId = "conversation_id" + case collection case xTypesenseApiKey = "x-typesense-api-key" + case rerankHybridMatches = "rerank_hybrid_matches" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(q, forKey: .q) + try container.encodeIfPresent(queryBy, forKey: .queryBy) + try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) + try container.encodeIfPresent(textMatchType, forKey: .textMatchType) + try container.encodeIfPresent(_prefix, forKey: ._prefix) + try container.encodeIfPresent(_infix, forKey: ._infix) + try container.encodeIfPresent(maxExtraPrefix, forKey: .maxExtraPrefix) + try container.encodeIfPresent(maxExtraSuffix, forKey: .maxExtraSuffix) + try container.encodeIfPresent(filterBy, forKey: .filterBy) + try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(facetBy, forKey: .facetBy) + try container.encodeIfPresent(maxFacetValues, forKey: .maxFacetValues) + try container.encodeIfPresent(facetQuery, forKey: .facetQuery) + try container.encodeIfPresent(numTypos, forKey: .numTypos) + try container.encodeIfPresent(page, forKey: .page) + try container.encodeIfPresent(perPage, forKey: .perPage) + try container.encodeIfPresent(limit, forKey: .limit) + try container.encodeIfPresent(offset, forKey: .offset) + try container.encodeIfPresent(groupBy, forKey: .groupBy) + try container.encodeIfPresent(groupLimit, forKey: .groupLimit) + try container.encodeIfPresent(groupMissingValues, forKey: .groupMissingValues) + try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(excludeFields, forKey: .excludeFields) + try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) + try container.encodeIfPresent(highlightAffixNumTokens, forKey: .highlightAffixNumTokens) + try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) + try container.encodeIfPresent(highlightEndTag, forKey: .highlightEndTag) + try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) + try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) + try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) + try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) + try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) + try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) + try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) + try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) + try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) + try container.encodeIfPresent(pinnedHits, forKey: .pinnedHits) + try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) + try container.encodeIfPresent(overrideTags, forKey: .overrideTags) + try container.encodeIfPresent(highlightFields, forKey: .highlightFields) + try container.encodeIfPresent(preSegmentedQuery, forKey: .preSegmentedQuery) + try container.encodeIfPresent(preset, forKey: .preset) + try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) + try container.encodeIfPresent(prioritizeExactMatch, forKey: .prioritizeExactMatch) + try container.encodeIfPresent(prioritizeTokenPosition, forKey: .prioritizeTokenPosition) + try container.encodeIfPresent(prioritizeNumMatchingFields, forKey: .prioritizeNumMatchingFields) + try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) + try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) + try container.encodeIfPresent(searchCutoffMs, forKey: .searchCutoffMs) + try container.encodeIfPresent(useCache, forKey: .useCache) + try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) + try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) + try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) + try container.encodeIfPresent(vectorQuery, forKey: .vectorQuery) + try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) + try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) + try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) + try container.encodeIfPresent(stopwords, forKey: .stopwords) + try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) + try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) + try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) + try container.encodeIfPresent(conversationId, forKey: .conversationId) + try container.encodeIfPresent(collection, forKey: .collection) + try container.encodeIfPresent(xTypesenseApiKey, forKey: .xTypesenseApiKey) + try container.encodeIfPresent(rerankHybridMatches, forKey: .rerankHybridMatches) + } } + diff --git a/Sources/Typesense/Models/MultiSearchParameters.swift b/Sources/Typesense/Models/MultiSearchParameters.swift index 9f868ed..e1e5765 100644 --- a/Sources/Typesense/Models/MultiSearchParameters.swift +++ b/Sources/Typesense/Models/MultiSearchParameters.swift @@ -1,42 +1,43 @@ // // MultiSearchParameters.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - +#if canImport(AnyCodable) +import AnyCodable +#endif /** Parameters for the multi search API. */ - public struct MultiSearchParameters: Codable { /** 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. */ public var q: String? - /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ + /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ public var queryBy: 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. */ + /** 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. */ public var queryByWeights: 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. */ public var textMatchType: 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. */ public var _prefix: String? - /** 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 */ + /** 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 */ public var _infix: String? - /** 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. */ + /** 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. */ public var maxExtraPrefix: Int? - /** 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. */ + /** 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. */ public var maxExtraSuffix: Int? - /** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */ + /** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */ public var filterBy: 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` */ + /** 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` */ public var sortBy: String? /** A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. */ public var facetBy: String? /** Maximum number of facet values to be returned. */ public var maxFacetValues: Int? - /** 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\". */ + /** 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\". */ public var facetQuery: String? /** The number of typographical errors (1 or 2) that would be tolerated. Default: 2 */ public var numTypos: String? @@ -48,9 +49,9 @@ public struct MultiSearchParameters: Codable { public var limit: Int? /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ public var offset: Int? - /** 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. */ + /** 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. */ public var groupBy: String? - /** 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 */ public var groupLimit: Int? /** 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 */ public var groupMissingValues: Bool? @@ -62,38 +63,51 @@ public struct MultiSearchParameters: Codable { public var highlightFullFields: String? /** The number of tokens that should surround the highlighted text on each side. Default: 4 */ public var highlightAffixNumTokens: Int? - /** The start tag used for the highlighted snippets. Default: `<mark>` */ + /** The start tag used for the highlighted snippets. Default: `` */ public var highlightStartTag: String? - /** The end tag used for the highlighted snippets. Default: `</mark>` */ + /** The end tag used for the highlighted snippets. Default: `` */ public var highlightEndTag: String? /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ public var snippetThreshold: Int? /** 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 */ public var dropTokensThreshold: Int? + public var dropTokensMode: DropTokensMode? /** 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 */ public var typoTokensThreshold: Int? - /** 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. */ + public var enableTyposForAlphaNumericalTokens: 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 */ + public var filterCuratedHits: 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 */ + public var enableSynonyms: Bool? + /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ + public var enableAnalytics: Bool? = true + /** Allow synonym resolution on word prefixes in the query. Default: false */ + public var synonymPrefix: Bool? + /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ + public var synonymNumTypos: Int? + /** 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`. */ public var pinnedHits: 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`. */ + /** 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`. */ public var hiddenHits: String? /** Comma separated list of tags to trigger the curations rules that match the tags. */ public var overrideTags: String? - /** A list of custom fields that must be highlighted even if you don't query for them */ + /** A list of custom fields that must be highlighted even if you don't query for them */ public var highlightFields: String? /** 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 */ - public var preSegmentedQuery: Bool? + public var preSegmentedQuery: Bool? = false /** Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. */ public var preset: String? /** 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 */ - public var enableOverrides: Bool? + public var enableOverrides: Bool? = false /** Set this parameter to true to ensure that an exact match is ranked above the others */ - public var prioritizeExactMatch: Bool? + public var prioritizeExactMatch: Bool? = true /** Make Typesense prioritize documents where the query words appear earlier in the text. */ - public var prioritizeTokenPosition: Bool? + public var prioritizeTokenPosition: Bool? = false /** Make Typesense prioritize documents where the query words appear in more number of fields. */ - public var prioritizeNumMatchingFields: Bool? + public var prioritizeNumMatchingFields: Bool? = true /** Make Typesense disable typos for numerical tokens. */ - public var enableTyposForNumericalTokens: Bool? + public var enableTyposForNumericalTokens: Bool? = true /** 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). */ public var exhaustiveSearch: Bool? /** 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. */ @@ -106,7 +120,7 @@ public struct MultiSearchParameters: Codable { public var minLen1typo: Int? /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ public var minLen2typo: Int? - /** 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. */ public var vectorQuery: String? /** Timeout (in milliseconds) for fetching remote embeddings. */ public var remoteEmbeddingTimeoutMs: Int? @@ -126,12 +140,8 @@ public struct MultiSearchParameters: Codable { public var conversationModelId: String? /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ public var conversationId: String? - /** Whether to rerank hybrid matches. */ - public var rerankHybridMatches: Bool? - /** API key for the request. */ - public var xTypesenseApiKey: String? - public init(q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, textMatchType: String? = nil, _prefix: String? = nil, _infix: String? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, filterBy: String? = nil, sortBy: String? = nil, facetBy: String? = nil, maxFacetValues: Int? = nil, facetQuery: String? = nil, numTypos: String? = nil, page: Int? = nil, perPage: Int? = nil, limit: Int? = nil, offset: Int? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, includeFields: String? = nil, excludeFields: String? = nil, highlightFullFields: String? = nil, highlightAffixNumTokens: Int? = nil, highlightStartTag: String? = nil, highlightEndTag: String? = nil, snippetThreshold: Int? = nil, dropTokensThreshold: Int? = nil, typoTokensThreshold: Int? = nil, pinnedHits: String? = nil, hiddenHits: String? = nil, overrideTags: String? = nil, highlightFields: String? = nil, preSegmentedQuery: Bool? = nil, preset: String? = nil, enableOverrides: Bool? = nil, prioritizeExactMatch: Bool? = nil, prioritizeTokenPosition: Bool? = nil, prioritizeNumMatchingFields: Bool? = nil, enableTyposForNumericalTokens: Bool? = nil, exhaustiveSearch: Bool? = nil, searchCutoffMs: Int? = nil, useCache: Bool? = nil, cacheTtl: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, vectorQuery: String? = nil, remoteEmbeddingTimeoutMs: Int? = nil, remoteEmbeddingNumTries: Int? = nil, facetStrategy: String? = nil, stopwords: String? = nil, facetReturnParent: String? = nil, voiceQuery: String? = nil, conversation: Bool? = nil, conversationModelId: String? = nil, conversationId: String? = nil, rerankHybridMatches: Bool? = nil, xTypesenseApiKey: String? = nil) { + public init(q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, textMatchType: String? = nil, _prefix: String? = nil, _infix: String? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, filterBy: String? = nil, sortBy: String? = nil, facetBy: String? = nil, maxFacetValues: Int? = nil, facetQuery: String? = nil, numTypos: String? = nil, page: Int? = nil, perPage: Int? = nil, limit: Int? = nil, offset: Int? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, includeFields: String? = nil, excludeFields: String? = nil, highlightFullFields: String? = nil, highlightAffixNumTokens: Int? = nil, highlightStartTag: String? = nil, highlightEndTag: String? = nil, snippetThreshold: Int? = nil, dropTokensThreshold: Int? = nil, dropTokensMode: DropTokensMode? = nil, typoTokensThreshold: Int? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, filterCuratedHits: Bool? = nil, enableSynonyms: Bool? = nil, enableAnalytics: Bool? = true, synonymPrefix: Bool? = nil, synonymNumTypos: Int? = nil, pinnedHits: String? = nil, hiddenHits: String? = nil, overrideTags: String? = nil, highlightFields: String? = nil, preSegmentedQuery: Bool? = false, preset: String? = nil, enableOverrides: Bool? = false, prioritizeExactMatch: Bool? = true, prioritizeTokenPosition: Bool? = false, prioritizeNumMatchingFields: Bool? = true, enableTyposForNumericalTokens: Bool? = true, exhaustiveSearch: Bool? = nil, searchCutoffMs: Int? = nil, useCache: Bool? = nil, cacheTtl: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, vectorQuery: String? = nil, remoteEmbeddingTimeoutMs: Int? = nil, remoteEmbeddingNumTries: Int? = nil, facetStrategy: String? = nil, stopwords: String? = nil, facetReturnParent: String? = nil, voiceQuery: String? = nil, conversation: Bool? = nil, conversationModelId: String? = nil, conversationId: String? = nil) { self.q = q self.queryBy = queryBy self.queryByWeights = queryByWeights @@ -161,7 +171,14 @@ public struct MultiSearchParameters: Codable { self.highlightEndTag = highlightEndTag self.snippetThreshold = snippetThreshold self.dropTokensThreshold = dropTokensThreshold + self.dropTokensMode = dropTokensMode self.typoTokensThreshold = typoTokensThreshold + self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens + self.filterCuratedHits = filterCuratedHits + self.enableSynonyms = enableSynonyms + self.enableAnalytics = enableAnalytics + self.synonymPrefix = synonymPrefix + self.synonymNumTypos = synonymNumTypos self.pinnedHits = pinnedHits self.hiddenHits = hiddenHits self.overrideTags = overrideTags @@ -189,11 +206,9 @@ public struct MultiSearchParameters: Codable { self.conversation = conversation self.conversationModelId = conversationModelId self.conversationId = conversationId - self.rerankHybridMatches = rerankHybridMatches - self.xTypesenseApiKey = xTypesenseApiKey } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case q case queryBy = "query_by" case queryByWeights = "query_by_weights" @@ -223,7 +238,14 @@ public struct MultiSearchParameters: Codable { case highlightEndTag = "highlight_end_tag" case snippetThreshold = "snippet_threshold" case dropTokensThreshold = "drop_tokens_threshold" + case dropTokensMode = "drop_tokens_mode" case typoTokensThreshold = "typo_tokens_threshold" + case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" + case filterCuratedHits = "filter_curated_hits" + case enableSynonyms = "enable_synonyms" + case enableAnalytics = "enable_analytics" + case synonymPrefix = "synonym_prefix" + case synonymNumTypos = "synonym_num_typos" case pinnedHits = "pinned_hits" case hiddenHits = "hidden_hits" case overrideTags = "override_tags" @@ -251,8 +273,76 @@ public struct MultiSearchParameters: Codable { case conversation case conversationModelId = "conversation_model_id" case conversationId = "conversation_id" - case rerankHybridMatches = "rerank_hybrid_matches" - case xTypesenseApiKey = "x-typesense-api-key" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(q, forKey: .q) + try container.encodeIfPresent(queryBy, forKey: .queryBy) + try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) + try container.encodeIfPresent(textMatchType, forKey: .textMatchType) + try container.encodeIfPresent(_prefix, forKey: ._prefix) + try container.encodeIfPresent(_infix, forKey: ._infix) + try container.encodeIfPresent(maxExtraPrefix, forKey: .maxExtraPrefix) + try container.encodeIfPresent(maxExtraSuffix, forKey: .maxExtraSuffix) + try container.encodeIfPresent(filterBy, forKey: .filterBy) + try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(facetBy, forKey: .facetBy) + try container.encodeIfPresent(maxFacetValues, forKey: .maxFacetValues) + try container.encodeIfPresent(facetQuery, forKey: .facetQuery) + try container.encodeIfPresent(numTypos, forKey: .numTypos) + try container.encodeIfPresent(page, forKey: .page) + try container.encodeIfPresent(perPage, forKey: .perPage) + try container.encodeIfPresent(limit, forKey: .limit) + try container.encodeIfPresent(offset, forKey: .offset) + try container.encodeIfPresent(groupBy, forKey: .groupBy) + try container.encodeIfPresent(groupLimit, forKey: .groupLimit) + try container.encodeIfPresent(groupMissingValues, forKey: .groupMissingValues) + try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(excludeFields, forKey: .excludeFields) + try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) + try container.encodeIfPresent(highlightAffixNumTokens, forKey: .highlightAffixNumTokens) + try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) + try container.encodeIfPresent(highlightEndTag, forKey: .highlightEndTag) + try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) + try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) + try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) + try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) + try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) + try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) + try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) + try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) + try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) + try container.encodeIfPresent(pinnedHits, forKey: .pinnedHits) + try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) + try container.encodeIfPresent(overrideTags, forKey: .overrideTags) + try container.encodeIfPresent(highlightFields, forKey: .highlightFields) + try container.encodeIfPresent(preSegmentedQuery, forKey: .preSegmentedQuery) + try container.encodeIfPresent(preset, forKey: .preset) + try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) + try container.encodeIfPresent(prioritizeExactMatch, forKey: .prioritizeExactMatch) + try container.encodeIfPresent(prioritizeTokenPosition, forKey: .prioritizeTokenPosition) + try container.encodeIfPresent(prioritizeNumMatchingFields, forKey: .prioritizeNumMatchingFields) + try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) + try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) + try container.encodeIfPresent(searchCutoffMs, forKey: .searchCutoffMs) + try container.encodeIfPresent(useCache, forKey: .useCache) + try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) + try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) + try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) + try container.encodeIfPresent(vectorQuery, forKey: .vectorQuery) + try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) + try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) + try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) + try container.encodeIfPresent(stopwords, forKey: .stopwords) + try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) + try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) + try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) + try container.encodeIfPresent(conversationId, forKey: .conversationId) + } } + diff --git a/Sources/Typesense/Models/MultiSearchResult.swift b/Sources/Typesense/Models/MultiSearchResult.swift index c7cdfc3..c99c372 100644 --- a/Sources/Typesense/Models/MultiSearchResult.swift +++ b/Sources/Typesense/Models/MultiSearchResult.swift @@ -1,23 +1,36 @@ // // MultiSearchResult.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +public struct MultiSearchResult: Codable { - -public struct MultiSearchResult: Decodable { - - public var results: [SearchResult] + public var results: [MultiSearchResultItem] public var conversation: SearchResultConversation? - public init(results: [SearchResult], conversation: SearchResultConversation? = nil) { + public init(results: [MultiSearchResultItem], conversation: SearchResultConversation? = nil) { self.results = results self.conversation = conversation } + public enum CodingKeys: String, CodingKey, CaseIterable { + case results + case conversation + } + + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(results, forKey: .results) + try container.encodeIfPresent(conversation, forKey: .conversation) + } } + diff --git a/Sources/Typesense/Models/MultiSearchResultItem.swift b/Sources/Typesense/Models/MultiSearchResultItem.swift new file mode 100644 index 0000000..8e3cdae --- /dev/null +++ b/Sources/Typesense/Models/MultiSearchResultItem.swift @@ -0,0 +1,98 @@ +// +// MultiSearchResultItem.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct MultiSearchResultItem: Codable { + + public var facetCounts: [FacetCounts]? + /** The number of documents found */ + public var found: Int? + public var foundDocs: Int? + /** The number of milliseconds the search took */ + public var searchTimeMs: Int? + /** The total number of documents in the collection */ + public var outOf: Int? + /** Whether the search was cut off */ + public var searchCutoff: Bool? + /** The search result page number */ + public var page: Int? + public var groupedHits: [SearchGroupedHit]? + /** The documents that matched the search query */ + public var hits: [SearchResultHit]? + public var requestParams: SearchRequestParams? + public var conversation: SearchResultConversation? + /** Returned only for union query response. */ + public var unionRequestParams: [SearchRequestParams]? + /** Custom JSON object that can be returned in the search response */ + public var metadata: [String: AnyCodable]? + /** HTTP error code */ + public var code: Int64? + /** Error description */ + public var error: String? + + public init(facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, searchTimeMs: Int? = nil, outOf: Int? = nil, searchCutoff: Bool? = nil, page: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, requestParams: SearchRequestParams? = nil, conversation: SearchResultConversation? = nil, unionRequestParams: [SearchRequestParams]? = nil, metadata: [String: AnyCodable]? = nil, code: Int64? = nil, error: String? = nil) { + self.facetCounts = facetCounts + self.found = found + self.foundDocs = foundDocs + self.searchTimeMs = searchTimeMs + self.outOf = outOf + self.searchCutoff = searchCutoff + self.page = page + self.groupedHits = groupedHits + self.hits = hits + self.requestParams = requestParams + self.conversation = conversation + self.unionRequestParams = unionRequestParams + self.metadata = metadata + self.code = code + self.error = error + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case facetCounts = "facet_counts" + case found + case foundDocs = "found_docs" + case searchTimeMs = "search_time_ms" + case outOf = "out_of" + case searchCutoff = "search_cutoff" + case page + case groupedHits = "grouped_hits" + case hits + case requestParams = "request_params" + case conversation + case unionRequestParams = "union_request_params" + case metadata + case code + case error + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(facetCounts, forKey: .facetCounts) + try container.encodeIfPresent(found, forKey: .found) + try container.encodeIfPresent(foundDocs, forKey: .foundDocs) + try container.encodeIfPresent(searchTimeMs, forKey: .searchTimeMs) + try container.encodeIfPresent(outOf, forKey: .outOf) + try container.encodeIfPresent(searchCutoff, forKey: .searchCutoff) + try container.encodeIfPresent(page, forKey: .page) + try container.encodeIfPresent(groupedHits, forKey: .groupedHits) + try container.encodeIfPresent(hits, forKey: .hits) + try container.encodeIfPresent(requestParams, forKey: .requestParams) + try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encodeIfPresent(unionRequestParams, forKey: .unionRequestParams) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(error, forKey: .error) + } +} + diff --git a/Sources/Typesense/Models/MultiSearchSearchesParameter.swift b/Sources/Typesense/Models/MultiSearchSearchesParameter.swift index 012bdf7..045612f 100644 --- a/Sources/Typesense/Models/MultiSearchSearchesParameter.swift +++ b/Sources/Typesense/Models/MultiSearchSearchesParameter.swift @@ -1,16 +1,37 @@ // // MultiSearchSearchesParameter.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct MultiSearchSearchesParameter: Codable { + + /** When true, merges the search results from each search query into a single ordered set of hits. */ + public var union: Bool? = false public var searches: [MultiSearchCollectionParameters] - public init(searches: [MultiSearchCollectionParameters]) { + public init(union: Bool? = false, searches: [MultiSearchCollectionParameters]) { + self.union = union self.searches = searches } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case union + case searches + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(union, forKey: .union) + try container.encode(searches, forKey: .searches) + } } + diff --git a/Sources/Typesense/Models/NLSearchModelBase.swift b/Sources/Typesense/Models/NLSearchModelBase.swift new file mode 100644 index 0000000..b356eee --- /dev/null +++ b/Sources/Typesense/Models/NLSearchModelBase.swift @@ -0,0 +1,118 @@ +// +// NLSearchModelBase.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct NLSearchModelBase: Codable { + + /** Name of the NL model to use */ + public var modelName: String? + /** API key for the NL model service */ + public var apiKey: String? + /** Custom API URL for the NL model service */ + public var apiUrl: String? + /** Maximum number of bytes to process */ + public var maxBytes: Int? + /** Temperature parameter for the NL model */ + public var temperature: Double? + /** System prompt for the NL model */ + public var systemPrompt: String? + /** Top-p parameter for the NL model (Google-specific) */ + public var topP: Double? + /** Top-k parameter for the NL model (Google-specific) */ + public var topK: Int? + /** Stop sequences for the NL model (Google-specific) */ + public var stopSequences: [String]? + /** API version for the NL model service */ + public var apiVersion: String? + /** Project ID for GCP Vertex AI */ + public var projectId: String? + /** Access token for GCP Vertex AI */ + public var accessToken: String? + /** Refresh token for GCP Vertex AI */ + public var refreshToken: String? + /** Client ID for GCP Vertex AI */ + public var clientId: String? + /** Client secret for GCP Vertex AI */ + public var clientSecret: String? + /** Region for GCP Vertex AI */ + public var region: String? + /** Maximum output tokens for GCP Vertex AI */ + public var maxOutputTokens: Int? + /** Account ID for Cloudflare-specific models */ + public var accountId: String? + + public init(modelName: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, maxBytes: Int? = nil, temperature: Double? = nil, systemPrompt: String? = nil, topP: Double? = nil, topK: Int? = nil, stopSequences: [String]? = nil, apiVersion: String? = nil, projectId: String? = nil, accessToken: String? = nil, refreshToken: String? = nil, clientId: String? = nil, clientSecret: String? = nil, region: String? = nil, maxOutputTokens: Int? = nil, accountId: String? = nil) { + self.modelName = modelName + self.apiKey = apiKey + self.apiUrl = apiUrl + self.maxBytes = maxBytes + self.temperature = temperature + self.systemPrompt = systemPrompt + self.topP = topP + self.topK = topK + self.stopSequences = stopSequences + self.apiVersion = apiVersion + self.projectId = projectId + self.accessToken = accessToken + self.refreshToken = refreshToken + self.clientId = clientId + self.clientSecret = clientSecret + self.region = region + self.maxOutputTokens = maxOutputTokens + self.accountId = accountId + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case modelName = "model_name" + case apiKey = "api_key" + case apiUrl = "api_url" + case maxBytes = "max_bytes" + case temperature + case systemPrompt = "system_prompt" + case topP = "top_p" + case topK = "top_k" + case stopSequences = "stop_sequences" + case apiVersion = "api_version" + case projectId = "project_id" + case accessToken = "access_token" + case refreshToken = "refresh_token" + case clientId = "client_id" + case clientSecret = "client_secret" + case region + case maxOutputTokens = "max_output_tokens" + case accountId = "account_id" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(apiKey, forKey: .apiKey) + try container.encodeIfPresent(apiUrl, forKey: .apiUrl) + try container.encodeIfPresent(maxBytes, forKey: .maxBytes) + try container.encodeIfPresent(temperature, forKey: .temperature) + try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) + try container.encodeIfPresent(topP, forKey: .topP) + try container.encodeIfPresent(topK, forKey: .topK) + try container.encodeIfPresent(stopSequences, forKey: .stopSequences) + try container.encodeIfPresent(apiVersion, forKey: .apiVersion) + try container.encodeIfPresent(projectId, forKey: .projectId) + try container.encodeIfPresent(accessToken, forKey: .accessToken) + try container.encodeIfPresent(refreshToken, forKey: .refreshToken) + try container.encodeIfPresent(clientId, forKey: .clientId) + try container.encodeIfPresent(clientSecret, forKey: .clientSecret) + try container.encodeIfPresent(region, forKey: .region) + try container.encodeIfPresent(maxOutputTokens, forKey: .maxOutputTokens) + try container.encodeIfPresent(accountId, forKey: .accountId) + } +} + diff --git a/Sources/Typesense/Models/NLSearchModelCreateSchema.swift b/Sources/Typesense/Models/NLSearchModelCreateSchema.swift new file mode 100644 index 0000000..bbd1dd0 --- /dev/null +++ b/Sources/Typesense/Models/NLSearchModelCreateSchema.swift @@ -0,0 +1,123 @@ +// +// NLSearchModelCreateSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct NLSearchModelCreateSchema: Codable { + + /** Name of the NL model to use */ + public var modelName: String? + /** API key for the NL model service */ + public var apiKey: String? + /** Custom API URL for the NL model service */ + public var apiUrl: String? + /** Maximum number of bytes to process */ + public var maxBytes: Int? + /** Temperature parameter for the NL model */ + public var temperature: Double? + /** System prompt for the NL model */ + public var systemPrompt: String? + /** Top-p parameter for the NL model (Google-specific) */ + public var topP: Double? + /** Top-k parameter for the NL model (Google-specific) */ + public var topK: Int? + /** Stop sequences for the NL model (Google-specific) */ + public var stopSequences: [String]? + /** API version for the NL model service */ + public var apiVersion: String? + /** Project ID for GCP Vertex AI */ + public var projectId: String? + /** Access token for GCP Vertex AI */ + public var accessToken: String? + /** Refresh token for GCP Vertex AI */ + public var refreshToken: String? + /** Client ID for GCP Vertex AI */ + public var clientId: String? + /** Client secret for GCP Vertex AI */ + public var clientSecret: String? + /** Region for GCP Vertex AI */ + public var region: String? + /** Maximum output tokens for GCP Vertex AI */ + public var maxOutputTokens: Int? + /** Account ID for Cloudflare-specific models */ + public var accountId: String? + /** Optional ID for the NL search model */ + public var id: String? + + public init(modelName: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, maxBytes: Int? = nil, temperature: Double? = nil, systemPrompt: String? = nil, topP: Double? = nil, topK: Int? = nil, stopSequences: [String]? = nil, apiVersion: String? = nil, projectId: String? = nil, accessToken: String? = nil, refreshToken: String? = nil, clientId: String? = nil, clientSecret: String? = nil, region: String? = nil, maxOutputTokens: Int? = nil, accountId: String? = nil, id: String? = nil) { + self.modelName = modelName + self.apiKey = apiKey + self.apiUrl = apiUrl + self.maxBytes = maxBytes + self.temperature = temperature + self.systemPrompt = systemPrompt + self.topP = topP + self.topK = topK + self.stopSequences = stopSequences + self.apiVersion = apiVersion + self.projectId = projectId + self.accessToken = accessToken + self.refreshToken = refreshToken + self.clientId = clientId + self.clientSecret = clientSecret + self.region = region + self.maxOutputTokens = maxOutputTokens + self.accountId = accountId + self.id = id + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case modelName = "model_name" + case apiKey = "api_key" + case apiUrl = "api_url" + case maxBytes = "max_bytes" + case temperature + case systemPrompt = "system_prompt" + case topP = "top_p" + case topK = "top_k" + case stopSequences = "stop_sequences" + case apiVersion = "api_version" + case projectId = "project_id" + case accessToken = "access_token" + case refreshToken = "refresh_token" + case clientId = "client_id" + case clientSecret = "client_secret" + case region + case maxOutputTokens = "max_output_tokens" + case accountId = "account_id" + case id + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(apiKey, forKey: .apiKey) + try container.encodeIfPresent(apiUrl, forKey: .apiUrl) + try container.encodeIfPresent(maxBytes, forKey: .maxBytes) + try container.encodeIfPresent(temperature, forKey: .temperature) + try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) + try container.encodeIfPresent(topP, forKey: .topP) + try container.encodeIfPresent(topK, forKey: .topK) + try container.encodeIfPresent(stopSequences, forKey: .stopSequences) + try container.encodeIfPresent(apiVersion, forKey: .apiVersion) + try container.encodeIfPresent(projectId, forKey: .projectId) + try container.encodeIfPresent(accessToken, forKey: .accessToken) + try container.encodeIfPresent(refreshToken, forKey: .refreshToken) + try container.encodeIfPresent(clientId, forKey: .clientId) + try container.encodeIfPresent(clientSecret, forKey: .clientSecret) + try container.encodeIfPresent(region, forKey: .region) + try container.encodeIfPresent(maxOutputTokens, forKey: .maxOutputTokens) + try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encodeIfPresent(id, forKey: .id) + } +} + diff --git a/Sources/Typesense/Models/NLSearchModelDeleteSchema.swift b/Sources/Typesense/Models/NLSearchModelDeleteSchema.swift new file mode 100644 index 0000000..2439beb --- /dev/null +++ b/Sources/Typesense/Models/NLSearchModelDeleteSchema.swift @@ -0,0 +1,33 @@ +// +// NLSearchModelDeleteSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct NLSearchModelDeleteSchema: Codable { + + /** ID of the deleted NL search model */ + public var id: String + + public init(id: String) { + self.id = id + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + } +} + diff --git a/Sources/Typesense/Models/NLSearchModelSchema.swift b/Sources/Typesense/Models/NLSearchModelSchema.swift new file mode 100644 index 0000000..48f5cdd --- /dev/null +++ b/Sources/Typesense/Models/NLSearchModelSchema.swift @@ -0,0 +1,123 @@ +// +// NLSearchModelSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct NLSearchModelSchema: Codable { + + /** Name of the NL model to use */ + public var modelName: String? + /** API key for the NL model service */ + public var apiKey: String? + /** Custom API URL for the NL model service */ + public var apiUrl: String? + /** Maximum number of bytes to process */ + public var maxBytes: Int? + /** Temperature parameter for the NL model */ + public var temperature: Double? + /** System prompt for the NL model */ + public var systemPrompt: String? + /** Top-p parameter for the NL model (Google-specific) */ + public var topP: Double? + /** Top-k parameter for the NL model (Google-specific) */ + public var topK: Int? + /** Stop sequences for the NL model (Google-specific) */ + public var stopSequences: [String]? + /** API version for the NL model service */ + public var apiVersion: String? + /** Project ID for GCP Vertex AI */ + public var projectId: String? + /** Access token for GCP Vertex AI */ + public var accessToken: String? + /** Refresh token for GCP Vertex AI */ + public var refreshToken: String? + /** Client ID for GCP Vertex AI */ + public var clientId: String? + /** Client secret for GCP Vertex AI */ + public var clientSecret: String? + /** Region for GCP Vertex AI */ + public var region: String? + /** Maximum output tokens for GCP Vertex AI */ + public var maxOutputTokens: Int? + /** Account ID for Cloudflare-specific models */ + public var accountId: String? + /** ID of the NL search model */ + public var id: String + + public init(modelName: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, maxBytes: Int? = nil, temperature: Double? = nil, systemPrompt: String? = nil, topP: Double? = nil, topK: Int? = nil, stopSequences: [String]? = nil, apiVersion: String? = nil, projectId: String? = nil, accessToken: String? = nil, refreshToken: String? = nil, clientId: String? = nil, clientSecret: String? = nil, region: String? = nil, maxOutputTokens: Int? = nil, accountId: String? = nil, id: String) { + self.modelName = modelName + self.apiKey = apiKey + self.apiUrl = apiUrl + self.maxBytes = maxBytes + self.temperature = temperature + self.systemPrompt = systemPrompt + self.topP = topP + self.topK = topK + self.stopSequences = stopSequences + self.apiVersion = apiVersion + self.projectId = projectId + self.accessToken = accessToken + self.refreshToken = refreshToken + self.clientId = clientId + self.clientSecret = clientSecret + self.region = region + self.maxOutputTokens = maxOutputTokens + self.accountId = accountId + self.id = id + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case modelName = "model_name" + case apiKey = "api_key" + case apiUrl = "api_url" + case maxBytes = "max_bytes" + case temperature + case systemPrompt = "system_prompt" + case topP = "top_p" + case topK = "top_k" + case stopSequences = "stop_sequences" + case apiVersion = "api_version" + case projectId = "project_id" + case accessToken = "access_token" + case refreshToken = "refresh_token" + case clientId = "client_id" + case clientSecret = "client_secret" + case region + case maxOutputTokens = "max_output_tokens" + case accountId = "account_id" + case id + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(apiKey, forKey: .apiKey) + try container.encodeIfPresent(apiUrl, forKey: .apiUrl) + try container.encodeIfPresent(maxBytes, forKey: .maxBytes) + try container.encodeIfPresent(temperature, forKey: .temperature) + try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) + try container.encodeIfPresent(topP, forKey: .topP) + try container.encodeIfPresent(topK, forKey: .topK) + try container.encodeIfPresent(stopSequences, forKey: .stopSequences) + try container.encodeIfPresent(apiVersion, forKey: .apiVersion) + try container.encodeIfPresent(projectId, forKey: .projectId) + try container.encodeIfPresent(accessToken, forKey: .accessToken) + try container.encodeIfPresent(refreshToken, forKey: .refreshToken) + try container.encodeIfPresent(clientId, forKey: .clientId) + try container.encodeIfPresent(clientSecret, forKey: .clientSecret) + try container.encodeIfPresent(region, forKey: .region) + try container.encodeIfPresent(maxOutputTokens, forKey: .maxOutputTokens) + try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encode(id, forKey: .id) + } +} + diff --git a/Sources/Typesense/Models/PresetDeleteSchema.swift b/Sources/Typesense/Models/PresetDeleteSchema.swift index 377af2c..aa59c84 100644 --- a/Sources/Typesense/Models/PresetDeleteSchema.swift +++ b/Sources/Typesense/Models/PresetDeleteSchema.swift @@ -1,13 +1,14 @@ // // PresetDeleteSchema.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct PresetDeleteSchema: Codable { @@ -17,5 +18,15 @@ public struct PresetDeleteSchema: Codable { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + } } + diff --git a/Sources/Typesense/Models/PresetSchema.swift b/Sources/Typesense/Models/PresetSchema.swift index 2fbfe00..8d47174 100644 --- a/Sources/Typesense/Models/PresetSchema.swift +++ b/Sources/Typesense/Models/PresetSchema.swift @@ -1,15 +1,36 @@ -import Foundation - +// +// PresetSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct PresetSchema: Codable { + + public var value: PresetUpsertSchemaValue public var name: String - public var value: PresetValue - public init(name: String, value: PresetValue) { - self.name = name + public init(value: PresetUpsertSchemaValue, name: String) { self.value = value + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case value + case name } + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(value, forKey: .value) + try container.encode(name, forKey: .name) + } } + diff --git a/Sources/Typesense/Models/PresetUpsertSchema.swift b/Sources/Typesense/Models/PresetUpsertSchema.swift index 02c9e98..08bdbb1 100644 --- a/Sources/Typesense/Models/PresetUpsertSchema.swift +++ b/Sources/Typesense/Models/PresetUpsertSchema.swift @@ -1,14 +1,32 @@ -import Foundation - +// +// PresetUpsertSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct PresetUpsertSchema: Codable { - public var value: PresetValue + public var value: PresetUpsertSchemaValue - public init(value: PresetValue) { + public init(value: PresetUpsertSchemaValue) { self.value = value } + public enum CodingKeys: String, CodingKey, CaseIterable { + case value + } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(value, forKey: .value) + } } + diff --git a/Sources/Typesense/Models/PresetUpsertSchemaValue.swift b/Sources/Typesense/Models/PresetUpsertSchemaValue.swift new file mode 100644 index 0000000..4e899a8 --- /dev/null +++ b/Sources/Typesense/Models/PresetUpsertSchemaValue.swift @@ -0,0 +1,38 @@ +// +// PresetUpsertSchemaValue.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum PresetUpsertSchemaValue: Codable, JSONEncodable { + case typeMultiSearchSearchesParameter(MultiSearchSearchesParameter) + case typeSearchParameters(SearchParameters) + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .typeMultiSearchSearchesParameter(let value): + try container.encode(value) + case .typeSearchParameters(let value): + try container.encode(value) + } + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if let value = try? container.decode(MultiSearchSearchesParameter.self) { + self = .typeMultiSearchSearchesParameter(value) + } else if let value = try? container.decode(SearchParameters.self) { + self = .typeSearchParameters(value) + } else { + throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of PresetUpsertSchemaValue")) + } + } +} + diff --git a/Sources/Typesense/Models/PresetValue.swift b/Sources/Typesense/Models/PresetValue.swift deleted file mode 100644 index b16bc86..0000000 --- a/Sources/Typesense/Models/PresetValue.swift +++ /dev/null @@ -1,28 +0,0 @@ -public enum PresetValue: Codable { - case multiSearch(MultiSearchSearchesParameter) - case singleCollectionSearch(SearchParameters) - - public init (from decoder: Decoder) throws { - if let multiSearch = try? MultiSearchSearchesParameter(from: decoder) { - self = .multiSearch(multiSearch) - } - else if let singleCollectionSearch = try? SearchParameters(from: decoder) { - self = .singleCollectionSearch(singleCollectionSearch) - } else { - throw DecodingError.dataCorrupted(DecodingError.Context( - codingPath: decoder.codingPath, - debugDescription: "Unable to decode value for preset `value`" - ) - ) - } - } - - public func encode(to encoder: Encoder) throws { - switch self { - case .multiSearch(let multiSearch): - try multiSearch.encode(to: encoder) - case .singleCollectionSearch(let singleCollectionSearch): - try singleCollectionSearch.encode(to: encoder) - } - } -} diff --git a/Sources/Typesense/Models/PresetsRetrieveSchema.swift b/Sources/Typesense/Models/PresetsRetrieveSchema.swift index e36db85..94c7cf2 100644 --- a/Sources/Typesense/Models/PresetsRetrieveSchema.swift +++ b/Sources/Typesense/Models/PresetsRetrieveSchema.swift @@ -1,6 +1,14 @@ -import Foundation - +// +// PresetsRetrieveSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif public struct PresetsRetrieveSchema: Codable { @@ -10,5 +18,15 @@ public struct PresetsRetrieveSchema: Codable { self.presets = presets } + public enum CodingKeys: String, CodingKey, CaseIterable { + case presets + } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(presets, forKey: .presets) + } } + diff --git a/Sources/Typesense/Models/SchemaChangeStatus.swift b/Sources/Typesense/Models/SchemaChangeStatus.swift new file mode 100644 index 0000000..3db6bce --- /dev/null +++ b/Sources/Typesense/Models/SchemaChangeStatus.swift @@ -0,0 +1,43 @@ +// +// SchemaChangeStatus.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SchemaChangeStatus: Codable { + + /** Name of the collection being modified */ + public var collection: String? + /** Number of documents that have been validated */ + public var validatedDocs: Int? + /** Number of documents that have been altered */ + public var alteredDocs: Int? + + public init(collection: String? = nil, validatedDocs: Int? = nil, alteredDocs: Int? = nil) { + self.collection = collection + self.validatedDocs = validatedDocs + self.alteredDocs = alteredDocs + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case collection + case validatedDocs = "validated_docs" + case alteredDocs = "altered_docs" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(collection, forKey: .collection) + try container.encodeIfPresent(validatedDocs, forKey: .validatedDocs) + try container.encodeIfPresent(alteredDocs, forKey: .alteredDocs) + } +} + diff --git a/Sources/Typesense/Models/ScopedKeyParameters.swift b/Sources/Typesense/Models/ScopedKeyParameters.swift deleted file mode 100644 index 0322e63..0000000 --- a/Sources/Typesense/Models/ScopedKeyParameters.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// ScopedKeyParameters.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct ScopedKeyParameters: Codable { - - public var filterBy: String? - public var expiresAt: Decimal? - - public init(filterBy: String? = nil, expiresAt: Decimal? = nil) { - self.filterBy = filterBy - self.expiresAt = expiresAt - } - - public enum CodingKeys: String, CodingKey { - case filterBy = "filter_by" - case expiresAt = "expires_at" - } - -} diff --git a/Sources/Typesense/Models/SearchGroupedHit.swift b/Sources/Typesense/Models/SearchGroupedHit.swift index 5a5b4da..517a73a 100644 --- a/Sources/Typesense/Models/SearchGroupedHit.swift +++ b/Sources/Typesense/Models/SearchGroupedHit.swift @@ -1,14 +1,16 @@ // // SearchGroupedHit.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif -public struct SearchGroupedHit: Decodable { +public struct SearchGroupedHit: Codable { public var found: Int? public var groupKey: [AnyCodable] @@ -21,10 +23,19 @@ public struct SearchGroupedHit: Decodable { self.hits = hits } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case found case groupKey = "group_key" case hits } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(found, forKey: .found) + try container.encode(groupKey, forKey: .groupKey) + try container.encode(hits, forKey: .hits) + } } + diff --git a/Sources/Typesense/Models/SearchHighlight.swift b/Sources/Typesense/Models/SearchHighlight.swift index a5318fd..3b4ff70 100644 --- a/Sources/Typesense/Models/SearchHighlight.swift +++ b/Sources/Typesense/Models/SearchHighlight.swift @@ -1,13 +1,14 @@ // // SearchHighlight.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SearchHighlight: Codable { @@ -22,9 +23,9 @@ public struct SearchHighlight: Codable { public var values: [String]? /** The indices property will be present only for string[] fields and will contain the corresponding indices of the snippets in the search field */ public var indices: [Int]? - public var matchedTokens: StringQuantum? + public var matchedTokens: [AnyCodable]? - public init(field: String? = nil, snippet: String? = nil, snippets: [String]? = nil, value: String? = nil, values: [String]? = nil, indices: [Int]? = nil, matchedTokens: StringQuantum? = nil) { + public init(field: String? = nil, snippet: String? = nil, snippets: [String]? = nil, value: String? = nil, values: [String]? = nil, indices: [Int]? = nil, matchedTokens: [AnyCodable]? = nil) { self.field = field self.snippet = snippet self.snippets = snippets @@ -34,7 +35,7 @@ public struct SearchHighlight: Codable { self.matchedTokens = matchedTokens } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case field case snippet case snippets @@ -44,4 +45,17 @@ public struct SearchHighlight: Codable { case matchedTokens = "matched_tokens" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(field, forKey: .field) + try container.encodeIfPresent(snippet, forKey: .snippet) + try container.encodeIfPresent(snippets, forKey: .snippets) + try container.encodeIfPresent(value, forKey: .value) + try container.encodeIfPresent(values, forKey: .values) + try container.encodeIfPresent(indices, forKey: .indices) + try container.encodeIfPresent(matchedTokens, forKey: .matchedTokens) + } } + diff --git a/Sources/Typesense/Models/SearchOverride.swift b/Sources/Typesense/Models/SearchOverride.swift deleted file mode 100644 index 4f623ef..0000000 --- a/Sources/Typesense/Models/SearchOverride.swift +++ /dev/null @@ -1,71 +0,0 @@ -// -// SearchOverride.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct SearchOverride: Codable { - - public var _id: String - public var rule: SearchOverrideRule - /** List of document `id`s that should be included in the search results with their corresponding `position`s. */ - public var includes: [SearchOverrideInclude]? - /** List of document `id`s that should be excluded from the search results. */ - public var excludes: [SearchOverrideExclude]? - /** A filter by clause that is applied to any search query that matches the override rule. */ - public var filterBy: String? - /** Indicates whether search query tokens that exist in the override's rule should be removed from the search query. */ - public var removeMatchedTokens: Bool? - /** 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. */ - public var metadata: T? - /** A sort by clause that is applied to any search query that matches the override rule. */ - public var sortBy: String? - /** Replaces the current search query with this value, when the search query matches the override rule. */ - public var replaceQuery: String? - /** When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. */ - public var filterCuratedHits: Bool? - /** 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. */ - public var effectiveFromTs: Int? - /** 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. */ - public var effectiveToTs: Int? - /** 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. */ - public var stopProcessing: Bool? - - public init(_id: String, rule: SearchOverrideRule, includes: [SearchOverrideInclude]? = nil, excludes: [SearchOverrideExclude]? = nil, filterBy: String? = nil, removeMatchedTokens: Bool? = nil, metadata: T? = nil, sortBy: String? = nil, replaceQuery: String? = nil, filterCuratedHits: Bool? = nil, effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, stopProcessing: Bool? = nil) { - self._id = _id - self.rule = rule - self.includes = includes - self.excludes = excludes - self.filterBy = filterBy - self.removeMatchedTokens = removeMatchedTokens - self.metadata = metadata - self.sortBy = sortBy - self.replaceQuery = replaceQuery - self.filterCuratedHits = filterCuratedHits - self.effectiveFromTs = effectiveFromTs - self.effectiveToTs = effectiveToTs - self.stopProcessing = stopProcessing - } - - public enum CodingKeys: String, CodingKey { - case _id = "id" - case rule - case includes - case excludes - case filterBy = "filter_by" - case removeMatchedTokens = "remove_matched_tokens" - case metadata - case sortBy = "sort_by" - case replaceQuery = "replace_query" - case filterCuratedHits = "filter_curated_hits" - case effectiveFromTs = "effective_from_ts" - case effectiveToTs = "effective_to_ts" - case stopProcessing = "stop_processing" - } - -} diff --git a/Sources/Typesense/Models/SearchOverrideDeleteResponse.swift b/Sources/Typesense/Models/SearchOverrideDeleteResponse.swift deleted file mode 100644 index c0ec077..0000000 --- a/Sources/Typesense/Models/SearchOverrideDeleteResponse.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// SearchOverrideDeleteResponse.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct SearchOverrideDeleteResponse: Codable { - - /** The id of a deleted override. */ - public var _id: String - - public init(_id: String) { - self._id = _id - } - - public enum CodingKeys: String, CodingKey { - case _id = "id" - } - -} diff --git a/Sources/Typesense/Models/SearchOverrideExclude.swift b/Sources/Typesense/Models/SearchOverrideExclude.swift deleted file mode 100644 index de9cb82..0000000 --- a/Sources/Typesense/Models/SearchOverrideExclude.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// SearchOverrideExclude.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct SearchOverrideExclude: Codable { - - /** document id that should be excluded from the search results. */ - public var _id: String - - public init(_id: String) { - self._id = _id - } - - public enum CodingKeys: String, CodingKey { - case _id = "id" - } - -} diff --git a/Sources/Typesense/Models/SearchOverrideInclude.swift b/Sources/Typesense/Models/SearchOverrideInclude.swift deleted file mode 100644 index 84139c1..0000000 --- a/Sources/Typesense/Models/SearchOverrideInclude.swift +++ /dev/null @@ -1,29 +0,0 @@ -// -// SearchOverrideInclude.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct SearchOverrideInclude: Codable { - - /** document id that should be included */ - public var _id: String - /** position number where document should be included in the search results */ - public var position: Int - - public init(_id: String, position: Int) { - self._id = _id - self.position = position - } - - public enum CodingKeys: String, CodingKey { - case _id = "id" - case position - } - -} diff --git a/Sources/Typesense/Models/SearchOverrideRule.swift b/Sources/Typesense/Models/SearchOverrideRule.swift deleted file mode 100644 index aeab27d..0000000 --- a/Sources/Typesense/Models/SearchOverrideRule.swift +++ /dev/null @@ -1,41 +0,0 @@ -// -// SearchOverrideRule.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct SearchOverrideRule: Codable { - - public enum Match: String, Codable { - case exact = "exact" - case contains = "contains" - } - /** List of tag values to associate with this override rule. */ - public var tags: [String]? - /** Indicates what search queries should be overridden */ - public var 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. */ - public var match: Match? - /** 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). */ - public var filterBy: String? - - public init(tags: [String]? = nil, query: String? = nil, match: Match? = nil, filterBy: String? = nil) { - self.tags = tags - self.query = query - self.match = match - self.filterBy = filterBy - } - - public enum CodingKeys: String, CodingKey { - case tags - case query - case match - case filterBy = "filter_by" - } - -} diff --git a/Sources/Typesense/Models/SearchOverrideSchema.swift b/Sources/Typesense/Models/SearchOverrideSchema.swift deleted file mode 100644 index 0a5c60b..0000000 --- a/Sources/Typesense/Models/SearchOverrideSchema.swift +++ /dev/null @@ -1,68 +0,0 @@ -// -// SearchOverrideSchema.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct SearchOverrideSchema: Codable { - - public var rule: SearchOverrideRule - /** List of document `id`s that should be included in the search results with their corresponding `position`s. */ - public var includes: [SearchOverrideInclude]? - /** List of document `id`s that should be excluded from the search results. */ - public var excludes: [SearchOverrideExclude]? - /** A filter by clause that is applied to any search query that matches the override rule. */ - public var filterBy: String? - /** Indicates whether search query tokens that exist in the override's rule should be removed from the search query. */ - public var removeMatchedTokens: Bool? - /** 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. */ - public var metadata: T? - /** A sort by clause that is applied to any search query that matches the override rule. */ - public var sortBy: String? - /** Replaces the current search query with this value, when the search query matches the override rule. */ - public var replaceQuery: String? - /** When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. */ - public var filterCuratedHits: Bool? - /** 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. */ - public var effectiveFromTs: Int? - /** 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. */ - public var effectiveToTs: Int? - /** 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. */ - public var stopProcessing: Bool? - - public init(rule: SearchOverrideRule, includes: [SearchOverrideInclude]? = nil, excludes: [SearchOverrideExclude]? = nil, filterBy: String? = nil, removeMatchedTokens: Bool? = nil, metadata: T? = nil, sortBy: String? = nil, replaceQuery: String? = nil, filterCuratedHits: Bool? = nil, effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, stopProcessing: Bool? = nil) { - self.rule = rule - self.includes = includes - self.excludes = excludes - self.filterBy = filterBy - self.removeMatchedTokens = removeMatchedTokens - self.metadata = metadata - self.sortBy = sortBy - self.replaceQuery = replaceQuery - self.filterCuratedHits = filterCuratedHits - self.effectiveFromTs = effectiveFromTs - self.effectiveToTs = effectiveToTs - self.stopProcessing = stopProcessing - } - - public enum CodingKeys: String, CodingKey { - case rule - case includes - case excludes - case filterBy = "filter_by" - case removeMatchedTokens = "remove_matched_tokens" - case metadata - case sortBy = "sort_by" - case replaceQuery = "replace_query" - case filterCuratedHits = "filter_curated_hits" - case effectiveFromTs = "effective_from_ts" - case effectiveToTs = "effective_to_ts" - case stopProcessing = "stop_processing" - } - -} diff --git a/Sources/Typesense/Models/SearchOverridesResponse.swift b/Sources/Typesense/Models/SearchOverridesResponse.swift deleted file mode 100644 index 2cfd2e7..0000000 --- a/Sources/Typesense/Models/SearchOverridesResponse.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// SearchOverridesResponse.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct SearchOverridesResponse: Codable { - - public var overrides: [SearchOverride] - - public init(overrides: [SearchOverride]) { - self.overrides = overrides - } - - -} diff --git a/Sources/Typesense/Models/SearchParameters.swift b/Sources/Typesense/Models/SearchParameters.swift index 795f28b..295cba8 100644 --- a/Sources/Typesense/Models/SearchParameters.swift +++ b/Sources/Typesense/Models/SearchParameters.swift @@ -1,41 +1,48 @@ // // SearchParameters.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SearchParameters: Codable { /** 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. */ public var q: String? - /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ + /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ public var queryBy: 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. */ + /** Whether to use natural language processing to parse the query. */ + public var nlQuery: Bool? + /** The ID of the natural language model to use. */ + public var nlModelId: 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. */ public var queryByWeights: 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. */ public var textMatchType: 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. */ public var _prefix: String? - /** 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 */ + /** 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 */ public var _infix: String? - /** 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. */ + /** 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. */ public var maxExtraPrefix: Int? - /** 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. */ + /** 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. */ public var maxExtraSuffix: Int? - /** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */ + /** Filter conditions for refining your open api validator search results. Separate multiple conditions with &&. */ public var filterBy: 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` */ + /** 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*. */ + public var maxFilterByCandidates: Int? + /** 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` */ public var sortBy: String? /** A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. */ public var facetBy: String? /** Maximum number of facet values to be returned. */ public var maxFacetValues: Int? - /** 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\". */ + /** 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\". */ public var facetQuery: String? /** The number of typographical errors (1 or 2) that would be tolerated. Default: 2 */ public var numTypos: String? @@ -47,9 +54,9 @@ public struct SearchParameters: Codable { public var limit: Int? /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ public var offset: Int? - /** 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. */ + /** 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. */ public var groupBy: String? - /** 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 */ public var groupLimit: Int? /** 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 */ public var groupMissingValues: Bool? @@ -61,44 +68,59 @@ public struct SearchParameters: Codable { public var highlightFullFields: String? /** The number of tokens that should surround the highlighted text on each side. Default: 4 */ public var highlightAffixNumTokens: Int? - /** The start tag used for the highlighted snippets. Default: `<mark>` */ + /** The start tag used for the highlighted snippets. Default: `` */ public var highlightStartTag: String? - /** The end tag used for the highlighted snippets. Default: `</mark>` */ + /** The end tag used for the highlighted snippets. Default: `` */ public var highlightEndTag: String? /** Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true */ - public var enableHighlightV1: Bool? + public var enableHighlightV1: Bool? = true + /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ + public var enableAnalytics: Bool? = true /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ public var snippetThreshold: Int? + /** List of synonym set names to associate with this search query */ + public var synonymSets: String? /** 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 */ public var dropTokensThreshold: Int? + public var dropTokensMode: DropTokensMode? /** 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 */ public var typoTokensThreshold: Int? - /** 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. */ + public var enableTyposForAlphaNumericalTokens: 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 */ + public var filterCuratedHits: 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 */ + public var enableSynonyms: Bool? + /** Allow synonym resolution on word prefixes in the query. Default: false */ + public var synonymPrefix: Bool? + /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ + public var synonymNumTypos: Int? + /** 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`. */ public var pinnedHits: 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`. */ + /** 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`. */ public var hiddenHits: String? /** Comma separated list of tags to trigger the curations rules that match the tags. */ public var overrideTags: String? - /** A list of custom fields that must be highlighted even if you don't query for them */ + /** A list of custom fields that must be highlighted even if you don't query for them */ public var highlightFields: 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`. */ + /** 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`. */ public var splitJoinTokens: String? /** 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 */ public var preSegmentedQuery: Bool? /** Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. */ public var preset: String? /** 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 */ - public var enableOverrides: Bool? + public var enableOverrides: Bool? = false /** Set this parameter to true to ensure that an exact match is ranked above the others */ - public var prioritizeExactMatch: Bool? + public var prioritizeExactMatch: Bool? = true /** Control the number of words that Typesense considers for typo and prefix searching. */ public var maxCandidates: Int? /** Make Typesense prioritize documents where the query words appear earlier in the text. */ - public var prioritizeTokenPosition: Bool? + public var prioritizeTokenPosition: Bool? = false /** Make Typesense prioritize documents where the query words appear in more number of fields. */ - public var prioritizeNumMatchingFields: Bool? + public var prioritizeNumMatchingFields: Bool? = true /** Make Typesense disable typos for numerical tokens. */ - public var enableTyposForNumericalTokens: Bool? + public var enableTyposForNumericalTokens: Bool? = true /** 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). */ public var exhaustiveSearch: Bool? /** 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. */ @@ -111,7 +133,7 @@ public struct SearchParameters: Codable { public var minLen1typo: Int? /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ public var minLen2typo: Int? - /** 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. */ public var vectorQuery: String? /** Timeout (in milliseconds) for fetching remote embeddings. */ public var remoteEmbeddingTimeoutMs: Int? @@ -132,9 +154,11 @@ public struct SearchParameters: Codable { /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ public var conversationId: String? - public init(q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, textMatchType: String? = nil, _prefix: String? = nil, _infix: String? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, filterBy: String? = nil, sortBy: String? = nil, facetBy: String? = nil, maxFacetValues: Int? = nil, facetQuery: String? = nil, numTypos: String? = nil, page: Int? = nil, perPage: Int? = nil, limit: Int? = nil, offset: Int? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, includeFields: String? = nil, excludeFields: String? = nil, highlightFullFields: String? = nil, highlightAffixNumTokens: Int? = nil, highlightStartTag: String? = nil, highlightEndTag: String? = nil, enableHighlightV1: Bool? = nil, snippetThreshold: Int? = nil, dropTokensThreshold: Int? = nil, typoTokensThreshold: Int? = nil, pinnedHits: String? = nil, hiddenHits: String? = nil, overrideTags: String? = nil, highlightFields: String? = nil, splitJoinTokens: String? = nil, preSegmentedQuery: Bool? = nil, preset: String? = nil, enableOverrides: Bool? = nil, prioritizeExactMatch: Bool? = nil, maxCandidates: Int? = nil, prioritizeTokenPosition: Bool? = nil, prioritizeNumMatchingFields: Bool? = nil, enableTyposForNumericalTokens: Bool? = nil, exhaustiveSearch: Bool? = nil, searchCutoffMs: Int? = nil, useCache: Bool? = nil, cacheTtl: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, vectorQuery: String? = nil, remoteEmbeddingTimeoutMs: Int? = nil, remoteEmbeddingNumTries: Int? = nil, facetStrategy: String? = nil, stopwords: String? = nil, facetReturnParent: String? = nil, voiceQuery: String? = nil, conversation: Bool? = nil, conversationModelId: String? = nil, conversationId: String? = nil) { + public init(q: String? = nil, queryBy: String? = nil, nlQuery: Bool? = nil, nlModelId: String? = nil, queryByWeights: String? = nil, textMatchType: String? = nil, _prefix: String? = nil, _infix: String? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, filterBy: String? = nil, maxFilterByCandidates: Int? = nil, sortBy: String? = nil, facetBy: String? = nil, maxFacetValues: Int? = nil, facetQuery: String? = nil, numTypos: String? = nil, page: Int? = nil, perPage: Int? = nil, limit: Int? = nil, offset: Int? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, includeFields: String? = nil, excludeFields: String? = nil, highlightFullFields: String? = nil, highlightAffixNumTokens: Int? = nil, highlightStartTag: String? = nil, highlightEndTag: String? = nil, enableHighlightV1: Bool? = true, enableAnalytics: Bool? = true, snippetThreshold: Int? = nil, synonymSets: String? = nil, dropTokensThreshold: Int? = nil, dropTokensMode: DropTokensMode? = nil, typoTokensThreshold: Int? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, filterCuratedHits: Bool? = nil, enableSynonyms: Bool? = nil, synonymPrefix: Bool? = nil, synonymNumTypos: Int? = nil, pinnedHits: String? = nil, hiddenHits: String? = nil, overrideTags: String? = nil, highlightFields: String? = nil, splitJoinTokens: String? = nil, preSegmentedQuery: Bool? = nil, preset: String? = nil, enableOverrides: Bool? = false, prioritizeExactMatch: Bool? = true, maxCandidates: Int? = nil, prioritizeTokenPosition: Bool? = false, prioritizeNumMatchingFields: Bool? = true, enableTyposForNumericalTokens: Bool? = true, exhaustiveSearch: Bool? = nil, searchCutoffMs: Int? = nil, useCache: Bool? = nil, cacheTtl: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, vectorQuery: String? = nil, remoteEmbeddingTimeoutMs: Int? = nil, remoteEmbeddingNumTries: Int? = nil, facetStrategy: String? = nil, stopwords: String? = nil, facetReturnParent: String? = nil, voiceQuery: String? = nil, conversation: Bool? = nil, conversationModelId: String? = nil, conversationId: String? = nil) { self.q = q self.queryBy = queryBy + self.nlQuery = nlQuery + self.nlModelId = nlModelId self.queryByWeights = queryByWeights self.textMatchType = textMatchType self._prefix = _prefix @@ -142,6 +166,7 @@ public struct SearchParameters: Codable { self.maxExtraPrefix = maxExtraPrefix self.maxExtraSuffix = maxExtraSuffix self.filterBy = filterBy + self.maxFilterByCandidates = maxFilterByCandidates self.sortBy = sortBy self.facetBy = facetBy self.maxFacetValues = maxFacetValues @@ -161,9 +186,17 @@ public struct SearchParameters: Codable { self.highlightStartTag = highlightStartTag self.highlightEndTag = highlightEndTag self.enableHighlightV1 = enableHighlightV1 + self.enableAnalytics = enableAnalytics self.snippetThreshold = snippetThreshold + self.synonymSets = synonymSets self.dropTokensThreshold = dropTokensThreshold + self.dropTokensMode = dropTokensMode self.typoTokensThreshold = typoTokensThreshold + self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens + self.filterCuratedHits = filterCuratedHits + self.enableSynonyms = enableSynonyms + self.synonymPrefix = synonymPrefix + self.synonymNumTypos = synonymNumTypos self.pinnedHits = pinnedHits self.hiddenHits = hiddenHits self.overrideTags = overrideTags @@ -195,9 +228,11 @@ public struct SearchParameters: Codable { self.conversationId = conversationId } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case q case queryBy = "query_by" + case nlQuery = "nl_query" + case nlModelId = "nl_model_id" case queryByWeights = "query_by_weights" case textMatchType = "text_match_type" case _prefix = "prefix" @@ -205,6 +240,7 @@ public struct SearchParameters: Codable { case maxExtraPrefix = "max_extra_prefix" case maxExtraSuffix = "max_extra_suffix" case filterBy = "filter_by" + case maxFilterByCandidates = "max_filter_by_candidates" case sortBy = "sort_by" case facetBy = "facet_by" case maxFacetValues = "max_facet_values" @@ -224,9 +260,17 @@ public struct SearchParameters: Codable { case highlightStartTag = "highlight_start_tag" case highlightEndTag = "highlight_end_tag" case enableHighlightV1 = "enable_highlight_v1" + case enableAnalytics = "enable_analytics" case snippetThreshold = "snippet_threshold" + case synonymSets = "synonym_sets" case dropTokensThreshold = "drop_tokens_threshold" + case dropTokensMode = "drop_tokens_mode" case typoTokensThreshold = "typo_tokens_threshold" + case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" + case filterCuratedHits = "filter_curated_hits" + case enableSynonyms = "enable_synonyms" + case synonymPrefix = "synonym_prefix" + case synonymNumTypos = "synonym_num_typos" case pinnedHits = "pinned_hits" case hiddenHits = "hidden_hits" case overrideTags = "override_tags" @@ -258,4 +302,81 @@ public struct SearchParameters: Codable { case conversationId = "conversation_id" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(q, forKey: .q) + try container.encodeIfPresent(queryBy, forKey: .queryBy) + try container.encodeIfPresent(nlQuery, forKey: .nlQuery) + try container.encodeIfPresent(nlModelId, forKey: .nlModelId) + try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) + try container.encodeIfPresent(textMatchType, forKey: .textMatchType) + try container.encodeIfPresent(_prefix, forKey: ._prefix) + try container.encodeIfPresent(_infix, forKey: ._infix) + try container.encodeIfPresent(maxExtraPrefix, forKey: .maxExtraPrefix) + try container.encodeIfPresent(maxExtraSuffix, forKey: .maxExtraSuffix) + try container.encodeIfPresent(filterBy, forKey: .filterBy) + try container.encodeIfPresent(maxFilterByCandidates, forKey: .maxFilterByCandidates) + try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(facetBy, forKey: .facetBy) + try container.encodeIfPresent(maxFacetValues, forKey: .maxFacetValues) + try container.encodeIfPresent(facetQuery, forKey: .facetQuery) + try container.encodeIfPresent(numTypos, forKey: .numTypos) + try container.encodeIfPresent(page, forKey: .page) + try container.encodeIfPresent(perPage, forKey: .perPage) + try container.encodeIfPresent(limit, forKey: .limit) + try container.encodeIfPresent(offset, forKey: .offset) + try container.encodeIfPresent(groupBy, forKey: .groupBy) + try container.encodeIfPresent(groupLimit, forKey: .groupLimit) + try container.encodeIfPresent(groupMissingValues, forKey: .groupMissingValues) + try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(excludeFields, forKey: .excludeFields) + try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) + try container.encodeIfPresent(highlightAffixNumTokens, forKey: .highlightAffixNumTokens) + try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) + try container.encodeIfPresent(highlightEndTag, forKey: .highlightEndTag) + try container.encodeIfPresent(enableHighlightV1, forKey: .enableHighlightV1) + try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) + try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) + try container.encodeIfPresent(synonymSets, forKey: .synonymSets) + try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) + try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) + try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) + try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) + try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) + try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) + try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) + try container.encodeIfPresent(pinnedHits, forKey: .pinnedHits) + try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) + try container.encodeIfPresent(overrideTags, forKey: .overrideTags) + try container.encodeIfPresent(highlightFields, forKey: .highlightFields) + try container.encodeIfPresent(splitJoinTokens, forKey: .splitJoinTokens) + try container.encodeIfPresent(preSegmentedQuery, forKey: .preSegmentedQuery) + try container.encodeIfPresent(preset, forKey: .preset) + try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) + try container.encodeIfPresent(prioritizeExactMatch, forKey: .prioritizeExactMatch) + try container.encodeIfPresent(maxCandidates, forKey: .maxCandidates) + try container.encodeIfPresent(prioritizeTokenPosition, forKey: .prioritizeTokenPosition) + try container.encodeIfPresent(prioritizeNumMatchingFields, forKey: .prioritizeNumMatchingFields) + try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) + try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) + try container.encodeIfPresent(searchCutoffMs, forKey: .searchCutoffMs) + try container.encodeIfPresent(useCache, forKey: .useCache) + try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) + try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) + try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) + try container.encodeIfPresent(vectorQuery, forKey: .vectorQuery) + try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) + try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) + try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) + try container.encodeIfPresent(stopwords, forKey: .stopwords) + try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) + try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) + try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) + try container.encodeIfPresent(conversationId, forKey: .conversationId) + } } + diff --git a/Sources/Typesense/Models/SearchRequestParams.swift b/Sources/Typesense/Models/SearchRequestParams.swift new file mode 100644 index 0000000..11e81b5 --- /dev/null +++ b/Sources/Typesense/Models/SearchRequestParams.swift @@ -0,0 +1,44 @@ +// +// SearchRequestParams.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SearchRequestParams: Codable { + + public var collectionName: String + public var q: String + public var perPage: Int + public var voiceQuery: SearchRequestParamsVoiceQuery? + + public init(collectionName: String, q: String, perPage: Int, voiceQuery: SearchRequestParamsVoiceQuery? = nil) { + self.collectionName = collectionName + self.q = q + self.perPage = perPage + self.voiceQuery = voiceQuery + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case collectionName = "collection_name" + case q + case perPage = "per_page" + case voiceQuery = "voice_query" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(collectionName, forKey: .collectionName) + try container.encode(q, forKey: .q) + try container.encode(perPage, forKey: .perPage) + try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) + } +} + diff --git a/Sources/Typesense/Models/SearchRequestParamsVoiceQuery.swift b/Sources/Typesense/Models/SearchRequestParamsVoiceQuery.swift new file mode 100644 index 0000000..be6044e --- /dev/null +++ b/Sources/Typesense/Models/SearchRequestParamsVoiceQuery.swift @@ -0,0 +1,32 @@ +// +// SearchRequestParamsVoiceQuery.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SearchRequestParamsVoiceQuery: Codable { + + public var transcribedQuery: String? + + public init(transcribedQuery: String? = nil) { + self.transcribedQuery = transcribedQuery + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case transcribedQuery = "transcribed_query" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(transcribedQuery, forKey: .transcribedQuery) + } +} + diff --git a/Sources/Typesense/Models/SearchResult.swift b/Sources/Typesense/Models/SearchResult.swift index 232e85a..84d5de9 100644 --- a/Sources/Typesense/Models/SearchResult.swift +++ b/Sources/Typesense/Models/SearchResult.swift @@ -1,19 +1,21 @@ // // SearchResult.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif - - -public struct SearchResult: Decodable { +public struct SearchResult: Codable { public var facetCounts: [FacetCounts]? /** The number of documents found */ public var found: Int? + public var foundDocs: Int? /** The number of milliseconds the search took */ public var searchTimeMs: Int? /** The total number of documents in the collection */ @@ -25,12 +27,17 @@ public struct SearchResult: Decodable { public var groupedHits: [SearchGroupedHit]? /** The documents that matched the search query */ public var hits: [SearchResultHit]? - public var requestParams: SearchResultRequestParams? + public var requestParams: SearchRequestParams? public var conversation: SearchResultConversation? + /** Returned only for union query response. */ + public var unionRequestParams: [SearchRequestParams]? + /** Custom JSON object that can be returned in the search response */ + public var metadata: [String: AnyCodable]? - public init(facetCounts: [FacetCounts]? = nil, found: Int? = nil, searchTimeMs: Int? = nil, outOf: Int? = nil, searchCutoff: Bool? = nil, page: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, requestParams: SearchResultRequestParams? = nil, conversation: SearchResultConversation? = nil) { + public init(facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, searchTimeMs: Int? = nil, outOf: Int? = nil, searchCutoff: Bool? = nil, page: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, requestParams: SearchRequestParams? = nil, conversation: SearchResultConversation? = nil, unionRequestParams: [SearchRequestParams]? = nil, metadata: [String: AnyCodable]? = nil) { self.facetCounts = facetCounts self.found = found + self.foundDocs = foundDocs self.searchTimeMs = searchTimeMs self.outOf = outOf self.searchCutoff = searchCutoff @@ -39,11 +46,14 @@ public struct SearchResult: Decodable { self.hits = hits self.requestParams = requestParams self.conversation = conversation + self.unionRequestParams = unionRequestParams + self.metadata = metadata } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case facetCounts = "facet_counts" case found + case foundDocs = "found_docs" case searchTimeMs = "search_time_ms" case outOf = "out_of" case searchCutoff = "search_cutoff" @@ -52,6 +62,27 @@ public struct SearchResult: Decodable { case hits case requestParams = "request_params" case conversation + case unionRequestParams = "union_request_params" + case metadata } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(facetCounts, forKey: .facetCounts) + try container.encodeIfPresent(found, forKey: .found) + try container.encodeIfPresent(foundDocs, forKey: .foundDocs) + try container.encodeIfPresent(searchTimeMs, forKey: .searchTimeMs) + try container.encodeIfPresent(outOf, forKey: .outOf) + try container.encodeIfPresent(searchCutoff, forKey: .searchCutoff) + try container.encodeIfPresent(page, forKey: .page) + try container.encodeIfPresent(groupedHits, forKey: .groupedHits) + try container.encodeIfPresent(hits, forKey: .hits) + try container.encodeIfPresent(requestParams, forKey: .requestParams) + try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encodeIfPresent(unionRequestParams, forKey: .unionRequestParams) + try container.encodeIfPresent(metadata, forKey: .metadata) + } } + diff --git a/Sources/Typesense/Models/SearchResultConversation.swift b/Sources/Typesense/Models/SearchResultConversation.swift index 6df51b7..2e905d9 100644 --- a/Sources/Typesense/Models/SearchResultConversation.swift +++ b/Sources/Typesense/Models/SearchResultConversation.swift @@ -1,33 +1,44 @@ // // SearchResultConversation.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SearchResultConversation: Codable { public var answer: String - public var conversationHistory: [[String: String]] + public var conversationHistory: [AnyCodable] public var conversationId: String public var query: String - public init(answer: String, conversationHistory: [[String: String]], conversationId: String, query: String) { + public init(answer: String, conversationHistory: [AnyCodable], conversationId: String, query: String) { self.answer = answer self.conversationHistory = conversationHistory self.conversationId = conversationId self.query = query } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case answer case conversationHistory = "conversation_history" case conversationId = "conversation_id" case query } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(answer, forKey: .answer) + try container.encode(conversationHistory, forKey: .conversationHistory) + try container.encode(conversationId, forKey: .conversationId) + try container.encode(query, forKey: .query) + } } + diff --git a/Sources/Typesense/Models/SearchResultHit.swift b/Sources/Typesense/Models/SearchResultHit.swift index 8c8a529..01a9d57 100644 --- a/Sources/Typesense/Models/SearchResultHit.swift +++ b/Sources/Typesense/Models/SearchResultHit.swift @@ -1,49 +1,70 @@ // // SearchResultHit.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif - - -public struct SearchResultHit: Decodable { +public struct SearchResultHit: Codable { /** (Deprecated) Contains highlighted portions of the search fields */ public var highlights: [SearchHighlight]? - public var document: T? + /** Highlighted version of the matching document */ + public var highlight: [String: AnyCodable]? + /** Can be any key-value pair */ + public var document: [String: AnyCodable]? public var textMatch: Int64? - public var geoDistanceMeters: [String:Int]? - /** Distance between the query vector and matching document's vector value */ + public var textMatchInfo: SearchResultHitTextMatchInfo? + /** Can be any key-value pair */ + public var geoDistanceMeters: [String: Int]? + /** Distance between the query vector and matching document's vector value */ public var vectorDistance: Float? + public var hybridSearchInfo: SearchResultHitHybridSearchInfo? + /** Returned only for union query response. Indicates the index of the query which this document matched to. */ + public var searchIndex: Int? - public init(highlights: [SearchHighlight]? = nil, document: T? = nil, textMatch: Int64? = nil, geoDistanceMeters: [String:Int]? = nil, vectorDistance: Float? = nil) { + public init(highlights: [SearchHighlight]? = nil, highlight: [String: AnyCodable]? = nil, document: [String: AnyCodable]? = nil, textMatch: Int64? = nil, textMatchInfo: SearchResultHitTextMatchInfo? = nil, geoDistanceMeters: [String: Int]? = nil, vectorDistance: Float? = nil, hybridSearchInfo: SearchResultHitHybridSearchInfo? = nil, searchIndex: Int? = nil) { self.highlights = highlights -// self.highlightData = highlight + self.highlight = highlight self.document = document self.textMatch = textMatch + self.textMatchInfo = textMatchInfo self.geoDistanceMeters = geoDistanceMeters self.vectorDistance = vectorDistance - } - - public init(from decoder: Decoder) throws { - let container: KeyedDecodingContainer.CodingKeys> = try decoder.container(keyedBy: SearchResultHit.CodingKeys.self) - self.highlights = try container.decodeIfPresent([SearchHighlight].self, forKey: SearchResultHit.CodingKeys.highlights) - self.document = try container.decodeIfPresent(T.self, forKey: SearchResultHit.CodingKeys.document) - self.textMatch = try container.decodeIfPresent(Int64.self, forKey: SearchResultHit.CodingKeys.textMatch) - self.geoDistanceMeters = try container.decodeIfPresent([String : Int].self, forKey: SearchResultHit.CodingKeys.geoDistanceMeters) - self.vectorDistance = try container.decodeIfPresent(Float.self, forKey: SearchResultHit.CodingKeys.vectorDistance) + self.hybridSearchInfo = hybridSearchInfo + self.searchIndex = searchIndex } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case highlights case highlight case document case textMatch = "text_match" + case textMatchInfo = "text_match_info" case geoDistanceMeters = "geo_distance_meters" case vectorDistance = "vector_distance" + case hybridSearchInfo = "hybrid_search_info" + case searchIndex = "search_index" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(highlights, forKey: .highlights) + try container.encodeIfPresent(highlight, forKey: .highlight) + try container.encodeIfPresent(document, forKey: .document) + try container.encodeIfPresent(textMatch, forKey: .textMatch) + try container.encodeIfPresent(textMatchInfo, forKey: .textMatchInfo) + try container.encodeIfPresent(geoDistanceMeters, forKey: .geoDistanceMeters) + try container.encodeIfPresent(vectorDistance, forKey: .vectorDistance) + try container.encodeIfPresent(hybridSearchInfo, forKey: .hybridSearchInfo) + try container.encodeIfPresent(searchIndex, forKey: .searchIndex) + } } + diff --git a/Sources/Typesense/Models/SearchResultHitHybridSearchInfo.swift b/Sources/Typesense/Models/SearchResultHitHybridSearchInfo.swift new file mode 100644 index 0000000..51d5219 --- /dev/null +++ b/Sources/Typesense/Models/SearchResultHitHybridSearchInfo.swift @@ -0,0 +1,34 @@ +// +// SearchResultHitHybridSearchInfo.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Information about hybrid search scoring */ +public struct SearchResultHitHybridSearchInfo: Codable { + + /** Combined score from rank fusion of text and vector search */ + public var rankFusionScore: Float? + + public init(rankFusionScore: Float? = nil) { + self.rankFusionScore = rankFusionScore + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case rankFusionScore = "rank_fusion_score" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(rankFusionScore, forKey: .rankFusionScore) + } +} + diff --git a/Sources/Typesense/Models/SearchResultHitTextMatchInfo.swift b/Sources/Typesense/Models/SearchResultHitTextMatchInfo.swift new file mode 100644 index 0000000..a42121e --- /dev/null +++ b/Sources/Typesense/Models/SearchResultHitTextMatchInfo.swift @@ -0,0 +1,56 @@ +// +// SearchResultHitTextMatchInfo.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SearchResultHitTextMatchInfo: Codable { + + public var bestFieldScore: String? + public var bestFieldWeight: Int? + public var fieldsMatched: Int? + public var numTokensDropped: Int64? + public var score: String? + public var tokensMatched: Int? + public var typoPrefixScore: Int? + + public init(bestFieldScore: String? = nil, bestFieldWeight: Int? = nil, fieldsMatched: Int? = nil, numTokensDropped: Int64? = nil, score: String? = nil, tokensMatched: Int? = nil, typoPrefixScore: Int? = nil) { + self.bestFieldScore = bestFieldScore + self.bestFieldWeight = bestFieldWeight + self.fieldsMatched = fieldsMatched + self.numTokensDropped = numTokensDropped + self.score = score + self.tokensMatched = tokensMatched + self.typoPrefixScore = typoPrefixScore + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case bestFieldScore = "best_field_score" + case bestFieldWeight = "best_field_weight" + case fieldsMatched = "fields_matched" + case numTokensDropped = "num_tokens_dropped" + case score + case tokensMatched = "tokens_matched" + case typoPrefixScore = "typo_prefix_score" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bestFieldScore, forKey: .bestFieldScore) + try container.encodeIfPresent(bestFieldWeight, forKey: .bestFieldWeight) + try container.encodeIfPresent(fieldsMatched, forKey: .fieldsMatched) + try container.encodeIfPresent(numTokensDropped, forKey: .numTokensDropped) + try container.encodeIfPresent(score, forKey: .score) + try container.encodeIfPresent(tokensMatched, forKey: .tokensMatched) + try container.encodeIfPresent(typoPrefixScore, forKey: .typoPrefixScore) + } +} + diff --git a/Sources/Typesense/Models/SearchResultRequestParams.swift b/Sources/Typesense/Models/SearchResultRequestParams.swift deleted file mode 100644 index 8a666a7..0000000 --- a/Sources/Typesense/Models/SearchResultRequestParams.swift +++ /dev/null @@ -1,33 +0,0 @@ -// -// SearchResultRequestParams.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct SearchResultRequestParams: Codable { - - public var collectionName: String - public var q: String - public var perPage: Int - public var voiceQuery: SearchResultRequestParamsVoiceQuery? - - public init(collectionName: String, q: String, perPage: Int, voiceQuery: SearchResultRequestParamsVoiceQuery? = nil) { - self.collectionName = collectionName - self.q = q - self.perPage = perPage - self.voiceQuery = voiceQuery - } - - public enum CodingKeys: String, CodingKey { - case collectionName = "collection_name" - case q - case perPage = "per_page" - case voiceQuery = "voice_query" - } - -} diff --git a/Sources/Typesense/Models/SearchResultRequestParamsVoiceQuery.swift b/Sources/Typesense/Models/SearchResultRequestParamsVoiceQuery.swift deleted file mode 100644 index 1a6ba50..0000000 --- a/Sources/Typesense/Models/SearchResultRequestParamsVoiceQuery.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// SearchResultRequestParamsVoiceQuery.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct SearchResultRequestParamsVoiceQuery: Codable { - - public var transcribedQuery: String? - - public init(transcribedQuery: String? = nil) { - self.transcribedQuery = transcribedQuery - } - - public enum CodingKeys: String, CodingKey { - case transcribedQuery = "transcribed_query" - } - -} diff --git a/Sources/Typesense/Models/SearchSynonym.swift b/Sources/Typesense/Models/SearchSynonym.swift index 6d22000..4cd1d3d 100644 --- a/Sources/Typesense/Models/SearchSynonym.swift +++ b/Sources/Typesense/Models/SearchSynonym.swift @@ -1,40 +1,52 @@ // // SearchSynonym.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SearchSynonym: Codable { - /** For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. */ + /** For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. */ public var root: String? /** Array of words that should be considered as synonyms. */ public var synonyms: [String] - public var _id: String /** Locale for the synonym, leave blank to use the standard tokenizer. */ public var locale: String? /** By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. */ public var symbolsToIndex: [String]? + public var id: String - public init(root: String? = nil, synonyms: [String], _id: String, locale: String? = nil, symbolsToIndex: [String]? = nil) { + public init(root: String? = nil, synonyms: [String], locale: String? = nil, symbolsToIndex: [String]? = nil, id: String) { self.root = root self.synonyms = synonyms - self._id = _id self.locale = locale self.symbolsToIndex = symbolsToIndex + self.id = id } - public enum CodingKeys: String, CodingKey { - case _id = "id" + public enum CodingKeys: String, CodingKey, CaseIterable { case root case synonyms case locale case symbolsToIndex = "symbols_to_index" + case id } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(root, forKey: .root) + try container.encode(synonyms, forKey: .synonyms) + try container.encodeIfPresent(locale, forKey: .locale) + try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) + try container.encode(id, forKey: .id) + } } + diff --git a/Sources/Typesense/Models/SearchSynonymDeleteResponse.swift b/Sources/Typesense/Models/SearchSynonymDeleteResponse.swift new file mode 100644 index 0000000..3dd313a --- /dev/null +++ b/Sources/Typesense/Models/SearchSynonymDeleteResponse.swift @@ -0,0 +1,33 @@ +// +// SearchSynonymDeleteResponse.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SearchSynonymDeleteResponse: Codable { + + /** The id of the synonym that was deleted */ + public var id: String + + public init(id: String) { + self.id = id + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + } +} + diff --git a/Sources/Typesense/Models/SearchSynonymSchema.swift b/Sources/Typesense/Models/SearchSynonymSchema.swift index b88a312..fdcbfb0 100644 --- a/Sources/Typesense/Models/SearchSynonymSchema.swift +++ b/Sources/Typesense/Models/SearchSynonymSchema.swift @@ -1,17 +1,18 @@ // // SearchSynonymSchema.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SearchSynonymSchema: Codable { - /** For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. */ + /** For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. */ public var root: String? /** Array of words that should be considered as synonyms. */ public var synonyms: [String] @@ -27,11 +28,21 @@ public struct SearchSynonymSchema: Codable { self.symbolsToIndex = symbolsToIndex } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case root case synonyms case locale case symbolsToIndex = "symbols_to_index" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(root, forKey: .root) + try container.encode(synonyms, forKey: .synonyms) + try container.encodeIfPresent(locale, forKey: .locale) + try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) + } } + diff --git a/Sources/Typesense/Models/SearchSynonymsResponse.swift b/Sources/Typesense/Models/SearchSynonymsResponse.swift index 0eeebb4..e665857 100644 --- a/Sources/Typesense/Models/SearchSynonymsResponse.swift +++ b/Sources/Typesense/Models/SearchSynonymsResponse.swift @@ -1,13 +1,14 @@ // // SearchSynonymsResponse.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SearchSynonymsResponse: Codable { @@ -17,5 +18,15 @@ public struct SearchSynonymsResponse: Codable { self.synonyms = synonyms } + public enum CodingKeys: String, CodingKey, CaseIterable { + case synonyms + } + + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(synonyms, forKey: .synonyms) + } } + diff --git a/Sources/Typesense/Models/SnapshotParameters.swift b/Sources/Typesense/Models/SnapshotParameters.swift deleted file mode 100644 index 2f147b0..0000000 --- a/Sources/Typesense/Models/SnapshotParameters.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// SnapshotParameters.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct SnapshotParameters: Codable { - - public var snapshotPath: String? - - public init(snapshotPath: String? = nil) { - self.snapshotPath = snapshotPath - } - - public enum CodingKeys: String, CodingKey { - case snapshotPath = "snapshot_path" - } - -} diff --git a/Sources/Typesense/Models/StemmingDictionary.swift b/Sources/Typesense/Models/StemmingDictionary.swift new file mode 100644 index 0000000..7902ea8 --- /dev/null +++ b/Sources/Typesense/Models/StemmingDictionary.swift @@ -0,0 +1,38 @@ +// +// StemmingDictionary.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct StemmingDictionary: Codable { + + /** Unique identifier for the dictionary */ + public var id: String + /** List of word mappings in the dictionary */ + public var words: [StemmingDictionaryWordsInner] + + public init(id: String, words: [StemmingDictionaryWordsInner]) { + self.id = id + self.words = words + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case words + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(words, forKey: .words) + } +} + diff --git a/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift b/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift new file mode 100644 index 0000000..69bb4e8 --- /dev/null +++ b/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift @@ -0,0 +1,38 @@ +// +// StemmingDictionaryWordsInner.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct StemmingDictionaryWordsInner: Codable { + + /** The word form to be stemmed */ + public var word: String + /** The root form of the word */ + public var root: String + + public init(word: String, root: String) { + self.word = word + self.root = root + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case word + case root + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(word, forKey: .word) + try container.encode(root, forKey: .root) + } +} + diff --git a/Sources/Typesense/Models/StopwordsSetDeleteSchema.swift b/Sources/Typesense/Models/StopwordsSetDeleteSchema.swift deleted file mode 100644 index 0fb3f91..0000000 --- a/Sources/Typesense/Models/StopwordsSetDeleteSchema.swift +++ /dev/null @@ -1,16 +0,0 @@ -import Foundation - - - -public struct StopwordsSetDeleteSchema: Codable { - public var _id: String - - public init(_id: String) { - self._id = _id - } - - public enum CodingKeys: String, CodingKey { - case _id = "id" - } - -} diff --git a/Sources/Typesense/Models/StopwordsSetRetrieveSchema.swift b/Sources/Typesense/Models/StopwordsSetRetrieveSchema.swift index fd37ac7..c5e2b9a 100644 --- a/Sources/Typesense/Models/StopwordsSetRetrieveSchema.swift +++ b/Sources/Typesense/Models/StopwordsSetRetrieveSchema.swift @@ -1,13 +1,14 @@ // // StopwordsSetRetrieveSchema.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct StopwordsSetRetrieveSchema: Codable { @@ -17,5 +18,15 @@ public struct StopwordsSetRetrieveSchema: Codable { self.stopwords = stopwords } + public enum CodingKeys: String, CodingKey, CaseIterable { + case stopwords + } + + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stopwords, forKey: .stopwords) + } } + diff --git a/Sources/Typesense/Models/StopwordsSetSchema.swift b/Sources/Typesense/Models/StopwordsSetSchema.swift index a452fc1..2b45970 100644 --- a/Sources/Typesense/Models/StopwordsSetSchema.swift +++ b/Sources/Typesense/Models/StopwordsSetSchema.swift @@ -1,30 +1,40 @@ // // StopwordsSetSchema.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct StopwordsSetSchema: Codable { - public var _id: String + public var id: String public var stopwords: [String] public var locale: String? - public init(_id: String, stopwords: [String], locale: String? = nil) { - self._id = _id + public init(id: String, stopwords: [String], locale: String? = nil) { + self.id = id self.stopwords = stopwords self.locale = locale } - public enum CodingKeys: String, CodingKey { - case _id = "id" + public enum CodingKeys: String, CodingKey, CaseIterable { + case id case stopwords case locale } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(stopwords, forKey: .stopwords) + try container.encodeIfPresent(locale, forKey: .locale) + } } + diff --git a/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift b/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift index 0c6eaf2..9112fd2 100644 --- a/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift +++ b/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift @@ -1,13 +1,14 @@ // // StopwordsSetUpsertSchema.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct StopwordsSetUpsertSchema: Codable { @@ -19,5 +20,17 @@ public struct StopwordsSetUpsertSchema: Codable { self.locale = locale } + public enum CodingKeys: String, CodingKey, CaseIterable { + case stopwords + case locale + } + + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stopwords, forKey: .stopwords) + try container.encodeIfPresent(locale, forKey: .locale) + } } + diff --git a/Sources/Typesense/Models/StopwordsSetsRetrieveAllSchema.swift b/Sources/Typesense/Models/StopwordsSetsRetrieveAllSchema.swift index 52d83cd..5c28e17 100644 --- a/Sources/Typesense/Models/StopwordsSetsRetrieveAllSchema.swift +++ b/Sources/Typesense/Models/StopwordsSetsRetrieveAllSchema.swift @@ -1,13 +1,14 @@ // // StopwordsSetsRetrieveAllSchema.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct StopwordsSetsRetrieveAllSchema: Codable { @@ -17,5 +18,15 @@ public struct StopwordsSetsRetrieveAllSchema: Codable { self.stopwords = stopwords } + public enum CodingKeys: String, CodingKey, CaseIterable { + case stopwords + } + + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stopwords, forKey: .stopwords) + } } + diff --git a/Sources/Typesense/Models/SuccessStatus.swift b/Sources/Typesense/Models/SuccessStatus.swift index dc647b2..832d7ad 100644 --- a/Sources/Typesense/Models/SuccessStatus.swift +++ b/Sources/Typesense/Models/SuccessStatus.swift @@ -1,13 +1,14 @@ // // SuccessStatus.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - - +#if canImport(AnyCodable) +import AnyCodable +#endif public struct SuccessStatus: Codable { @@ -17,5 +18,15 @@ public struct SuccessStatus: Codable { self.success = success } + public enum CodingKeys: String, CodingKey, CaseIterable { + case success + } + + // Encodable protocol methods + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(success, forKey: .success) + } } + diff --git a/Sources/Typesense/Models/SynonymItemDeleteSchema.swift b/Sources/Typesense/Models/SynonymItemDeleteSchema.swift new file mode 100644 index 0000000..45323f4 --- /dev/null +++ b/Sources/Typesense/Models/SynonymItemDeleteSchema.swift @@ -0,0 +1,33 @@ +// +// SynonymItemDeleteSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SynonymItemDeleteSchema: Codable { + + /** ID of the deleted synonym item */ + public var id: String + + public init(id: String) { + self.id = id + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + } +} + diff --git a/Sources/Typesense/Models/SynonymItemSchema.swift b/Sources/Typesense/Models/SynonymItemSchema.swift new file mode 100644 index 0000000..7c00f6c --- /dev/null +++ b/Sources/Typesense/Models/SynonymItemSchema.swift @@ -0,0 +1,53 @@ +// +// SynonymItemSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SynonymItemSchema: Codable { + + /** Unique identifier for the synonym item */ + public var id: String + /** Array of words that should be considered as synonyms */ + public var synonyms: [String] + /** For 1-way synonyms, indicates the root word that words in the synonyms parameter map to */ + public var root: String? + /** Locale for the synonym, leave blank to use the standard tokenizer */ + public var locale: String? + /** By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is */ + public var symbolsToIndex: [String]? + + public init(id: String, synonyms: [String], root: String? = nil, locale: String? = nil, symbolsToIndex: [String]? = nil) { + self.id = id + self.synonyms = synonyms + self.root = root + self.locale = locale + self.symbolsToIndex = symbolsToIndex + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case synonyms + case root + case locale + case symbolsToIndex = "symbols_to_index" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(synonyms, forKey: .synonyms) + try container.encodeIfPresent(root, forKey: .root) + try container.encodeIfPresent(locale, forKey: .locale) + try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) + } +} + diff --git a/Sources/Typesense/Models/SynonymSetCreateSchema.swift b/Sources/Typesense/Models/SynonymSetCreateSchema.swift new file mode 100644 index 0000000..9656b05 --- /dev/null +++ b/Sources/Typesense/Models/SynonymSetCreateSchema.swift @@ -0,0 +1,33 @@ +// +// SynonymSetCreateSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SynonymSetCreateSchema: Codable { + + /** Array of synonym items */ + public var items: [SynonymItemSchema] + + public init(items: [SynonymItemSchema]) { + self.items = items + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case items + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(items, forKey: .items) + } +} + diff --git a/Sources/Typesense/Models/SynonymSetDeleteSchema.swift b/Sources/Typesense/Models/SynonymSetDeleteSchema.swift new file mode 100644 index 0000000..db3b07c --- /dev/null +++ b/Sources/Typesense/Models/SynonymSetDeleteSchema.swift @@ -0,0 +1,33 @@ +// +// SynonymSetDeleteSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SynonymSetDeleteSchema: Codable { + + /** Name of the deleted synonym set */ + public var name: String + + public init(name: String) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + } +} + diff --git a/Sources/Typesense/Models/SynonymSetSchema.swift b/Sources/Typesense/Models/SynonymSetSchema.swift new file mode 100644 index 0000000..d295741 --- /dev/null +++ b/Sources/Typesense/Models/SynonymSetSchema.swift @@ -0,0 +1,38 @@ +// +// SynonymSetSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SynonymSetSchema: Codable { + + /** Array of synonym items */ + public var items: [SynonymItemSchema] + /** Name of the synonym set */ + public var name: String + + public init(items: [SynonymItemSchema], name: String) { + self.items = items + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case items + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(items, forKey: .items) + try container.encode(name, forKey: .name) + } +} + diff --git a/Sources/Typesense/Models/SynonymSetsRetrieveSchema.swift b/Sources/Typesense/Models/SynonymSetsRetrieveSchema.swift new file mode 100644 index 0000000..2cef89e --- /dev/null +++ b/Sources/Typesense/Models/SynonymSetsRetrieveSchema.swift @@ -0,0 +1,33 @@ +// +// SynonymSetsRetrieveSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SynonymSetsRetrieveSchema: Codable { + + /** Array of synonym sets */ + public var synonymSets: [SynonymSetSchema] + + public init(synonymSets: [SynonymSetSchema]) { + self.synonymSets = synonymSets + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case synonymSets = "synonym_sets" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(synonymSets, forKey: .synonymSets) + } +} + diff --git a/Sources/Typesense/Models/ToggleSlowRequestLogRequest.swift b/Sources/Typesense/Models/ToggleSlowRequestLogRequest.swift new file mode 100644 index 0000000..e5a6090 --- /dev/null +++ b/Sources/Typesense/Models/ToggleSlowRequestLogRequest.swift @@ -0,0 +1,32 @@ +// +// ToggleSlowRequestLogRequest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ToggleSlowRequestLogRequest: Codable { + + public var logSlowRequestsTimeMs: Int + + public init(logSlowRequestsTimeMs: Int) { + self.logSlowRequestsTimeMs = logSlowRequestsTimeMs + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case logSlowRequestsTimeMs = "log-slow-requests-time-ms" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(logSlowRequestsTimeMs, forKey: .logSlowRequestsTimeMs) + } +} + diff --git a/Sources/Typesense/Models/UpdateByFilterResponse.swift b/Sources/Typesense/Models/UpdateByFilterResponse.swift deleted file mode 100644 index d0e7639..0000000 --- a/Sources/Typesense/Models/UpdateByFilterResponse.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// InlineResponse2001.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct UpdateByFilterResponse: Codable { - - /** The number of documents that have been updated */ - public var numUpdated: Int - - public init(numUpdated: Int) { - self.numUpdated = numUpdated - } - - public enum CodingKeys: String, CodingKey { - case numUpdated = "num_updated" - } - -} diff --git a/Sources/Typesense/Models/UpdateDocuments200Response.swift b/Sources/Typesense/Models/UpdateDocuments200Response.swift new file mode 100644 index 0000000..f388aed --- /dev/null +++ b/Sources/Typesense/Models/UpdateDocuments200Response.swift @@ -0,0 +1,33 @@ +// +// UpdateDocuments200Response.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct UpdateDocuments200Response: Codable { + + /** The number of documents that have been updated */ + public var numUpdated: Int + + public init(numUpdated: Int) { + self.numUpdated = numUpdated + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case numUpdated = "num_updated" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(numUpdated, forKey: .numUpdated) + } +} + diff --git a/Sources/Typesense/Models/UpdateDocumentsByFilterParameters.swift b/Sources/Typesense/Models/UpdateDocumentsByFilterParameters.swift deleted file mode 100644 index 2a0e1d8..0000000 --- a/Sources/Typesense/Models/UpdateDocumentsByFilterParameters.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// UpdateDocumentsParameters.swift -// -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen -// - -import Foundation - - - -public struct UpdateDocumentsByFilterParameters: Codable { - - public var filterBy: String? - - public init(filterBy: String? = nil) { - self.filterBy = filterBy - } - - public enum CodingKeys: String, CodingKey { - case filterBy = "filter_by" - } - -} diff --git a/Sources/Typesense/Models/UpdateDocumentsUpdateDocumentsParametersParameter.swift b/Sources/Typesense/Models/UpdateDocumentsUpdateDocumentsParametersParameter.swift new file mode 100644 index 0000000..9e65bea --- /dev/null +++ b/Sources/Typesense/Models/UpdateDocumentsUpdateDocumentsParametersParameter.swift @@ -0,0 +1,32 @@ +// +// UpdateDocumentsUpdateDocumentsParametersParameter.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct UpdateDocumentsUpdateDocumentsParametersParameter: Codable { + + public var filterBy: String? + + public init(filterBy: String? = nil) { + self.filterBy = filterBy + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case filterBy = "filter_by" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(filterBy, forKey: .filterBy) + } +} + diff --git a/Sources/Typesense/Models/VoiceQueryModelCollectionConfig.swift b/Sources/Typesense/Models/VoiceQueryModelCollectionConfig.swift index fa2f97e..963e6d5 100644 --- a/Sources/Typesense/Models/VoiceQueryModelCollectionConfig.swift +++ b/Sources/Typesense/Models/VoiceQueryModelCollectionConfig.swift @@ -1,15 +1,16 @@ // // VoiceQueryModelCollectionConfig.swift // -// Generated by swagger-codegen -// https://github.com/swagger-api/swagger-codegen +// Generated by openapi-generator +// https://openapi-generator.tech // import Foundation - +#if canImport(AnyCodable) +import AnyCodable +#endif /** Configuration for the voice query model */ - public struct VoiceQueryModelCollectionConfig: Codable { public var modelName: String? @@ -18,8 +19,15 @@ public struct VoiceQueryModelCollectionConfig: Codable { self.modelName = modelName } - public enum CodingKeys: String, CodingKey { + public enum CodingKeys: String, CodingKey, CaseIterable { case modelName = "model_name" } + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(modelName, forKey: .modelName) + } } + diff --git a/get-models.sh b/get-models.sh old mode 100644 new mode 100755 index dc97b07..48a3a6d --- a/get-models.sh +++ b/get-models.sh @@ -1,17 +1,21 @@ +#!/bin/bash + +set -e + +echo "Pulling openapi.yml" + curl https://raw.githubusercontent.com/typesense/typesense-api-spec/master/openapi.yml > openapi.yml -swagger-codegen generate -i openapi.yml -l swift5 -o output + +docker run --rm -v "$(pwd):/local" openapitools/openapi-generator-cli generate -i "/local/openapi.yml" -g swift5 -o "/local/output" --additional-properties useJsonEncodable=false --additional-properties hashableModels=false --additional-properties identifiableModels=false + rm -rf Models -cd output/SwaggerClient/Classes/Swaggers +cd output/OpenAPIClient/Classes/OpenAPIs mv ./Models ../../../../ cd ../../../../ rm -rf output cd Models -# Delete useless structs generated as a mistake by the code-gen -rm OneOfSearchParametersMaxHits.swift -rm OneOfMultisearchParametersMaxHits.swift - # Fix the maxHits type by defining it as a String Optional find . -name "SearchParameters.swift" -exec sed -i '' 's/maxHits: OneOfSearchParametersMaxHits\?/maxHits: String\?/g' {} \; find . -name "MultiSearchParameters.swift" -exec sed -i '' 's/maxHits: OneOfMultiSearchParametersMaxHits\?/maxHits: String\?/g' {} \; @@ -19,7 +23,7 @@ find . -name "MultiSearchCollectionParameters.swift" -exec sed -i '' 's/maxHits: # Add Generics to SearchResult find . -name "SearchResult.swift" -exec sed -i '' 's/SearchResult:/SearchResult:/g' {} \; -find . -name "SearchResult.swift" -exec sed -i '' 's/groupedHits: \[SearchGroupedHit\]\?/groupedHits: \[SearchGroupedHit\]\?/g' {} \; +find . -name "SearchResult.swift" -exec sed -i '' 's/groupedHits: \[SearchGroupedHit\]\?/groupedHits: \[SearchGroupedHit\]\?/g' {} \; find . -name "SearchResult.swift" -exec sed -i '' 's/hits: \[SearchResultHit\]\?/hits: \[SearchResultHit\]\?/g' {} \; # Add Generics to MultiSearchResult @@ -39,8 +43,6 @@ find . -name "SearchGroupedHit.swift" -exec sed -i '' 's/hits: \[SearchResultHit # Convert matchedTokens to custom defined StringQuantum find . -name "SearchHighlight.swift" -exec sed -i '' 's/matchedTokens: \[Any\]\?/matchedTokens: StringQuantum\?/g' {} \; - - - - - +cd .. +rm -rf Sources/Typesense/Models +mv ./Models ./Sources/Typesense \ No newline at end of file diff --git a/openapi.yml b/openapi.yml new file mode 100644 index 0000000..e1a279d --- /dev/null +++ b/openapi.yml @@ -0,0 +1,4613 @@ +openapi: 3.0.3 +info: + title: Typesense API + description: "An open source search engine for building delightful search experiences." + version: '30.0' + license: + name: GPL-3.0 + url: https://opensource.org/licenses/GPL-3.0 +servers: + - url: "{protocol}://{hostname}:{port}" + description: Typesense Server + variables: + protocol: + default: http + description: The protocol of your Typesense server + hostname: + default: localhost + description: The hostname of your Typesense server + port: + default: "8108" + description: The port of your Typesense server +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: 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: curation_sets + description: Manage curation sets + - 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 + parameters: + - name: getCollectionsParameters + in: query + schema: + type: object + properties: + exclude_fields: + description: Comma-separated list of fields from the collection to exclude from the response + type: string + limit: + description: > + Number of collections to fetch. + Default: returns all collections. + type: integer + offset: + description: Identifies the starting point to return collections when paginating. + type: integer + 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: updateDocumentsParameters + in: query + schema: + type: object + properties: + filter_by: + 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: deleteDocumentsParameters + in: query + schema: + 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 + 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: searchParameters + required: true + in: query + schema: + $ref: "#/components/schemas/SearchParameters" + 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" + + /synonym_sets: + get: + tags: + - synonyms + summary: List all synonym sets + description: Retrieve all synonym sets + operationId: retrieveSynonymSets + responses: + "200": + description: List of all synonym sets + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/SynonymSetSchema" + + /synonym_sets/{synonymSetName}: + get: + tags: + - synonyms + summary: Retrieve a synonym set + description: Retrieve a specific synonym set by its name + operationId: retrieveSynonymSet + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to retrieve + required: true + schema: + type: string + responses: + "200": + description: Synonym set fetched + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymSetRetrieveSchema" + "404": + description: Synonym set not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + + put: + tags: + - synonyms + summary: Create or update a synonym set + description: Create or update a synonym set with the given name + operationId: upsertSynonymSet + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to create/update + required: true + schema: + type: string + requestBody: + description: The synonym set to be created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymSetCreateSchema" + required: true + responses: + "200": + description: Synonym set successfully created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymSetSchema" + "400": + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + delete: + tags: + - synonyms + summary: Delete a synonym set + description: Delete a specific synonym set by its name + operationId: deleteSynonymSet + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to delete + required: true + schema: + type: string + responses: + "200": + description: Synonym set successfully deleted + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymSetDeleteSchema" + "404": + description: Synonym set not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + + /synonym_sets/{synonymSetName}/items: + get: + tags: + - synonyms + summary: List items in a synonym set + description: Retrieve all synonym items in a set + operationId: retrieveSynonymSetItems + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to retrieve items for + required: true + schema: + type: string + responses: + "200": + description: List of synonym items + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/SynonymItemSchema" + "404": + description: Synonym set not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + + /synonym_sets/{synonymSetName}/items/{itemId}: + get: + tags: + - synonyms + summary: Retrieve a synonym set item + description: Retrieve a specific synonym item by its id + operationId: retrieveSynonymSetItem + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set + required: true + schema: + type: string + - name: itemId + in: path + description: The id of the synonym item to retrieve + required: true + schema: + type: string + responses: + "200": + description: Synonym item fetched + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymItemSchema" + "404": + description: Synonym item not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + put: + tags: + - synonyms + summary: Create or update a synonym set item + description: Create or update a synonym set item with the given id + operationId: upsertSynonymSetItem + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set + required: true + schema: + type: string + - name: itemId + in: path + description: The id of the synonym item to upsert + required: true + schema: + type: string + requestBody: + description: The synonym item to be created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymItemSchema" + required: true + responses: + "200": + description: Synonym item successfully created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymItemSchema" + "400": + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + delete: + tags: + - synonyms + summary: Delete a synonym set item + description: Delete a specific synonym item by its id + operationId: deleteSynonymSetItem + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set + required: true + schema: + type: string + - name: itemId + in: path + description: The id of the synonym item to delete + required: true + schema: + type: string + responses: + "200": + description: Synonym item successfully deleted + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymItemDeleteSchema" + "404": + description: Synonym item not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + + /curation_sets: + get: + tags: + - curation_sets + summary: List all curation sets + description: Retrieve all curation sets + operationId: retrieveCurationSets + responses: + "200": + description: List of all curation sets + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/CurationSetSchema" + + /curation_sets/{curationSetName}: + get: + tags: + - curation_sets + summary: Retrieve a curation set + description: Retrieve a specific curation set by its name + operationId: retrieveCurationSet + parameters: + - name: curationSetName + in: path + description: The name of the curation set to retrieve + required: true + schema: + type: string + responses: + "200": + description: Curation set fetched + content: + application/json: + schema: + $ref: "#/components/schemas/CurationSetRetrieveSchema" + "404": + description: Curation set not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + put: + tags: + - curation_sets + summary: Create or update a curation set + description: Create or update a curation set with the given name + operationId: upsertCurationSet + parameters: + - name: curationSetName + in: path + description: The name of the curation set to create/update + required: true + schema: + type: string + requestBody: + description: The curation set to be created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/CurationSetCreateSchema" + required: true + responses: + "200": + description: Curation set successfully created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/CurationSetSchema" + "400": + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + delete: + tags: + - curation_sets + summary: Delete a curation set + description: Delete a specific curation set by its name + operationId: deleteCurationSet + parameters: + - name: curationSetName + in: path + description: The name of the curation set to delete + required: true + schema: + type: string + responses: + "200": + description: Curation set successfully deleted + content: + application/json: + schema: + $ref: "#/components/schemas/CurationSetDeleteSchema" + "404": + description: Curation set not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + + /curation_sets/{curationSetName}/items: + get: + tags: + - curation_sets + summary: List items in a curation set + description: Retrieve all curation items in a set + operationId: retrieveCurationSetItems + parameters: + - name: curationSetName + in: path + description: The name of the curation set to retrieve items for + required: true + schema: + type: string + responses: + "200": + description: List of curation items + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/CurationItemSchema" + "404": + description: Curation set not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + + /curation_sets/{curationSetName}/items/{itemId}: + get: + tags: + - curation_sets + summary: Retrieve a curation set item + description: Retrieve a specific curation item by its id + operationId: retrieveCurationSetItem + parameters: + - name: curationSetName + in: path + description: The name of the curation set + required: true + schema: + type: string + - name: itemId + in: path + description: The id of the curation item to retrieve + required: true + schema: + type: string + responses: + "200": + description: Curation item fetched + content: + application/json: + schema: + $ref: "#/components/schemas/CurationItemSchema" + "404": + description: Curation item not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + put: + tags: + - curation_sets + summary: Create or update a curation set item + description: Create or update a curation set item with the given id + operationId: upsertCurationSetItem + parameters: + - name: curationSetName + in: path + description: The name of the curation set + required: true + schema: + type: string + - name: itemId + in: path + description: The id of the curation item to upsert + required: true + schema: + type: string + requestBody: + description: The curation item to be created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/CurationItemCreateSchema" + required: true + responses: + "200": + description: Curation item successfully created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/CurationItemSchema" + "400": + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + delete: + tags: + - curation_sets + summary: Delete a curation set item + description: Delete a specific curation item by its id + operationId: deleteCurationSetItem + parameters: + - name: curationSetName + in: path + description: The name of the curation set + required: true + schema: + type: string + - name: itemId + in: path + description: The id of the curation item to delete + required: true + schema: + type: string + responses: + "200": + description: Curation item successfully deleted + content: + application/json: + schema: + $ref: "#/components/schemas/CurationItemDeleteSchema" + "404": + description: Curation item 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: exportDocumentsParameters + in: query + schema: + 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 + + 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 + # Do not change the index position of this param + - name: importDocumentsParameters + in: query + schema: + 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" + 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: Retrieve 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: + summary: Create a conversation model + description: Create a Conversation Model + operationId: createConversationModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelCreateSchema' + required: true + responses: + '201': + 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" + /operations/cache/clear: + post: + tags: + - operations + summary: Clear the cached responses of search requests in the LRU cache. + description: + Clear the cached responses of search requests that are sent with `use_cache` parameter in the LRU cache. + operationId: clearCache + responses: + '200': + description: Clear cache succeeded. + content: + application/json: + schema: + $ref: "#/components/schemas/SuccessStatus" + /operations/db/compact: + post: + tags: + - operations + summary: Compacting the on-disk database + description: + Typesense uses RocksDB to store your documents on the disk. If you do frequent writes or updates, you could benefit from running a compaction of the underlying RocksDB database. + This could reduce the size of the database and decrease read latency. While the database will not block during this operation, we recommend running it during off-peak hours. + operationId: compactDb + responses: + '200': + description: Compacting the on-disk database succeeded. + content: + application/json: + schema: + $ref: "#/components/schemas/SuccessStatus" + /config: + post: + tags: + - operations + summary: Toggle Slow Request Log + description: + Enable logging of requests that take over a defined threshold of time. + Default is `-1` which disables slow request logging. + Slow requests are logged to the primary log file, with the prefix SLOW REQUEST. + operationId: toggleSlowRequestLog + requestBody: + content: + application/json: + schema: + type: object + properties: + log-slow-requests-time-ms: + type: integer + required: + - log-slow-requests-time-ms + example: | + {"log-slow-requests-time-ms": 2000} + responses: + '200': + description: Compacting the on-disk database succeeded. + 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: multiSearchParameters + required: true + in: query + schema: + $ref: "#/components/schemas/MultiSearchParameters" + 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: Submit a single analytics event. The event must correspond to an existing analytics rule by name. + operationId: createAnalyticsEvent + requestBody: + description: The analytics event to be created + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEvent' + required: true + responses: + '200': + 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' + get: + tags: + - analytics + summary: Retrieve analytics events + description: Retrieve the most recent events for a user and rule. + operationId: getAnalyticsEvents + parameters: + - name: user_id + in: query + required: true + schema: + type: string + - name: name + in: query + description: Analytics rule name + required: true + schema: + type: string + - name: n + in: query + description: Number of events to return (max 1000) + required: true + schema: + type: integer + responses: + '200': + description: Events fetched + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventsResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /analytics/flush: + post: + tags: + - analytics + summary: Flush in-memory analytics to disk + description: Triggers a flush of analytics data to persistent storage. + operationId: flushAnalytics + responses: + '200': + description: Flush triggered + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventCreateResponse' + /analytics/status: + get: + tags: + - analytics + summary: Get analytics subsystem status + description: Returns sizes of internal analytics buffers and queues. + operationId: getAnalyticsStatus + responses: + '200': + description: Status fetched + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsStatus' + /analytics/rules: + post: + tags: + - analytics + summary: Create analytics rule(s) + description: Create one or more analytics rules. You can send a single rule object or an array of rule objects. + operationId: createAnalyticsRule + requestBody: + description: The analytics rule(s) to be created + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/AnalyticsRuleCreate" + - type: array + items: + $ref: "#/components/schemas/AnalyticsRuleCreate" + required: true + responses: + '200': + description: Analytics rule(s) successfully created + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/AnalyticsRule" + - type: array + items: + anyOf: + - $ref: "#/components/schemas/AnalyticsRule" + - type: object + properties: + error: + type: string + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + get: + tags: + - analytics + summary: Retrieve analytics rules + description: Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. + operationId: retrieveAnalyticsRules + parameters: + - in: query + name: rule_tag + schema: + type: string + required: false + description: Filter rules by rule_tag + responses: + '200': + description: Analytics rules fetched + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/AnalyticsRule" + /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/AnalyticsRuleUpdate" + required: true + responses: + '200': + description: Analytics rule successfully upserted + content: + application/json: + schema: + $ref: "#/components/schemas/AnalyticsRule" + '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/AnalyticsRule" + '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/AnalyticsRule" + '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 # Go with the first field name listed above to produce sane defaults + 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 # characters only + # Could `enum` be used instead, given it's symbols/special *characters*, e.g.: + # enum: ["@", "!", ".", "/", ","] + minLength: 1 + maxLength: 1 + default: [] + synonym_sets: + type: array + description: List of synonym set names to associate with this collection + items: + type: string + example: "synonym_set_1" + 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 # characters only + # Could `enum` be used instead, given it's symbols/special *characters*, e.g.: + # enum: ["@", "!", ".", "/", ","] + minLength: 1 + maxLength: 1 + default: [] + voice_query_model: + $ref: "#/components/schemas/VoiceQueryModelCollectionConfig" + metadata: + type: object + description: > + Optional details about the collection, e.g., when it was created, who created it etc. + 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" + synonym_sets: + type: array + description: List of synonym set names to associate with this collection + items: + type: string + example: "synonym_set_1" + metadata: + type: object + description: > + Optional details about the collection, e.g., when it was created, who created it etc. + 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 + # 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: + - 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: + $ref: "#/components/schemas/SearchRequestParams" + conversation: + $ref: "#/components/schemas/SearchResultConversation" + union_request_params: + type: array + description: Returned only for union query response. + items: + $ref: "#/components/schemas/SearchRequestParams" + metadata: + type: object + description: Custom JSON object that can be returned in the search response + additionalProperties: true + SearchRequestParams: + 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 + 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 + additionalProperties: + type: object + 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 + hybrid_search_info: + type: object + description: Information about hybrid search scoring + properties: + rank_fusion_score: + type: number + format: float + description: Combined score from rank fusion of text and vector search + search_index: + type: integer + description: Returned only for union query response. Indicates the index of the query which this document matched to. + 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{}" + 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" + 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 your open 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 + + enable_analytics: + description: > + Flag for enabling/disabling analytics aggregation for specific search + queries (for e.g. those originating from a test script). + 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 + + synonym_sets: + type: string + description: List of synonym set names to associate with this search query + example: "synonym_set_1,synonym_set_2" + + 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 + + enable_analytics: + description: > + Flag for enabling/disabling analytics aggregation for specific search + queries (for e.g. those originating from a test script). + type: boolean + 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 + default: false + 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 + AnalyticsEvent: + type: object + required: + - name + - event_type + - data + properties: + name: + type: string + description: Name of the analytics rule this event corresponds to + event_type: + type: string + description: Type of event (e.g., click, conversion, query, visit) + data: + type: object + description: Event payload + properties: + user_id: + type: string + doc_id: + type: string + doc_ids: + type: array + items: + type: string + q: + type: string + analytics_tag: + type: string + AnalyticsEventsResponse: + type: object + required: + - events + properties: + events: + type: array + items: + type: object + properties: + name: { type: string } + event_type: { type: string } + collection: { type: string } + timestamp: { type: integer, format: int64 } + user_id: { type: string } + doc_id: { type: string } + doc_ids: + type: array + items: { type: string } + query: { type: string } + AnalyticsRuleCreate: + type: object + required: + - name + - type + - collection + - event_type + properties: + name: + type: string + type: + type: string + enum: [popular_queries, nohits_queries, counter, log] + collection: + type: string + event_type: + type: string + rule_tag: + type: string + params: + type: object + properties: + destination_collection: + type: string + limit: + type: integer + capture_search_requests: + type: boolean + meta_fields: + type: array + items: { type: string } + expand_query: + type: boolean + counter_field: + type: string + weight: + type: integer + AnalyticsRuleUpdate: + type: object + description: Fields allowed to update on an analytics rule + properties: + name: + type: string + rule_tag: + type: string + params: + type: object + properties: + destination_collection: + type: string + limit: + type: integer + capture_search_requests: + type: boolean + meta_fields: + type: array + items: { type: string } + expand_query: + type: boolean + counter_field: + type: string + weight: + type: integer + AnalyticsRule: + allOf: + - $ref: '#/components/schemas/AnalyticsRuleCreate' + - type: object + AnalyticsStatus: + type: object + properties: + popular_prefix_queries: { type: integer } + nohits_prefix_queries: { type: integer } + log_prefix_queries: { type: integer } + query_log_events: { type: integer } + query_counter_events: { type: integer } + doc_log_events: { type: integer } + doc_counter_events: { type: integer } + + 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 + 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 up to 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 + + SynonymItemSchema: + type: object + required: + - id + - synonyms + properties: + id: + type: string + description: Unique identifier for the synonym item + synonyms: + type: array + description: Array of words that should be considered as synonyms + items: + type: string + root: + type: string + description: For 1-way synonyms, indicates the root word that words in the synonyms parameter map to + 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 + + SynonymSetCreateSchema: + type: object + required: + - items + properties: + items: + type: array + description: Array of synonym items + items: + $ref: "#/components/schemas/SynonymItemSchema" + + SynonymSetSchema: + allOf: + - $ref: "#/components/schemas/SynonymSetCreateSchema" + - type: object + required: + - name + properties: + name: + type: string + description: Name of the synonym set + + SynonymSetsRetrieveSchema: + type: object + required: + - synonym_sets + properties: + synonym_sets: + type: array + description: Array of synonym sets + items: + $ref: "#/components/schemas/SynonymSetSchema" + + SynonymSetRetrieveSchema: + $ref: "#/components/schemas/SynonymSetCreateSchema" + + SynonymSetDeleteSchema: + type: object + required: + - name + properties: + name: + type: string + description: Name of the deleted synonym set + + SynonymItemDeleteSchema: + type: object + required: + - id + properties: + id: + type: string + description: ID of the deleted synonym item + + CurationItemCreateSchema: + type: object + required: + - rule + properties: + rule: + $ref: '#/components/schemas/CurationRule' + 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/CurationInclude' + excludes: + type: array + description: List of document `id`s that should be excluded from the search results. + items: + $ref: '#/components/schemas/CurationExclude' + filter_by: + type: string + description: > + A filter by clause that is applied to any search query that matches the curation rule. + remove_matched_tokens: + type: boolean + description: > + Indicates whether search query tokens that exist in the curation'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 curation rule. + replace_query: + type: string + description: > + Replaces the current search query with this value, when the search query matches the curation 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 curation will be active. You can use this to create 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 curation will be active. You can use this to create rules that stop applying after a period of time. + stop_processing: + type: boolean + description: > + When set to true, curation processing will stop at the first matching rule. When set to false curation processing will continue and multiple curation actions will be triggered in sequence. + Curations are processed in the lexical sort order of their id field. + id: + type: string + description: ID of the curation item + + + CurationItemSchema: + allOf: + - $ref: '#/components/schemas/CurationItemCreateSchema' + - type: object + required: + - id + properties: + id: + type: string + + CurationSetCreateSchema: + type: object + required: + - items + properties: + items: + type: array + description: Array of curation items + items: + $ref: '#/components/schemas/CurationItemCreateSchema' + description: + type: string + description: Optional description for the curation set + + CurationSetSchema: + allOf: + - $ref: '#/components/schemas/CurationSetCreateSchema' + - type: object + required: + - name + properties: + name: + type: string + + CurationRule: + type: object + properties: + tags: + type: array + description: List of tag values to associate with this curation rule. + items: + type: string + query: + type: string + description: Indicates what search queries should be curated + 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 curation should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). + + CurationInclude: + 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 + + CurationExclude: + type: object + required: + - id + properties: + id: + type: string + description: document id that should be excluded from the search results. + + CurationSetRetrieveSchema: + $ref: '#/components/schemas/CurationSetCreateSchema' + + CurationSetDeleteSchema: + type: object + required: + - name + properties: + name: + type: string + description: Name of the deleted curation set + CurationItemDeleteSchema: + type: object + required: + - id + properties: + id: + type: string + description: ID of the deleted curation item + + securitySchemes: + api_key_header: + type: apiKey + name: X-TYPESENSE-API-KEY + in: header From 6787850191e8ea89e36d3856183e63177b6f54aa Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Mon, 1 Dec 2025 17:27:03 +0700 Subject: [PATCH 02/21] feat: openapi tasks --- Package.resolved | 18 + Package.swift | 11 + Sources/Typesense/Analytics.swift | 8 +- Sources/Typesense/AnalyticsEvents.swift | 6 +- ...yticsRule.swift => AnalyticsRuleAPI.swift} | 10 +- Sources/Typesense/AnalyticsRules.swift | 38 +- Sources/Typesense/ApiKeys.swift | 4 +- Sources/Typesense/Documents.swift | 237 +- Sources/Typesense/Models/AnalyticsEvent.swift | 20 +- .../Typesense/Models/AnalyticsEventData.swift | 18 +- .../AnalyticsEventsResponseEventsInner.swift | 34 +- Sources/Typesense/Models/AnalyticsRule.swift | 26 +- .../Models/AnalyticsRuleCreate.swift | 26 +- .../Models/AnalyticsRuleCreateParams.swift | 26 +- .../Models/AnalyticsRuleUpdate.swift | 10 +- .../Typesense/Models/AnalyticsStatus.swift | 42 +- Sources/Typesense/Models/ApiKey.swift | 18 +- Sources/Typesense/Models/ApiKeySchema.swift | 18 +- .../Typesense/Models/CollectionAlias.swift | 12 +- .../Typesense/Models/CollectionResponse.swift | 62 +- .../Typesense/Models/CollectionSchema.swift | 52 +- .../Models/CollectionUpdateSchema.swift | 12 +- .../ConversationModelCreateSchema.swift | 42 +- .../Models/ConversationModelSchema.swift | 42 +- .../ConversationModelUpdateSchema.swift | 42 +- .../CreateAnalyticsRule200Response.swift | 38 - ...teAnalyticsRule200ResponseOneOfInner.swift | 62 - .../Models/CreateAnalyticsRuleRequest.swift | 38 - .../Models/CurationItemCreateSchema.swift | 80 +- .../Typesense/Models/CurationItemSchema.swift | 78 +- Sources/Typesense/Models/CurationRule.swift | 32 +- .../Models/CurationSetCreateSchema.swift | 12 +- .../Typesense/Models/CurationSetSchema.swift | 12 +- ....swift => DeleteDocumentsParameters.swift} | 14 +- ....swift => ExportDocumentsParameters.swift} | 16 +- .../Models/FacetCountsCountsInner.swift | 10 +- .../Typesense/Models/FacetCountsStats.swift | 10 +- Sources/Typesense/Models/Field.swift | 98 +- .../Models/FieldEmbedModelConfig.swift | 42 +- ...r.swift => GetCollectionsParameters.swift} | 4 +- ....swift => ImportDocumentsParameters.swift} | 32 +- .../MultiSearchCollectionParameters.swift | 490 +- .../Models/MultiSearchParameters.swift | 480 +- .../Typesense/Models/MultiSearchResult.swift | 12 +- .../Models/MultiSearchResultItem.swift | 58 +- .../Models/MultiSearchSearchesParameter.swift | 10 +- .../Typesense/Models/NLSearchModelBase.swift | 122 +- .../Models/NLSearchModelCreateSchema.swift | 122 +- .../Models/NLSearchModelSchema.swift | 122 +- .../Models/PresetUpsertSchemaValue.swift | 2 +- .../Typesense/Models/SchemaChangeStatus.swift | 12 +- .../Typesense/Models/SearchGroupedHit.swift | 6 +- .../Typesense/Models/SearchHighlight.swift | 20 +- .../Typesense/Models/SearchParameters.swift | 550 +- .../Models/SearchRequestParams.swift | 10 +- Sources/Typesense/Models/SearchResult.swift | 58 +- .../Typesense/Models/SearchResultHit.swift | 50 +- Sources/Typesense/Models/SearchSynonym.swift | 22 +- .../Models/SearchSynonymSchema.swift | 22 +- .../Models/StemmingDictionaryWordsInner.swift | 12 +- .../Typesense/Models/StopwordsSetSchema.swift | 10 +- .../Models/StopwordsSetUpsertSchema.swift | 10 +- .../Typesense/Models/SynonymItemSchema.swift | 22 +- ....swift => UpdateDocumentsParameters.swift} | 4 +- Sources/Typesense/MultiSearch.swift | 2 +- Sources/Typesense/Operations.swift | 4 +- Sources/Typesense/Override.swift | 36 +- Sources/Typesense/Overrides.swift | 40 +- .../Shared/DocumentIndexParameters.swift | 13 + Sources/Typesense/Shared/Enums.swift | 13 - Sources/Typesense/Stopword.swift | 4 +- Sources/Typesense/utils/Extensions.swift | 2 - Tasks/AddVendorAttributes.swift | 41 + Tasks/PreprocessOpenAPI.swift | 168 + Tasks/VendorAttributes.swift | 71 + Tasks/main.swift | 139 + Tests/TypesenseTests/AnalyticsTests.swift | 86 +- Tests/TypesenseTests/ApiKeyTests.swift | 12 +- .../ConversationModelTests.swift | 2 +- Tests/TypesenseTests/MultiSearchTests.swift | 2 +- Tests/TypesenseTests/OperationTests.swift | 2 +- Tests/TypesenseTests/OverrideTests.swift | 84 +- Tests/TypesenseTests/OverridesTests.swift | 130 +- Tests/TypesenseTests/PresetTests.swift | 2 +- Tests/TypesenseTests/PresetsTests.swift | 12 +- Tests/TypesenseTests/StopwordTests.swift | 4 +- Tests/TypesenseTests/StopwordsTests.swift | 4 +- Tests/TypesenseTests/SynonymTests.swift | 8 +- Tests/TypesenseTests/TestUtils.swift | 48 +- preprocessed_openapi.yml | 5857 +++++++++++++++++ 90 files changed, 8220 insertions(+), 2204 deletions(-) rename Sources/Typesense/{AnalyticsRule.swift => AnalyticsRuleAPI.swift} (67%) delete mode 100644 Sources/Typesense/Models/CreateAnalyticsRule200Response.swift delete mode 100644 Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInner.swift delete mode 100644 Sources/Typesense/Models/CreateAnalyticsRuleRequest.swift rename Sources/Typesense/Models/{DeleteDocumentsDeleteDocumentsParametersParameter.swift => DeleteDocumentsParameters.swift} (88%) rename Sources/Typesense/Models/{ExportDocumentsExportDocumentsParametersParameter.swift => ExportDocumentsParameters.swift} (83%) rename Sources/Typesense/Models/{GetCollectionsGetCollectionsParametersParameter.swift => GetCollectionsParameters.swift} (90%) rename Sources/Typesense/Models/{ImportDocumentsImportDocumentsParametersParameter.swift => ImportDocumentsParameters.swift} (84%) rename Sources/Typesense/Models/{UpdateDocumentsUpdateDocumentsParametersParameter.swift => UpdateDocumentsParameters.swift} (81%) create mode 100644 Sources/Typesense/Shared/DocumentIndexParameters.swift delete mode 100644 Sources/Typesense/Shared/Enums.swift create mode 100644 Tasks/AddVendorAttributes.swift create mode 100644 Tasks/PreprocessOpenAPI.swift create mode 100644 Tasks/VendorAttributes.swift create mode 100644 Tasks/main.swift create mode 100644 preprocessed_openapi.yml diff --git a/Package.resolved b/Package.resolved index ad0d042..1eeadf3 100644 --- a/Package.resolved +++ b/Package.resolved @@ -9,6 +9,24 @@ "revision": "862808b2070cd908cb04f9aafe7de83d35f81b05", "version": "0.6.7" } + }, + { + "package": "swift-argument-parser", + "repositoryURL": "https://github.com/apple/swift-argument-parser", + "state": { + "branch": null, + "revision": "cdd0ef3755280949551dc26dee5de9ddeda89f54", + "version": "1.6.2" + } + }, + { + "package": "Yams", + "repositoryURL": "https://github.com/jpsim/Yams.git", + "state": { + "branch": null, + "revision": "3d6871d5b4a5cd519adf233fbb576e0a2af71c17", + "version": "5.4.0" + } } ] }, diff --git a/Package.swift b/Package.swift index ca15cbb..79ccbfa 100644 --- a/Package.swift +++ b/Package.swift @@ -21,6 +21,8 @@ let package = Package( url: "https://github.com/Flight-School/AnyCodable", from: "0.6.0" ), + .package(url: "https://github.com/apple/swift-argument-parser", from: "1.2.0"), + .package(url: "https://github.com/jpsim/Yams.git", from: "5.0.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. @@ -31,5 +33,14 @@ let package = Package( .testTarget( name: "TypesenseTests", dependencies: ["Typesense"]), + + .executableTarget( + name: "Tasks", + dependencies: [ + .product(name: "ArgumentParser", package: "swift-argument-parser"), + .product(name: "Yams", package: "Yams") + ], + path: "Tasks" + ) ] ) diff --git a/Sources/Typesense/Analytics.swift b/Sources/Typesense/Analytics.swift index a14f507..8c5fcc1 100644 --- a/Sources/Typesense/Analytics.swift +++ b/Sources/Typesense/Analytics.swift @@ -11,12 +11,12 @@ public struct Analytics { self.analyticsRules = AnalyticsRules(apiCall: apiCall) } - public func events() -> AnalyticsEvents { - return AnalyticsEvents(apiCall: self.apiCall) + public func events() -> AnalyticsEventsAPI { + return AnalyticsEventsAPI(apiCall: self.apiCall) } - public func rule(id: String) -> AnalyticsRule { - return AnalyticsRule(name: id, apiCall: self.apiCall) + public func rule(_ name: String) -> AnalyticsRuleAPI { + return AnalyticsRuleAPI(name: name, apiCall: self.apiCall) } public func rules() -> AnalyticsRules { diff --git a/Sources/Typesense/AnalyticsEvents.swift b/Sources/Typesense/AnalyticsEvents.swift index 4008b88..c8f3f7f 100644 --- a/Sources/Typesense/AnalyticsEvents.swift +++ b/Sources/Typesense/AnalyticsEvents.swift @@ -3,7 +3,7 @@ import Foundation import FoundationNetworking #endif -public struct AnalyticsEvents { +public struct AnalyticsEventsAPI { static var resourcePath: String = "\(Analytics.resourcePath)/events" var apiCall: ApiCall @@ -11,9 +11,9 @@ public struct AnalyticsEvents { self.apiCall = apiCall } - public func create(params: AnalyticsEventCreateSchema) async throws -> (AnalyticsEventCreateResponse?, URLResponse?) { + public func create(_ params: AnalyticsEvent) async throws -> (AnalyticsEventCreateResponse?, URLResponse?) { let json = try encoder.encode(params) - let (data, response) = try await self.apiCall.post(endPoint: AnalyticsEvents.resourcePath, body: json) + let (data, response) = try await self.apiCall.post(endPoint: AnalyticsEventsAPI.resourcePath, body: json) if let result = data { let validData = try decoder.decode(AnalyticsEventCreateResponse.self, from: result) return (validData, response) diff --git a/Sources/Typesense/AnalyticsRule.swift b/Sources/Typesense/AnalyticsRuleAPI.swift similarity index 67% rename from Sources/Typesense/AnalyticsRule.swift rename to Sources/Typesense/AnalyticsRuleAPI.swift index 3a13f01..839f597 100644 --- a/Sources/Typesense/AnalyticsRule.swift +++ b/Sources/Typesense/AnalyticsRuleAPI.swift @@ -3,7 +3,7 @@ import Foundation import FoundationNetworking #endif -public struct AnalyticsRule { +public struct AnalyticsRuleAPI { var name: String private var apiCall: ApiCall init(name: String, apiCall: ApiCall) { @@ -11,19 +11,19 @@ public struct AnalyticsRule { self.apiCall = apiCall } - public func retrieve() async throws -> (AnalyticsRuleSchema?, URLResponse?) { + public func retrieve() async throws -> (AnalyticsRule?, URLResponse?) { let (data, response) = try await self.apiCall.get(endPoint: endpointPath()) if let result = data { - let fetchedRule = try decoder.decode(AnalyticsRuleSchema.self, from: result) + let fetchedRule = try decoder.decode(AnalyticsRule.self, from: result) return (fetchedRule, response) } return (nil, response) } - public func delete() async throws -> (AnalyticsRuleDeleteResponse?, URLResponse?) { + public func delete() async throws -> (AnalyticsRule?, URLResponse?) { let (data, response) = try await self.apiCall.delete(endPoint: endpointPath()) if let result = data { - let deletedRule = try decoder.decode(AnalyticsRuleDeleteResponse.self, from: result) + let deletedRule = try decoder.decode(AnalyticsRule.self, from: result) return (deletedRule, response) } return (nil, response) diff --git a/Sources/Typesense/AnalyticsRules.swift b/Sources/Typesense/AnalyticsRules.swift index 3a122ab..19efd90 100644 --- a/Sources/Typesense/AnalyticsRules.swift +++ b/Sources/Typesense/AnalyticsRules.swift @@ -12,21 +12,49 @@ public struct AnalyticsRules { self.apiCall = apiCall } - public func upsert(params: AnalyticsRuleSchema) async throws -> (AnalyticsRuleSchema?, URLResponse?) { + public func update(_ params: AnalyticsRuleUpdate) async throws -> (AnalyticsRule?, URLResponse?) { let ruleData = try encoder.encode(params) let (data, response) = try await self.apiCall.put(endPoint: endpointPath(params.name), body: ruleData) if let result = data { - let ruleResult = try decoder.decode(AnalyticsRuleSchema.self, from: result) + let ruleResult = try decoder.decode(AnalyticsRule.self, from: result) return (ruleResult, response) } return (nil, response) } - public func retrieveAll() async throws -> (AnalyticsRulesRetrieveSchema?, URLResponse?) { - let (data, response) = try await self.apiCall.get(endPoint: endpointPath()) + public func create(_ params: AnalyticsRuleCreate) async throws -> (AnalyticsRule?, URLResponse?) { + let ruleData = try encoder.encode(params) + let (data, response) = try await self.apiCall.put(endPoint: endpointPath(), body: ruleData) + if let result = data { + let ruleResult = try decoder.decode(AnalyticsRule.self, from: result) + return (ruleResult, response) + } + + return (nil, response) + } + + public func createMany(_ params: [AnalyticsRuleCreate]) async throws -> ([AnalyticsRule]?, URLResponse?) { + let ruleData = try encoder.encode(params) + let (data, response) = try await self.apiCall.put(endPoint: endpointPath(), body: ruleData) + if let result = data { + let ruleResult = try decoder.decode([AnalyticsRule].self, from: result) + return (ruleResult, response) + } + + return (nil, response) + } + + public func retrieveAll(ruleTag: String? = nil) async throws -> ([AnalyticsRule]?, URLResponse?) { + var urlParams: [URLQueryItem] = [] + + if let rule_tag = ruleTag{ + urlParams.append(URLQueryItem(name: "rule_tag", value: rule_tag)) + } + + let (data, response) = try await self.apiCall.get(endPoint: endpointPath(), queryParameters: urlParams) if let result = data { - let rules = try decoder.decode(AnalyticsRulesRetrieveSchema.self, from: result) + let rules = try decoder.decode([AnalyticsRule].self, from: result) return (rules, response) } diff --git a/Sources/Typesense/ApiKeys.swift b/Sources/Typesense/ApiKeys.swift index 5be3dfc..08e6af6 100644 --- a/Sources/Typesense/ApiKeys.swift +++ b/Sources/Typesense/ApiKeys.swift @@ -28,7 +28,7 @@ public struct ApiKeys { return (nil, nil) } - public func retrieve(id: Int) async throws -> (ApiKey?, URLResponse?) { + public func retrieve(id: Int64) async throws -> (ApiKey?, URLResponse?) { let (data, response) = try await apiCall.get(endPoint: "\(RESOURCEPATH)/\(id)") if let result = data { @@ -50,7 +50,7 @@ public struct ApiKeys { return (nil, nil) } - public func delete(id: Int) async throws -> (Data?, URLResponse?) { + public func delete(id: Int64) async throws -> (Data?, URLResponse?) { let (data, response) = try await apiCall.delete(endPoint: "\(RESOURCEPATH)/\(id)") return (data, response) diff --git a/Sources/Typesense/Documents.swift b/Sources/Typesense/Documents.swift index e42bb0d..7dce061 100644 --- a/Sources/Typesense/Documents.swift +++ b/Sources/Typesense/Documents.swift @@ -38,22 +38,22 @@ public struct Documents { return (nil, response) } - public func update(document: T, options: UpdateDocumentsByFilterParameters) async throws -> (UpdateByFilterResponse?, URLResponse?) { + public func update(document: T, options: UpdateDocumentsParameters) async throws -> (UpdateDocuments200Response?, URLResponse?) { let queryParams = try createURLQuery(forSchema: options) let jsonData = try encoder.encode(document) let (data, response) = try await apiCall.patch(endPoint: endpointPath(), body: jsonData, queryParameters: queryParams) if let validData = data { - let decodedData = try decoder.decode(UpdateByFilterResponse.self, from: validData) + let decodedData = try decoder.decode(UpdateDocuments200Response.self, from: validData) return (decodedData, response) } return (nil, response) } - public func delete(options: DeleteDocumentsParameters) async throws -> (DeleteDocumentsResponse?, URLResponse?) { + public func delete(options: DeleteDocumentsParameters) async throws -> (DeleteDocuments200Response?, URLResponse?) { let queryParams = try createURLQuery(forSchema: options) let (data, response) = try await apiCall.delete(endPoint: endpointPath(), queryParameters: queryParams) if let validData = data { - let decodedData = try decoder.decode(DeleteDocumentsResponse.self, from: validData) + let decodedData = try decoder.decode(DeleteDocuments200Response.self, from: validData) return (decodedData, response) } return (nil, response) @@ -79,233 +79,8 @@ public struct Documents { } public func search(_ searchParameters: SearchParameters, for: T.Type) async throws -> (SearchResult?, URLResponse?) { - var searchQueryParams: [URLQueryItem] = [] - - if let q = searchParameters.q { - searchQueryParams.append(URLQueryItem(name: "q", value: q)) - } - - if let queryBy = searchParameters.queryBy { - searchQueryParams.append(URLQueryItem(name: "query_by", value: queryBy)) - } - - if let queryByWeights = searchParameters.queryByWeights { - searchQueryParams.append(URLQueryItem(name: "query_by_weights", value: queryByWeights)) - } - - if let textMatchType = searchParameters.textMatchType { - searchQueryParams.append(URLQueryItem(name: "text_match_type", value: textMatchType)) - } - - if let _prefix = searchParameters._prefix { - searchQueryParams.append(URLQueryItem(name: "prefix", value: _prefix)) - } - - if let _infix = searchParameters._infix { - searchQueryParams.append(URLQueryItem(name: "infix", value: _infix)) - } - - if let maxExtraPrefix = searchParameters.maxExtraPrefix { - searchQueryParams.append(URLQueryItem(name: "max_extra_prefix", value: String(maxExtraPrefix))) - } - - if let maxExtraSuffix = searchParameters.maxExtraSuffix { - searchQueryParams.append(URLQueryItem(name: "max_extra_suffix", value: String(maxExtraSuffix))) - } - - if let filterBy = searchParameters.filterBy { - searchQueryParams.append(URLQueryItem(name: "filter_by", value: filterBy)) - } - - if let sortBy = searchParameters.sortBy { - searchQueryParams.append(URLQueryItem(name: "sort_by", value: sortBy)) - } - - if let facetBy = searchParameters.facetBy { - searchQueryParams.append(URLQueryItem(name: "facet_by", value: facetBy)) - } - - if let maxFacetValues = searchParameters.maxFacetValues { - searchQueryParams.append(URLQueryItem(name: "max_facet_values", value: String(maxFacetValues))) - } - - if let facetQuery = searchParameters.facetQuery { - searchQueryParams.append(URLQueryItem(name: "facet_query", value: facetQuery)) - } - - if let numTypos = searchParameters.numTypos { - searchQueryParams.append(URLQueryItem(name: "num_typos", value: String(numTypos))) - } - - if let page = searchParameters.page { - searchQueryParams.append(URLQueryItem(name: "page", value: String(page))) - } - - if let perPage = searchParameters.perPage { - searchQueryParams.append(URLQueryItem(name: "per_page", value: String(perPage))) - } - - if let limit = searchParameters.limit { - searchQueryParams.append(URLQueryItem(name: "limit", value: String(limit))) - } - - if let offset = searchParameters.offset { - searchQueryParams.append(URLQueryItem(name: "offset", value: String(offset))) - } - - if let groupBy = searchParameters.groupBy { - searchQueryParams.append(URLQueryItem(name: "group_by", value: groupBy)) - } - - if let groupLimit = searchParameters.groupLimit { - searchQueryParams.append(URLQueryItem(name: "group_limit", value: String(groupLimit))) - } - - if let groupMissingValues = searchParameters.groupMissingValues { - searchQueryParams.append(URLQueryItem(name: "group_missing_values", value: String(groupMissingValues))) - } - - if let includeFields = searchParameters.includeFields { - searchQueryParams.append(URLQueryItem(name: "include_fields", value: includeFields)) - } - - if let excludeFields = searchParameters.excludeFields { - searchQueryParams.append(URLQueryItem(name: "exclude_fields", value: excludeFields)) - } - - if let highlightFullFields = searchParameters.highlightFullFields { - searchQueryParams.append(URLQueryItem(name: "highlight_full_fields", value: highlightFullFields)) - } - - if let highlightAffixNumTokens = searchParameters.highlightAffixNumTokens { - searchQueryParams.append(URLQueryItem(name: "highlight_affix_num_tokens", value: String(highlightAffixNumTokens))) - } - - if let highlightStartTag = searchParameters.highlightStartTag { - searchQueryParams.append(URLQueryItem(name: "highlight_start_tag", value: highlightStartTag)) - } - - if let highlightEndTag = searchParameters.highlightEndTag { - searchQueryParams.append(URLQueryItem(name: "highlight_end_tag", value: highlightEndTag)) - } - - if let enableHighlightV1 = searchParameters.enableHighlightV1 { - searchQueryParams.append(URLQueryItem(name: "enable_highlight_v1", value: String(enableHighlightV1))) - } - - if let snippetThreshold = searchParameters.snippetThreshold { - searchQueryParams.append(URLQueryItem(name: "snippet_threshold", value: String(snippetThreshold))) - } - - if let dropTokensThreshold = searchParameters.dropTokensThreshold { - searchQueryParams.append(URLQueryItem(name: "drop_tokens_threshold", value: String(dropTokensThreshold))) - } - - if let typoTokensThreshold = searchParameters.typoTokensThreshold { - searchQueryParams.append(URLQueryItem(name: "typo_tokens_threshold", value: String(typoTokensThreshold))) - } - - if let pinnedHits = searchParameters.pinnedHits { - searchQueryParams.append(URLQueryItem(name: "pinned_hits", value: pinnedHits)) - } - - if let hiddenHits = searchParameters.hiddenHits { - searchQueryParams.append(URLQueryItem(name: "hidden_hits", value: hiddenHits)) - } - - if let overrideTags = searchParameters.overrideTags { - searchQueryParams.append(URLQueryItem(name: "override_tags", value: overrideTags)) - } - - if let highlightFields = searchParameters.highlightFields { - searchQueryParams.append(URLQueryItem(name: "highlight_fields", value: highlightFields)) - } - - if let splitJoinTokens = searchParameters.splitJoinTokens { - searchQueryParams.append(URLQueryItem(name: "split_join_tokens", value: splitJoinTokens)) - } - - if let preSegmentedQuery = searchParameters.preSegmentedQuery { - searchQueryParams.append(URLQueryItem(name: "pre_segmented_query", value: String(preSegmentedQuery))) - } - - if let preset = searchParameters.preset { - searchQueryParams.append(URLQueryItem(name: "preset", value: preset)) - } - - if let enableOverrides = searchParameters.enableOverrides { - searchQueryParams.append(URLQueryItem(name: "enable_overrides", value: String(enableOverrides))) - } - - if let prioritizeExactMatch = searchParameters.prioritizeExactMatch { - searchQueryParams.append(URLQueryItem(name: "prioritize_exact_match", value: String(prioritizeExactMatch))) - } - - if let maxCandidates = searchParameters.maxCandidates { - searchQueryParams.append(URLQueryItem(name: "max_candidates", value: String(maxCandidates))) - } - - if let prioritizeTokenPosition = searchParameters.prioritizeTokenPosition { - searchQueryParams.append(URLQueryItem(name: "prioritize_token_position", value: String(prioritizeTokenPosition))) - } - - if let prioritizeNumMatchingFields = searchParameters.prioritizeNumMatchingFields { - searchQueryParams.append(URLQueryItem(name: "prioritize_num_matching_fields", value: String(prioritizeNumMatchingFields))) - } - - if let enableTyposForNumericalTokens = searchParameters.enableTyposForNumericalTokens { - searchQueryParams.append(URLQueryItem(name: "enable_typos_for_numerical_tokens", value: String(enableTyposForNumericalTokens))) - } - - if let exhaustiveSearch = searchParameters.exhaustiveSearch { - searchQueryParams.append(URLQueryItem(name: "exhaustive_search", value: String(exhaustiveSearch))) - } - - if let searchCutoffMs = searchParameters.searchCutoffMs { - searchQueryParams.append(URLQueryItem(name: "search_cutoff_ms", value: String(searchCutoffMs))) - } - - if let useCache = searchParameters.useCache { - searchQueryParams.append(URLQueryItem(name: "use_cache", value: String(useCache))) - } - - if let cacheTtl = searchParameters.cacheTtl { - searchQueryParams.append(URLQueryItem(name: "cache_ttl", value: String(cacheTtl))) - } - - if let minLen1typo = searchParameters.minLen1typo { - searchQueryParams.append(URLQueryItem(name: "min_len1type", value: String(minLen1typo))) - } - - if let minLen2typo = searchParameters.minLen2typo { - searchQueryParams.append(URLQueryItem(name: "min_len2type", value: String(minLen2typo))) - } - - if let vectorQuery = searchParameters.vectorQuery { - searchQueryParams.append(URLQueryItem(name: "vector_query", value: vectorQuery)) - } - - if let remoteEmbeddingTimeoutMS = searchParameters.remoteEmbeddingTimeoutMs { - searchQueryParams.append(URLQueryItem(name: "remote_embedding_timeout_ms", value: String(remoteEmbeddingTimeoutMS))) - } - - if let remoteEmbeddingNumTries = searchParameters.remoteEmbeddingNumTries { - searchQueryParams.append(URLQueryItem(name: "remote_embedding_num_tries", value: String(remoteEmbeddingNumTries))) - } - - if let facetStrategy = searchParameters.facetStrategy { - searchQueryParams.append(URLQueryItem(name: "facet_strategy", value: facetStrategy)) - } - - if let stopwords = searchParameters.stopwords { - searchQueryParams.append(URLQueryItem(name: "stopwords", value: stopwords)) - } - - if let facetReturnParent = searchParameters.facetReturnParent { - searchQueryParams.append(URLQueryItem(name: "facet_strategy", value: facetReturnParent)) - } - - let (data, response) = try await apiCall.get(endPoint: endpointPath("search"), queryParameters: searchQueryParams) + let queryParams = try createURLQuery(forSchema: searchParameters) + let (data, response) = try await apiCall.get(endPoint: endpointPath("search"), queryParameters: queryParams) if let validData = data { let searchRes = try decoder.decode(SearchResult.self, from: validData) diff --git a/Sources/Typesense/Models/AnalyticsEvent.swift b/Sources/Typesense/Models/AnalyticsEvent.swift index 04ce95e..a409a8d 100644 --- a/Sources/Typesense/Models/AnalyticsEvent.swift +++ b/Sources/Typesense/Models/AnalyticsEvent.swift @@ -12,31 +12,31 @@ import AnyCodable public struct AnalyticsEvent: Codable { - /** Name of the analytics rule this event corresponds to */ - public var name: String + public var data: AnalyticsEventData /** Type of event (e.g., click, conversion, query, visit) */ public var eventType: String - public var data: AnalyticsEventData + /** Name of the analytics rule this event corresponds to */ + public var name: String - public init(name: String, eventType: String, data: AnalyticsEventData) { - self.name = name - self.eventType = eventType + public init(data: AnalyticsEventData, eventType: String, name: String) { self.data = data + self.eventType = eventType + self.name = name } public enum CodingKeys: String, CodingKey, CaseIterable { - case name - case eventType = "event_type" case data + case eventType = "event_type" + case name } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(name, forKey: .name) - try container.encode(eventType, forKey: .eventType) try container.encode(data, forKey: .data) + try container.encode(eventType, forKey: .eventType) + try container.encode(name, forKey: .name) } } diff --git a/Sources/Typesense/Models/AnalyticsEventData.swift b/Sources/Typesense/Models/AnalyticsEventData.swift index 23d6d3d..095a5c5 100644 --- a/Sources/Typesense/Models/AnalyticsEventData.swift +++ b/Sources/Typesense/Models/AnalyticsEventData.swift @@ -13,37 +13,37 @@ import AnyCodable /** Event payload */ public struct AnalyticsEventData: Codable { - public var userId: String? + public var analyticsTag: String? public var docId: String? public var docIds: [String]? public var q: String? - public var analyticsTag: String? + public var userId: String? - public init(userId: String? = nil, docId: String? = nil, docIds: [String]? = nil, q: String? = nil, analyticsTag: String? = nil) { - self.userId = userId + public init(analyticsTag: String? = nil, docId: String? = nil, docIds: [String]? = nil, q: String? = nil, userId: String? = nil) { + self.analyticsTag = analyticsTag self.docId = docId self.docIds = docIds self.q = q - self.analyticsTag = analyticsTag + self.userId = userId } public enum CodingKeys: String, CodingKey, CaseIterable { - case userId = "user_id" + case analyticsTag = "analytics_tag" case docId = "doc_id" case docIds = "doc_ids" case q - case analyticsTag = "analytics_tag" + case userId = "user_id" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(userId, forKey: .userId) + try container.encodeIfPresent(analyticsTag, forKey: .analyticsTag) try container.encodeIfPresent(docId, forKey: .docId) try container.encodeIfPresent(docIds, forKey: .docIds) try container.encodeIfPresent(q, forKey: .q) - try container.encodeIfPresent(analyticsTag, forKey: .analyticsTag) + try container.encodeIfPresent(userId, forKey: .userId) } } diff --git a/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift b/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift index 75b867a..5c1ee44 100644 --- a/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift +++ b/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift @@ -12,49 +12,49 @@ import AnyCodable public struct AnalyticsEventsResponseEventsInner: Codable { - public var name: String? - public var eventType: String? public var collection: String? - public var timestamp: Int64? - public var userId: String? public var docId: String? public var docIds: [String]? + public var eventType: String? + public var name: String? public var query: String? + public var timestamp: Int64? + public var userId: String? - public init(name: String? = nil, eventType: String? = nil, collection: String? = nil, timestamp: Int64? = nil, userId: String? = nil, docId: String? = nil, docIds: [String]? = nil, query: String? = nil) { - self.name = name - self.eventType = eventType + public init(collection: String? = nil, docId: String? = nil, docIds: [String]? = nil, eventType: String? = nil, name: String? = nil, query: String? = nil, timestamp: Int64? = nil, userId: String? = nil) { self.collection = collection - self.timestamp = timestamp - self.userId = userId self.docId = docId self.docIds = docIds + self.eventType = eventType + self.name = name self.query = query + self.timestamp = timestamp + self.userId = userId } public enum CodingKeys: String, CodingKey, CaseIterable { - case name - case eventType = "event_type" case collection - case timestamp - case userId = "user_id" case docId = "doc_id" case docIds = "doc_ids" + case eventType = "event_type" + case name case query + case timestamp + case userId = "user_id" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(name, forKey: .name) - try container.encodeIfPresent(eventType, forKey: .eventType) try container.encodeIfPresent(collection, forKey: .collection) - try container.encodeIfPresent(timestamp, forKey: .timestamp) - try container.encodeIfPresent(userId, forKey: .userId) try container.encodeIfPresent(docId, forKey: .docId) try container.encodeIfPresent(docIds, forKey: .docIds) + try container.encodeIfPresent(eventType, forKey: .eventType) + try container.encodeIfPresent(name, forKey: .name) try container.encodeIfPresent(query, forKey: .query) + try container.encodeIfPresent(timestamp, forKey: .timestamp) + try container.encodeIfPresent(userId, forKey: .userId) } } diff --git a/Sources/Typesense/Models/AnalyticsRule.swift b/Sources/Typesense/Models/AnalyticsRule.swift index a9b5650..b3a495e 100644 --- a/Sources/Typesense/Models/AnalyticsRule.swift +++ b/Sources/Typesense/Models/AnalyticsRule.swift @@ -18,41 +18,41 @@ public struct AnalyticsRule: Codable { case counter = "counter" case log = "log" } - public var name: String - public var type: ModelType public var collection: String public var eventType: String - public var ruleTag: String? + public var name: String public var params: AnalyticsRuleCreateParams? + public var ruleTag: String? + public var type: ModelType - public init(name: String, type: ModelType, collection: String, eventType: String, ruleTag: String? = nil, params: AnalyticsRuleCreateParams? = nil) { - self.name = name - self.type = type + public init(collection: String, eventType: String, name: String, params: AnalyticsRuleCreateParams? = nil, ruleTag: String? = nil, type: ModelType) { self.collection = collection self.eventType = eventType - self.ruleTag = ruleTag + self.name = name self.params = params + self.ruleTag = ruleTag + self.type = type } public enum CodingKeys: String, CodingKey, CaseIterable { - case name - case type case collection case eventType = "event_type" - case ruleTag = "rule_tag" + case name case params + case ruleTag = "rule_tag" + case type } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(name, forKey: .name) - try container.encode(type, forKey: .type) try container.encode(collection, forKey: .collection) try container.encode(eventType, forKey: .eventType) - try container.encodeIfPresent(ruleTag, forKey: .ruleTag) + try container.encode(name, forKey: .name) try container.encodeIfPresent(params, forKey: .params) + try container.encodeIfPresent(ruleTag, forKey: .ruleTag) + try container.encode(type, forKey: .type) } } diff --git a/Sources/Typesense/Models/AnalyticsRuleCreate.swift b/Sources/Typesense/Models/AnalyticsRuleCreate.swift index c772d13..ef0ba37 100644 --- a/Sources/Typesense/Models/AnalyticsRuleCreate.swift +++ b/Sources/Typesense/Models/AnalyticsRuleCreate.swift @@ -18,41 +18,41 @@ public struct AnalyticsRuleCreate: Codable { case counter = "counter" case log = "log" } - public var name: String - public var type: ModelType public var collection: String public var eventType: String - public var ruleTag: String? + public var name: String public var params: AnalyticsRuleCreateParams? + public var ruleTag: String? + public var type: ModelType - public init(name: String, type: ModelType, collection: String, eventType: String, ruleTag: String? = nil, params: AnalyticsRuleCreateParams? = nil) { - self.name = name - self.type = type + public init(collection: String, eventType: String, name: String, params: AnalyticsRuleCreateParams? = nil, ruleTag: String? = nil, type: ModelType) { self.collection = collection self.eventType = eventType - self.ruleTag = ruleTag + self.name = name self.params = params + self.ruleTag = ruleTag + self.type = type } public enum CodingKeys: String, CodingKey, CaseIterable { - case name - case type case collection case eventType = "event_type" - case ruleTag = "rule_tag" + case name case params + case ruleTag = "rule_tag" + case type } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(name, forKey: .name) - try container.encode(type, forKey: .type) try container.encode(collection, forKey: .collection) try container.encode(eventType, forKey: .eventType) - try container.encodeIfPresent(ruleTag, forKey: .ruleTag) + try container.encode(name, forKey: .name) try container.encodeIfPresent(params, forKey: .params) + try container.encodeIfPresent(ruleTag, forKey: .ruleTag) + try container.encode(type, forKey: .type) } } diff --git a/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift b/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift index 3bc547a..5b36c74 100644 --- a/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift +++ b/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift @@ -12,31 +12,31 @@ import AnyCodable public struct AnalyticsRuleCreateParams: Codable { + public var captureSearchRequests: Bool? + public var counterField: String? public var destinationCollection: String? + public var expandQuery: Bool? public var limit: Int? - public var captureSearchRequests: Bool? public var metaFields: [String]? - public var expandQuery: Bool? - public var counterField: String? public var weight: Int? - public init(destinationCollection: String? = nil, limit: Int? = nil, captureSearchRequests: Bool? = nil, metaFields: [String]? = nil, expandQuery: Bool? = nil, counterField: String? = nil, weight: Int? = nil) { + public init(captureSearchRequests: Bool? = nil, counterField: String? = nil, destinationCollection: String? = nil, expandQuery: Bool? = nil, limit: Int? = nil, metaFields: [String]? = nil, weight: Int? = nil) { + self.captureSearchRequests = captureSearchRequests + self.counterField = counterField self.destinationCollection = destinationCollection + self.expandQuery = expandQuery self.limit = limit - self.captureSearchRequests = captureSearchRequests self.metaFields = metaFields - self.expandQuery = expandQuery - self.counterField = counterField self.weight = weight } public enum CodingKeys: String, CodingKey, CaseIterable { + case captureSearchRequests = "capture_search_requests" + case counterField = "counter_field" case destinationCollection = "destination_collection" + case expandQuery = "expand_query" case limit - case captureSearchRequests = "capture_search_requests" case metaFields = "meta_fields" - case expandQuery = "expand_query" - case counterField = "counter_field" case weight } @@ -44,12 +44,12 @@ public struct AnalyticsRuleCreateParams: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(captureSearchRequests, forKey: .captureSearchRequests) + try container.encodeIfPresent(counterField, forKey: .counterField) try container.encodeIfPresent(destinationCollection, forKey: .destinationCollection) + try container.encodeIfPresent(expandQuery, forKey: .expandQuery) try container.encodeIfPresent(limit, forKey: .limit) - try container.encodeIfPresent(captureSearchRequests, forKey: .captureSearchRequests) try container.encodeIfPresent(metaFields, forKey: .metaFields) - try container.encodeIfPresent(expandQuery, forKey: .expandQuery) - try container.encodeIfPresent(counterField, forKey: .counterField) try container.encodeIfPresent(weight, forKey: .weight) } } diff --git a/Sources/Typesense/Models/AnalyticsRuleUpdate.swift b/Sources/Typesense/Models/AnalyticsRuleUpdate.swift index ecb8a93..8cddca1 100644 --- a/Sources/Typesense/Models/AnalyticsRuleUpdate.swift +++ b/Sources/Typesense/Models/AnalyticsRuleUpdate.swift @@ -14,19 +14,19 @@ import AnyCodable public struct AnalyticsRuleUpdate: Codable { public var name: String? - public var ruleTag: String? public var params: AnalyticsRuleCreateParams? + public var ruleTag: String? - public init(name: String? = nil, ruleTag: String? = nil, params: AnalyticsRuleCreateParams? = nil) { + public init(name: String? = nil, params: AnalyticsRuleCreateParams? = nil, ruleTag: String? = nil) { self.name = name - self.ruleTag = ruleTag self.params = params + self.ruleTag = ruleTag } public enum CodingKeys: String, CodingKey, CaseIterable { case name - case ruleTag = "rule_tag" case params + case ruleTag = "rule_tag" } // Encodable protocol methods @@ -34,8 +34,8 @@ public struct AnalyticsRuleUpdate: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(name, forKey: .name) - try container.encodeIfPresent(ruleTag, forKey: .ruleTag) try container.encodeIfPresent(params, forKey: .params) + try container.encodeIfPresent(ruleTag, forKey: .ruleTag) } } diff --git a/Sources/Typesense/Models/AnalyticsStatus.swift b/Sources/Typesense/Models/AnalyticsStatus.swift index 875c910..34a8905 100644 --- a/Sources/Typesense/Models/AnalyticsStatus.swift +++ b/Sources/Typesense/Models/AnalyticsStatus.swift @@ -12,45 +12,45 @@ import AnyCodable public struct AnalyticsStatus: Codable { - public var popularPrefixQueries: Int? - public var nohitsPrefixQueries: Int? + public var docCounterEvents: Int? + public var docLogEvents: Int? public var logPrefixQueries: Int? - public var queryLogEvents: Int? + public var nohitsPrefixQueries: Int? + public var popularPrefixQueries: Int? public var queryCounterEvents: Int? - public var docLogEvents: Int? - public var docCounterEvents: Int? + public var queryLogEvents: Int? - public init(popularPrefixQueries: Int? = nil, nohitsPrefixQueries: Int? = nil, logPrefixQueries: Int? = nil, queryLogEvents: Int? = nil, queryCounterEvents: Int? = nil, docLogEvents: Int? = nil, docCounterEvents: Int? = nil) { - self.popularPrefixQueries = popularPrefixQueries - self.nohitsPrefixQueries = nohitsPrefixQueries + public init(docCounterEvents: Int? = nil, docLogEvents: Int? = nil, logPrefixQueries: Int? = nil, nohitsPrefixQueries: Int? = nil, popularPrefixQueries: Int? = nil, queryCounterEvents: Int? = nil, queryLogEvents: Int? = nil) { + self.docCounterEvents = docCounterEvents + self.docLogEvents = docLogEvents self.logPrefixQueries = logPrefixQueries - self.queryLogEvents = queryLogEvents + self.nohitsPrefixQueries = nohitsPrefixQueries + self.popularPrefixQueries = popularPrefixQueries self.queryCounterEvents = queryCounterEvents - self.docLogEvents = docLogEvents - self.docCounterEvents = docCounterEvents + self.queryLogEvents = queryLogEvents } public enum CodingKeys: String, CodingKey, CaseIterable { - case popularPrefixQueries = "popular_prefix_queries" - case nohitsPrefixQueries = "nohits_prefix_queries" + case docCounterEvents = "doc_counter_events" + case docLogEvents = "doc_log_events" case logPrefixQueries = "log_prefix_queries" - case queryLogEvents = "query_log_events" + case nohitsPrefixQueries = "nohits_prefix_queries" + case popularPrefixQueries = "popular_prefix_queries" case queryCounterEvents = "query_counter_events" - case docLogEvents = "doc_log_events" - case docCounterEvents = "doc_counter_events" + case queryLogEvents = "query_log_events" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(popularPrefixQueries, forKey: .popularPrefixQueries) - try container.encodeIfPresent(nohitsPrefixQueries, forKey: .nohitsPrefixQueries) + try container.encodeIfPresent(docCounterEvents, forKey: .docCounterEvents) + try container.encodeIfPresent(docLogEvents, forKey: .docLogEvents) try container.encodeIfPresent(logPrefixQueries, forKey: .logPrefixQueries) - try container.encodeIfPresent(queryLogEvents, forKey: .queryLogEvents) + try container.encodeIfPresent(nohitsPrefixQueries, forKey: .nohitsPrefixQueries) + try container.encodeIfPresent(popularPrefixQueries, forKey: .popularPrefixQueries) try container.encodeIfPresent(queryCounterEvents, forKey: .queryCounterEvents) - try container.encodeIfPresent(docLogEvents, forKey: .docLogEvents) - try container.encodeIfPresent(docCounterEvents, forKey: .docCounterEvents) + try container.encodeIfPresent(queryLogEvents, forKey: .queryLogEvents) } } diff --git a/Sources/Typesense/Models/ApiKey.swift b/Sources/Typesense/Models/ApiKey.swift index 55f37c3..3214956 100644 --- a/Sources/Typesense/Models/ApiKey.swift +++ b/Sources/Typesense/Models/ApiKey.swift @@ -12,30 +12,30 @@ import AnyCodable public struct ApiKey: Codable { - public var value: String? - public var description: String public var actions: [String] public var collections: [String] + public var description: String public var expiresAt: Int64? + public var value: String? public var id: Int64? public var valuePrefix: String? - public init(value: String? = nil, description: String, actions: [String], collections: [String], expiresAt: Int64? = nil, id: Int64? = nil, valuePrefix: String? = nil) { - self.value = value - self.description = description + public init(actions: [String], collections: [String], description: String, expiresAt: Int64? = nil, value: String? = nil, id: Int64? = nil, valuePrefix: String? = nil) { self.actions = actions self.collections = collections + self.description = description self.expiresAt = expiresAt + self.value = value self.id = id self.valuePrefix = valuePrefix } public enum CodingKeys: String, CodingKey, CaseIterable { - case value - case description case actions case collections + case description case expiresAt = "expires_at" + case value case id case valuePrefix = "value_prefix" } @@ -44,11 +44,11 @@ public struct ApiKey: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(value, forKey: .value) - try container.encode(description, forKey: .description) try container.encode(actions, forKey: .actions) try container.encode(collections, forKey: .collections) + try container.encode(description, forKey: .description) try container.encodeIfPresent(expiresAt, forKey: .expiresAt) + try container.encodeIfPresent(value, forKey: .value) try container.encodeIfPresent(id, forKey: .id) try container.encodeIfPresent(valuePrefix, forKey: .valuePrefix) } diff --git a/Sources/Typesense/Models/ApiKeySchema.swift b/Sources/Typesense/Models/ApiKeySchema.swift index 40eccb6..82b5723 100644 --- a/Sources/Typesense/Models/ApiKeySchema.swift +++ b/Sources/Typesense/Models/ApiKeySchema.swift @@ -12,37 +12,37 @@ import AnyCodable public struct ApiKeySchema: Codable { - public var value: String? - public var description: String public var actions: [String] public var collections: [String] + public var description: String public var expiresAt: Int64? + public var value: String? - public init(value: String? = nil, description: String, actions: [String], collections: [String], expiresAt: Int64? = nil) { - self.value = value - self.description = description + public init(actions: [String], collections: [String], description: String, expiresAt: Int64? = nil, value: String? = nil) { self.actions = actions self.collections = collections + self.description = description self.expiresAt = expiresAt + self.value = value } public enum CodingKeys: String, CodingKey, CaseIterable { - case value - case description case actions case collections + case description case expiresAt = "expires_at" + case value } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(value, forKey: .value) - try container.encode(description, forKey: .description) try container.encode(actions, forKey: .actions) try container.encode(collections, forKey: .collections) + try container.encode(description, forKey: .description) try container.encodeIfPresent(expiresAt, forKey: .expiresAt) + try container.encodeIfPresent(value, forKey: .value) } } diff --git a/Sources/Typesense/Models/CollectionAlias.swift b/Sources/Typesense/Models/CollectionAlias.swift index 08f9bbe..1a39ceb 100644 --- a/Sources/Typesense/Models/CollectionAlias.swift +++ b/Sources/Typesense/Models/CollectionAlias.swift @@ -12,27 +12,27 @@ import AnyCodable public struct CollectionAlias: Codable { - /** Name of the collection alias */ - public var name: String /** Name of the collection the alias mapped to */ public var collectionName: String + /** Name of the collection alias */ + public var name: String - public init(name: String, collectionName: String) { - self.name = name + public init(collectionName: String, name: String) { self.collectionName = collectionName + self.name = name } public enum CodingKeys: String, CodingKey, CaseIterable { - case name case collectionName = "collection_name" + case name } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(name, forKey: .name) try container.encode(collectionName, forKey: .collectionName) + try container.encode(name, forKey: .name) } } diff --git a/Sources/Typesense/Models/CollectionResponse.swift b/Sources/Typesense/Models/CollectionResponse.swift index f1ec6ab..56a30da 100644 --- a/Sources/Typesense/Models/CollectionResponse.swift +++ b/Sources/Typesense/Models/CollectionResponse.swift @@ -12,71 +12,71 @@ import AnyCodable public struct CollectionResponse: Codable { - /** Name of the collection */ - public var name: String - /** A list of fields for querying, filtering and faceting */ - public var fields: [Field] /** 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. */ public var defaultSortingField: String? = "" - /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ - public var tokenSeparators: [String]? - /** List of synonym set names to associate with this collection */ - public var synonymSets: [String]? /** 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. */ public var enableNestedFields: Bool? = false + /** A list of fields for querying, filtering and faceting */ + public var fields: [Field] + /** Optional details about the collection, e.g., when it was created, who created it etc. */ + public var metadata: AnyCodable? + /** Name of the collection */ + public var name: String /** List of symbols or special characters to be indexed. */ public var symbolsToIndex: [String]? + /** List of synonym set names to associate with this collection */ + public var synonymSets: [String]? + /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ + public var tokenSeparators: [String]? public var voiceQueryModel: VoiceQueryModelCollectionConfig? - /** Optional details about the collection, e.g., when it was created, who created it etc. */ - public var metadata: AnyCodable? - /** Number of documents in the collection */ - public var numDocuments: Int64 /** Timestamp of when the collection was created (Unix epoch in seconds) */ public var createdAt: Int64 + /** Number of documents in the collection */ + public var numDocuments: Int64 - public init(name: String, fields: [Field], defaultSortingField: String? = "", tokenSeparators: [String]? = nil, synonymSets: [String]? = nil, enableNestedFields: Bool? = false, symbolsToIndex: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil, metadata: AnyCodable? = nil, numDocuments: Int64, createdAt: Int64) { - self.name = name - self.fields = fields + public init(defaultSortingField: String? = "", enableNestedFields: Bool? = false, fields: [Field], metadata: AnyCodable? = nil, name: String, symbolsToIndex: [String]? = nil, synonymSets: [String]? = nil, tokenSeparators: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil, createdAt: Int64, numDocuments: Int64) { self.defaultSortingField = defaultSortingField - self.tokenSeparators = tokenSeparators - self.synonymSets = synonymSets self.enableNestedFields = enableNestedFields + self.fields = fields + self.metadata = metadata + self.name = name self.symbolsToIndex = symbolsToIndex + self.synonymSets = synonymSets + self.tokenSeparators = tokenSeparators self.voiceQueryModel = voiceQueryModel - self.metadata = metadata - self.numDocuments = numDocuments self.createdAt = createdAt + self.numDocuments = numDocuments } public enum CodingKeys: String, CodingKey, CaseIterable { - case name - case fields case defaultSortingField = "default_sorting_field" - case tokenSeparators = "token_separators" - case synonymSets = "synonym_sets" case enableNestedFields = "enable_nested_fields" + case fields + case metadata + case name case symbolsToIndex = "symbols_to_index" + case synonymSets = "synonym_sets" + case tokenSeparators = "token_separators" case voiceQueryModel = "voice_query_model" - case metadata - case numDocuments = "num_documents" case createdAt = "created_at" + case numDocuments = "num_documents" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(name, forKey: .name) - try container.encode(fields, forKey: .fields) try container.encodeIfPresent(defaultSortingField, forKey: .defaultSortingField) - try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) - try container.encodeIfPresent(synonymSets, forKey: .synonymSets) try container.encodeIfPresent(enableNestedFields, forKey: .enableNestedFields) + try container.encode(fields, forKey: .fields) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encode(name, forKey: .name) try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) + try container.encodeIfPresent(synonymSets, forKey: .synonymSets) + try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) try container.encodeIfPresent(voiceQueryModel, forKey: .voiceQueryModel) - try container.encodeIfPresent(metadata, forKey: .metadata) - try container.encode(numDocuments, forKey: .numDocuments) try container.encode(createdAt, forKey: .createdAt) + try container.encode(numDocuments, forKey: .numDocuments) } } diff --git a/Sources/Typesense/Models/CollectionSchema.swift b/Sources/Typesense/Models/CollectionSchema.swift index a436050..e20ad31 100644 --- a/Sources/Typesense/Models/CollectionSchema.swift +++ b/Sources/Typesense/Models/CollectionSchema.swift @@ -12,61 +12,61 @@ import AnyCodable public struct CollectionSchema: Codable { - /** Name of the collection */ - public var name: String - /** A list of fields for querying, filtering and faceting */ - public var fields: [Field] /** 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. */ public var defaultSortingField: String? = "" - /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ - public var tokenSeparators: [String]? - /** List of synonym set names to associate with this collection */ - public var synonymSets: [String]? /** 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. */ public var enableNestedFields: Bool? = false + /** A list of fields for querying, filtering and faceting */ + public var fields: [Field] + /** Optional details about the collection, e.g., when it was created, who created it etc. */ + public var metadata: AnyCodable? + /** Name of the collection */ + public var name: String /** List of symbols or special characters to be indexed. */ public var symbolsToIndex: [String]? + /** List of synonym set names to associate with this collection */ + public var synonymSets: [String]? + /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ + public var tokenSeparators: [String]? public var voiceQueryModel: VoiceQueryModelCollectionConfig? - /** Optional details about the collection, e.g., when it was created, who created it etc. */ - public var metadata: AnyCodable? - public init(name: String, fields: [Field], defaultSortingField: String? = "", tokenSeparators: [String]? = nil, synonymSets: [String]? = nil, enableNestedFields: Bool? = false, symbolsToIndex: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil, metadata: AnyCodable? = nil) { - self.name = name - self.fields = fields + public init(defaultSortingField: String? = "", enableNestedFields: Bool? = false, fields: [Field], metadata: AnyCodable? = nil, name: String, symbolsToIndex: [String]? = nil, synonymSets: [String]? = nil, tokenSeparators: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil) { self.defaultSortingField = defaultSortingField - self.tokenSeparators = tokenSeparators - self.synonymSets = synonymSets self.enableNestedFields = enableNestedFields + self.fields = fields + self.metadata = metadata + self.name = name self.symbolsToIndex = symbolsToIndex + self.synonymSets = synonymSets + self.tokenSeparators = tokenSeparators self.voiceQueryModel = voiceQueryModel - self.metadata = metadata } public enum CodingKeys: String, CodingKey, CaseIterable { - case name - case fields case defaultSortingField = "default_sorting_field" - case tokenSeparators = "token_separators" - case synonymSets = "synonym_sets" case enableNestedFields = "enable_nested_fields" + case fields + case metadata + case name case symbolsToIndex = "symbols_to_index" + case synonymSets = "synonym_sets" + case tokenSeparators = "token_separators" case voiceQueryModel = "voice_query_model" - case metadata } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(name, forKey: .name) - try container.encode(fields, forKey: .fields) try container.encodeIfPresent(defaultSortingField, forKey: .defaultSortingField) - try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) - try container.encodeIfPresent(synonymSets, forKey: .synonymSets) try container.encodeIfPresent(enableNestedFields, forKey: .enableNestedFields) + try container.encode(fields, forKey: .fields) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encode(name, forKey: .name) try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) + try container.encodeIfPresent(synonymSets, forKey: .synonymSets) + try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) try container.encodeIfPresent(voiceQueryModel, forKey: .voiceQueryModel) - try container.encodeIfPresent(metadata, forKey: .metadata) } } diff --git a/Sources/Typesense/Models/CollectionUpdateSchema.swift b/Sources/Typesense/Models/CollectionUpdateSchema.swift index 66dcbcd..77211a2 100644 --- a/Sources/Typesense/Models/CollectionUpdateSchema.swift +++ b/Sources/Typesense/Models/CollectionUpdateSchema.swift @@ -14,21 +14,21 @@ public struct CollectionUpdateSchema: Codable { /** A list of fields for querying, filtering and faceting */ public var fields: [Field] - /** List of synonym set names to associate with this collection */ - public var synonymSets: [String]? /** Optional details about the collection, e.g., when it was created, who created it etc. */ public var metadata: AnyCodable? + /** List of synonym set names to associate with this collection */ + public var synonymSets: [String]? - public init(fields: [Field], synonymSets: [String]? = nil, metadata: AnyCodable? = nil) { + public init(fields: [Field], metadata: AnyCodable? = nil, synonymSets: [String]? = nil) { self.fields = fields - self.synonymSets = synonymSets self.metadata = metadata + self.synonymSets = synonymSets } public enum CodingKeys: String, CodingKey, CaseIterable { case fields - case synonymSets = "synonym_sets" case metadata + case synonymSets = "synonym_sets" } // Encodable protocol methods @@ -36,8 +36,8 @@ public struct CollectionUpdateSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(fields, forKey: .fields) - try container.encodeIfPresent(synonymSets, forKey: .synonymSets) try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encodeIfPresent(synonymSets, forKey: .synonymSets) } } diff --git a/Sources/Typesense/Models/ConversationModelCreateSchema.swift b/Sources/Typesense/Models/ConversationModelCreateSchema.swift index e4b8030..2082789 100644 --- a/Sources/Typesense/Models/ConversationModelCreateSchema.swift +++ b/Sources/Typesense/Models/ConversationModelCreateSchema.swift @@ -12,46 +12,46 @@ import AnyCodable public struct ConversationModelCreateSchema: Codable { - /** An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. */ - public var id: String? - /** Name of the LLM model offered by OpenAI, Cloudflare or vLLM */ - public var modelName: String + /** LLM service's account ID (only applicable for Cloudflare) */ + public var accountId: String? /** The LLM service's API Key */ public var apiKey: String? /** Typesense collection that stores the historical conversations */ public var historyCollection: String - /** LLM service's account ID (only applicable for Cloudflare) */ - public var accountId: String? + /** An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. */ + public var id: String? + /** 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. */ + public var maxBytes: Int + /** Name of the LLM model offered by OpenAI, Cloudflare or vLLM */ + public var modelName: String /** The system prompt that contains special instructions to the LLM */ public var systemPrompt: String? /** Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) */ public var ttl: Int? - /** 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. */ - public var maxBytes: Int /** URL of vLLM service */ public var vllmUrl: String? - public init(id: String? = nil, modelName: String, apiKey: String? = nil, historyCollection: String, accountId: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, maxBytes: Int, vllmUrl: String? = nil) { - self.id = id - self.modelName = modelName + public init(accountId: String? = nil, apiKey: String? = nil, historyCollection: String, id: String? = nil, maxBytes: Int, modelName: String, systemPrompt: String? = nil, ttl: Int? = nil, vllmUrl: String? = nil) { + self.accountId = accountId self.apiKey = apiKey self.historyCollection = historyCollection - self.accountId = accountId + self.id = id + self.maxBytes = maxBytes + self.modelName = modelName self.systemPrompt = systemPrompt self.ttl = ttl - self.maxBytes = maxBytes self.vllmUrl = vllmUrl } public enum CodingKeys: String, CodingKey, CaseIterable { - case id - case modelName = "model_name" + case accountId = "account_id" case apiKey = "api_key" case historyCollection = "history_collection" - case accountId = "account_id" + case id + case maxBytes = "max_bytes" + case modelName = "model_name" case systemPrompt = "system_prompt" case ttl - case maxBytes = "max_bytes" case vllmUrl = "vllm_url" } @@ -59,14 +59,14 @@ public struct ConversationModelCreateSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(id, forKey: .id) - try container.encode(modelName, forKey: .modelName) + try container.encodeIfPresent(accountId, forKey: .accountId) try container.encodeIfPresent(apiKey, forKey: .apiKey) try container.encode(historyCollection, forKey: .historyCollection) - try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(maxBytes, forKey: .maxBytes) + try container.encode(modelName, forKey: .modelName) try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) try container.encodeIfPresent(ttl, forKey: .ttl) - try container.encode(maxBytes, forKey: .maxBytes) try container.encodeIfPresent(vllmUrl, forKey: .vllmUrl) } } diff --git a/Sources/Typesense/Models/ConversationModelSchema.swift b/Sources/Typesense/Models/ConversationModelSchema.swift index c4389c9..069e835 100644 --- a/Sources/Typesense/Models/ConversationModelSchema.swift +++ b/Sources/Typesense/Models/ConversationModelSchema.swift @@ -12,46 +12,46 @@ import AnyCodable public struct ConversationModelSchema: Codable { - /** An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. */ - public var id: String - /** Name of the LLM model offered by OpenAI, Cloudflare or vLLM */ - public var modelName: String + /** LLM service's account ID (only applicable for Cloudflare) */ + public var accountId: String? /** The LLM service's API Key */ public var apiKey: String? /** Typesense collection that stores the historical conversations */ public var historyCollection: String - /** LLM service's account ID (only applicable for Cloudflare) */ - public var accountId: String? + /** An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. */ + public var id: String + /** 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. */ + public var maxBytes: Int + /** Name of the LLM model offered by OpenAI, Cloudflare or vLLM */ + public var modelName: String /** The system prompt that contains special instructions to the LLM */ public var systemPrompt: String? /** Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) */ public var ttl: Int? - /** 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. */ - public var maxBytes: Int /** URL of vLLM service */ public var vllmUrl: String? - public init(id: String, modelName: String, apiKey: String? = nil, historyCollection: String, accountId: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, maxBytes: Int, vllmUrl: String? = nil) { - self.id = id - self.modelName = modelName + public init(accountId: String? = nil, apiKey: String? = nil, historyCollection: String, id: String, maxBytes: Int, modelName: String, systemPrompt: String? = nil, ttl: Int? = nil, vllmUrl: String? = nil) { + self.accountId = accountId self.apiKey = apiKey self.historyCollection = historyCollection - self.accountId = accountId + self.id = id + self.maxBytes = maxBytes + self.modelName = modelName self.systemPrompt = systemPrompt self.ttl = ttl - self.maxBytes = maxBytes self.vllmUrl = vllmUrl } public enum CodingKeys: String, CodingKey, CaseIterable { - case id - case modelName = "model_name" + case accountId = "account_id" case apiKey = "api_key" case historyCollection = "history_collection" - case accountId = "account_id" + case id + case maxBytes = "max_bytes" + case modelName = "model_name" case systemPrompt = "system_prompt" case ttl - case maxBytes = "max_bytes" case vllmUrl = "vllm_url" } @@ -59,14 +59,14 @@ public struct ConversationModelSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(id, forKey: .id) - try container.encode(modelName, forKey: .modelName) + try container.encodeIfPresent(accountId, forKey: .accountId) try container.encodeIfPresent(apiKey, forKey: .apiKey) try container.encode(historyCollection, forKey: .historyCollection) - try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encode(id, forKey: .id) + try container.encode(maxBytes, forKey: .maxBytes) + try container.encode(modelName, forKey: .modelName) try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) try container.encodeIfPresent(ttl, forKey: .ttl) - try container.encode(maxBytes, forKey: .maxBytes) try container.encodeIfPresent(vllmUrl, forKey: .vllmUrl) } } diff --git a/Sources/Typesense/Models/ConversationModelUpdateSchema.swift b/Sources/Typesense/Models/ConversationModelUpdateSchema.swift index 05a764c..30a0500 100644 --- a/Sources/Typesense/Models/ConversationModelUpdateSchema.swift +++ b/Sources/Typesense/Models/ConversationModelUpdateSchema.swift @@ -12,46 +12,46 @@ import AnyCodable public struct ConversationModelUpdateSchema: Codable { - /** An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. */ - public var id: String? - /** Name of the LLM model offered by OpenAI, Cloudflare or vLLM */ - public var modelName: String? + /** LLM service's account ID (only applicable for Cloudflare) */ + public var accountId: String? /** The LLM service's API Key */ public var apiKey: String? /** Typesense collection that stores the historical conversations */ public var historyCollection: String? - /** LLM service's account ID (only applicable for Cloudflare) */ - public var accountId: String? + /** An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. */ + public var id: String? + /** 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. */ + public var maxBytes: Int? + /** Name of the LLM model offered by OpenAI, Cloudflare or vLLM */ + public var modelName: String? /** The system prompt that contains special instructions to the LLM */ public var systemPrompt: String? /** Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) */ public var ttl: Int? - /** 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. */ - public var maxBytes: Int? /** URL of vLLM service */ public var vllmUrl: String? - public init(id: String? = nil, modelName: String? = nil, apiKey: String? = nil, historyCollection: String? = nil, accountId: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, maxBytes: Int? = nil, vllmUrl: String? = nil) { - self.id = id - self.modelName = modelName + public init(accountId: String? = nil, apiKey: String? = nil, historyCollection: String? = nil, id: String? = nil, maxBytes: Int? = nil, modelName: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, vllmUrl: String? = nil) { + self.accountId = accountId self.apiKey = apiKey self.historyCollection = historyCollection - self.accountId = accountId + self.id = id + self.maxBytes = maxBytes + self.modelName = modelName self.systemPrompt = systemPrompt self.ttl = ttl - self.maxBytes = maxBytes self.vllmUrl = vllmUrl } public enum CodingKeys: String, CodingKey, CaseIterable { - case id - case modelName = "model_name" + case accountId = "account_id" case apiKey = "api_key" case historyCollection = "history_collection" - case accountId = "account_id" + case id + case maxBytes = "max_bytes" + case modelName = "model_name" case systemPrompt = "system_prompt" case ttl - case maxBytes = "max_bytes" case vllmUrl = "vllm_url" } @@ -59,14 +59,14 @@ public struct ConversationModelUpdateSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(id, forKey: .id) - try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(accountId, forKey: .accountId) try container.encodeIfPresent(apiKey, forKey: .apiKey) try container.encodeIfPresent(historyCollection, forKey: .historyCollection) - try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(maxBytes, forKey: .maxBytes) + try container.encodeIfPresent(modelName, forKey: .modelName) try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) try container.encodeIfPresent(ttl, forKey: .ttl) - try container.encodeIfPresent(maxBytes, forKey: .maxBytes) try container.encodeIfPresent(vllmUrl, forKey: .vllmUrl) } } diff --git a/Sources/Typesense/Models/CreateAnalyticsRule200Response.swift b/Sources/Typesense/Models/CreateAnalyticsRule200Response.swift deleted file mode 100644 index 57120e6..0000000 --- a/Sources/Typesense/Models/CreateAnalyticsRule200Response.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// CreateAnalyticsRule200Response.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation -#if canImport(AnyCodable) -import AnyCodable -#endif - -public enum CreateAnalyticsRule200Response: Codable, JSONEncodable { - case typeAnalyticsRule(AnalyticsRule) - case type[CreateAnalyticsRule200ResponseOneOfInner]([CreateAnalyticsRule200ResponseOneOfInner]) - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - switch self { - case .typeAnalyticsRule(let value): - try container.encode(value) - case .type[CreateAnalyticsRule200ResponseOneOfInner](let value): - try container.encode(value) - } - } - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - if let value = try? container.decode(AnalyticsRule.self) { - self = .typeAnalyticsRule(value) - } else if let value = try? container.decode([CreateAnalyticsRule200ResponseOneOfInner].self) { - self = .type[CreateAnalyticsRule200ResponseOneOfInner](value) - } else { - throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of CreateAnalyticsRule200Response")) - } - } -} - diff --git a/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInner.swift b/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInner.swift deleted file mode 100644 index c631685..0000000 --- a/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInner.swift +++ /dev/null @@ -1,62 +0,0 @@ -// -// CreateAnalyticsRule200ResponseOneOfInner.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation -#if canImport(AnyCodable) -import AnyCodable -#endif - -public struct CreateAnalyticsRule200ResponseOneOfInner: Codable { - - public enum ModelType: String, Codable, CaseIterable { - case popularQueries = "popular_queries" - case nohitsQueries = "nohits_queries" - case counter = "counter" - case log = "log" - } - public var name: String - public var type: ModelType - public var collection: String - public var eventType: String - public var ruleTag: String? - public var params: AnalyticsRuleCreateParams? - public var error: String? - - public init(name: String, type: ModelType, collection: String, eventType: String, ruleTag: String? = nil, params: AnalyticsRuleCreateParams? = nil, error: String? = nil) { - self.name = name - self.type = type - self.collection = collection - self.eventType = eventType - self.ruleTag = ruleTag - self.params = params - self.error = error - } - - public enum CodingKeys: String, CodingKey, CaseIterable { - case name - case type - case collection - case eventType = "event_type" - case ruleTag = "rule_tag" - case params - case error - } - - // Encodable protocol methods - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(name, forKey: .name) - try container.encode(type, forKey: .type) - try container.encode(collection, forKey: .collection) - try container.encode(eventType, forKey: .eventType) - try container.encodeIfPresent(ruleTag, forKey: .ruleTag) - try container.encodeIfPresent(params, forKey: .params) - try container.encodeIfPresent(error, forKey: .error) - } -} - diff --git a/Sources/Typesense/Models/CreateAnalyticsRuleRequest.swift b/Sources/Typesense/Models/CreateAnalyticsRuleRequest.swift deleted file mode 100644 index 025873c..0000000 --- a/Sources/Typesense/Models/CreateAnalyticsRuleRequest.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// CreateAnalyticsRuleRequest.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation -#if canImport(AnyCodable) -import AnyCodable -#endif - -public enum CreateAnalyticsRuleRequest: Codable, JSONEncodable { - case typeAnalyticsRuleCreate(AnalyticsRuleCreate) - case type[AnalyticsRuleCreate]([AnalyticsRuleCreate]) - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - switch self { - case .typeAnalyticsRuleCreate(let value): - try container.encode(value) - case .type[AnalyticsRuleCreate](let value): - try container.encode(value) - } - } - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - if let value = try? container.decode(AnalyticsRuleCreate.self) { - self = .typeAnalyticsRuleCreate(value) - } else if let value = try? container.decode([AnalyticsRuleCreate].self) { - self = .type[AnalyticsRuleCreate](value) - } else { - throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of CreateAnalyticsRuleRequest")) - } - } -} - diff --git a/Sources/Typesense/Models/CurationItemCreateSchema.swift b/Sources/Typesense/Models/CurationItemCreateSchema.swift index 59f666f..5f2d6d1 100644 --- a/Sources/Typesense/Models/CurationItemCreateSchema.swift +++ b/Sources/Typesense/Models/CurationItemCreateSchema.swift @@ -12,81 +12,81 @@ import AnyCodable public struct CurationItemCreateSchema: Codable { - public var rule: CurationRule - /** List of document `id`s that should be included in the search results with their corresponding `position`s. */ - public var includes: [CurationInclude]? + /** A Unix timestamp that indicates the date/time from which the curation will be active. You can use this to create rules that start applying from a future point in time. */ + public var effectiveFromTs: Int? + /** A Unix timestamp that indicates the date/time until which the curation will be active. You can use this to create rules that stop applying after a period of time. */ + public var effectiveToTs: Int? /** List of document `id`s that should be excluded from the search results. */ public var excludes: [CurationExclude]? /** A filter by clause that is applied to any search query that matches the curation rule. */ public var filterBy: String? - /** Indicates whether search query tokens that exist in the curation's rule should be removed from the search query. */ - public var removeMatchedTokens: Bool? + /** When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. */ + public var filterCuratedHits: Bool? + /** ID of the curation item */ + public var id: String? + /** List of document `id`s that should be included in the search results with their corresponding `position`s. */ + public var includes: [CurationInclude]? /** 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. */ public var metadata: AnyCodable? - /** A sort by clause that is applied to any search query that matches the curation rule. */ - public var sortBy: String? + /** Indicates whether search query tokens that exist in the curation's rule should be removed from the search query. */ + public var removeMatchedTokens: Bool? /** Replaces the current search query with this value, when the search query matches the curation rule. */ public var replaceQuery: String? - /** When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. */ - public var filterCuratedHits: Bool? - /** A Unix timestamp that indicates the date/time from which the curation will be active. You can use this to create rules that start applying from a future point in time. */ - public var effectiveFromTs: Int? - /** A Unix timestamp that indicates the date/time until which the curation will be active. You can use this to create rules that stop applying after a period of time. */ - public var effectiveToTs: Int? + public var rule: CurationRule + /** A sort by clause that is applied to any search query that matches the curation rule. */ + public var sortBy: String? /** When set to true, curation processing will stop at the first matching rule. When set to false curation processing will continue and multiple curation actions will be triggered in sequence. Curations are processed in the lexical sort order of their id field. */ public var stopProcessing: Bool? - /** ID of the curation item */ - public var id: String? - public init(rule: CurationRule, includes: [CurationInclude]? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, removeMatchedTokens: Bool? = nil, metadata: AnyCodable? = nil, sortBy: String? = nil, replaceQuery: String? = nil, filterCuratedHits: Bool? = nil, effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, stopProcessing: Bool? = nil, id: String? = nil) { - self.rule = rule - self.includes = includes + public init(effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, id: String? = nil, includes: [CurationInclude]? = nil, metadata: AnyCodable? = nil, removeMatchedTokens: Bool? = nil, replaceQuery: String? = nil, rule: CurationRule, sortBy: String? = nil, stopProcessing: Bool? = nil) { + self.effectiveFromTs = effectiveFromTs + self.effectiveToTs = effectiveToTs self.excludes = excludes self.filterBy = filterBy - self.removeMatchedTokens = removeMatchedTokens + self.filterCuratedHits = filterCuratedHits + self.id = id + self.includes = includes self.metadata = metadata - self.sortBy = sortBy + self.removeMatchedTokens = removeMatchedTokens self.replaceQuery = replaceQuery - self.filterCuratedHits = filterCuratedHits - self.effectiveFromTs = effectiveFromTs - self.effectiveToTs = effectiveToTs + self.rule = rule + self.sortBy = sortBy self.stopProcessing = stopProcessing - self.id = id } public enum CodingKeys: String, CodingKey, CaseIterable { - case rule - case includes + case effectiveFromTs = "effective_from_ts" + case effectiveToTs = "effective_to_ts" case excludes case filterBy = "filter_by" - case removeMatchedTokens = "remove_matched_tokens" + case filterCuratedHits = "filter_curated_hits" + case id + case includes case metadata - case sortBy = "sort_by" + case removeMatchedTokens = "remove_matched_tokens" case replaceQuery = "replace_query" - case filterCuratedHits = "filter_curated_hits" - case effectiveFromTs = "effective_from_ts" - case effectiveToTs = "effective_to_ts" + case rule + case sortBy = "sort_by" case stopProcessing = "stop_processing" - case id } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(rule, forKey: .rule) - try container.encodeIfPresent(includes, forKey: .includes) + try container.encodeIfPresent(effectiveFromTs, forKey: .effectiveFromTs) + try container.encodeIfPresent(effectiveToTs, forKey: .effectiveToTs) try container.encodeIfPresent(excludes, forKey: .excludes) try container.encodeIfPresent(filterBy, forKey: .filterBy) - try container.encodeIfPresent(removeMatchedTokens, forKey: .removeMatchedTokens) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(includes, forKey: .includes) try container.encodeIfPresent(metadata, forKey: .metadata) - try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(removeMatchedTokens, forKey: .removeMatchedTokens) try container.encodeIfPresent(replaceQuery, forKey: .replaceQuery) - try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) - try container.encodeIfPresent(effectiveFromTs, forKey: .effectiveFromTs) - try container.encodeIfPresent(effectiveToTs, forKey: .effectiveToTs) + try container.encode(rule, forKey: .rule) + try container.encodeIfPresent(sortBy, forKey: .sortBy) try container.encodeIfPresent(stopProcessing, forKey: .stopProcessing) - try container.encodeIfPresent(id, forKey: .id) } } diff --git a/Sources/Typesense/Models/CurationItemSchema.swift b/Sources/Typesense/Models/CurationItemSchema.swift index 63a5cfc..63d4a56 100644 --- a/Sources/Typesense/Models/CurationItemSchema.swift +++ b/Sources/Typesense/Models/CurationItemSchema.swift @@ -12,80 +12,80 @@ import AnyCodable public struct CurationItemSchema: Codable { - public var rule: CurationRule - /** List of document `id`s that should be included in the search results with their corresponding `position`s. */ - public var includes: [CurationInclude]? + /** A Unix timestamp that indicates the date/time from which the curation will be active. You can use this to create rules that start applying from a future point in time. */ + public var effectiveFromTs: Int? + /** A Unix timestamp that indicates the date/time until which the curation will be active. You can use this to create rules that stop applying after a period of time. */ + public var effectiveToTs: Int? /** List of document `id`s that should be excluded from the search results. */ public var excludes: [CurationExclude]? /** A filter by clause that is applied to any search query that matches the curation rule. */ public var filterBy: String? - /** Indicates whether search query tokens that exist in the curation's rule should be removed from the search query. */ - public var removeMatchedTokens: Bool? + /** When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. */ + public var filterCuratedHits: Bool? + public var id: String + /** List of document `id`s that should be included in the search results with their corresponding `position`s. */ + public var includes: [CurationInclude]? /** 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. */ public var metadata: AnyCodable? - /** A sort by clause that is applied to any search query that matches the curation rule. */ - public var sortBy: String? + /** Indicates whether search query tokens that exist in the curation's rule should be removed from the search query. */ + public var removeMatchedTokens: Bool? /** Replaces the current search query with this value, when the search query matches the curation rule. */ public var replaceQuery: String? - /** When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. */ - public var filterCuratedHits: Bool? - /** A Unix timestamp that indicates the date/time from which the curation will be active. You can use this to create rules that start applying from a future point in time. */ - public var effectiveFromTs: Int? - /** A Unix timestamp that indicates the date/time until which the curation will be active. You can use this to create rules that stop applying after a period of time. */ - public var effectiveToTs: Int? + public var rule: CurationRule + /** A sort by clause that is applied to any search query that matches the curation rule. */ + public var sortBy: String? /** When set to true, curation processing will stop at the first matching rule. When set to false curation processing will continue and multiple curation actions will be triggered in sequence. Curations are processed in the lexical sort order of their id field. */ public var stopProcessing: Bool? - public var id: String - public init(rule: CurationRule, includes: [CurationInclude]? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, removeMatchedTokens: Bool? = nil, metadata: AnyCodable? = nil, sortBy: String? = nil, replaceQuery: String? = nil, filterCuratedHits: Bool? = nil, effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, stopProcessing: Bool? = nil, id: String) { - self.rule = rule - self.includes = includes + public init(effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, id: String, includes: [CurationInclude]? = nil, metadata: AnyCodable? = nil, removeMatchedTokens: Bool? = nil, replaceQuery: String? = nil, rule: CurationRule, sortBy: String? = nil, stopProcessing: Bool? = nil) { + self.effectiveFromTs = effectiveFromTs + self.effectiveToTs = effectiveToTs self.excludes = excludes self.filterBy = filterBy - self.removeMatchedTokens = removeMatchedTokens + self.filterCuratedHits = filterCuratedHits + self.id = id + self.includes = includes self.metadata = metadata - self.sortBy = sortBy + self.removeMatchedTokens = removeMatchedTokens self.replaceQuery = replaceQuery - self.filterCuratedHits = filterCuratedHits - self.effectiveFromTs = effectiveFromTs - self.effectiveToTs = effectiveToTs + self.rule = rule + self.sortBy = sortBy self.stopProcessing = stopProcessing - self.id = id } public enum CodingKeys: String, CodingKey, CaseIterable { - case rule - case includes + case effectiveFromTs = "effective_from_ts" + case effectiveToTs = "effective_to_ts" case excludes case filterBy = "filter_by" - case removeMatchedTokens = "remove_matched_tokens" + case filterCuratedHits = "filter_curated_hits" + case id + case includes case metadata - case sortBy = "sort_by" + case removeMatchedTokens = "remove_matched_tokens" case replaceQuery = "replace_query" - case filterCuratedHits = "filter_curated_hits" - case effectiveFromTs = "effective_from_ts" - case effectiveToTs = "effective_to_ts" + case rule + case sortBy = "sort_by" case stopProcessing = "stop_processing" - case id } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(rule, forKey: .rule) - try container.encodeIfPresent(includes, forKey: .includes) + try container.encodeIfPresent(effectiveFromTs, forKey: .effectiveFromTs) + try container.encodeIfPresent(effectiveToTs, forKey: .effectiveToTs) try container.encodeIfPresent(excludes, forKey: .excludes) try container.encodeIfPresent(filterBy, forKey: .filterBy) - try container.encodeIfPresent(removeMatchedTokens, forKey: .removeMatchedTokens) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) + try container.encode(id, forKey: .id) + try container.encodeIfPresent(includes, forKey: .includes) try container.encodeIfPresent(metadata, forKey: .metadata) - try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(removeMatchedTokens, forKey: .removeMatchedTokens) try container.encodeIfPresent(replaceQuery, forKey: .replaceQuery) - try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) - try container.encodeIfPresent(effectiveFromTs, forKey: .effectiveFromTs) - try container.encodeIfPresent(effectiveToTs, forKey: .effectiveToTs) + try container.encode(rule, forKey: .rule) + try container.encodeIfPresent(sortBy, forKey: .sortBy) try container.encodeIfPresent(stopProcessing, forKey: .stopProcessing) - try container.encode(id, forKey: .id) } } diff --git a/Sources/Typesense/Models/CurationRule.swift b/Sources/Typesense/Models/CurationRule.swift index 64245d7..16b81bc 100644 --- a/Sources/Typesense/Models/CurationRule.swift +++ b/Sources/Typesense/Models/CurationRule.swift @@ -16,37 +16,37 @@ public struct CurationRule: Codable { case exact = "exact" case contains = "contains" } - /** List of tag values to associate with this curation rule. */ - public var tags: [String]? - /** Indicates what search queries should be curated */ - public var 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. */ - public var match: Match? /** Indicates that the curation should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). */ public var filterBy: 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. */ + public var match: Match? + /** Indicates what search queries should be curated */ + public var query: String? + /** List of tag values to associate with this curation rule. */ + public var tags: [String]? - public init(tags: [String]? = nil, query: String? = nil, match: Match? = nil, filterBy: String? = nil) { - self.tags = tags - self.query = query - self.match = match + public init(filterBy: String? = nil, match: Match? = nil, query: String? = nil, tags: [String]? = nil) { self.filterBy = filterBy + self.match = match + self.query = query + self.tags = tags } public enum CodingKeys: String, CodingKey, CaseIterable { - case tags - case query - case match case filterBy = "filter_by" + case match + case query + case tags } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(tags, forKey: .tags) - try container.encodeIfPresent(query, forKey: .query) - try container.encodeIfPresent(match, forKey: .match) try container.encodeIfPresent(filterBy, forKey: .filterBy) + try container.encodeIfPresent(match, forKey: .match) + try container.encodeIfPresent(query, forKey: .query) + try container.encodeIfPresent(tags, forKey: .tags) } } diff --git a/Sources/Typesense/Models/CurationSetCreateSchema.swift b/Sources/Typesense/Models/CurationSetCreateSchema.swift index 2663c86..bec7cd2 100644 --- a/Sources/Typesense/Models/CurationSetCreateSchema.swift +++ b/Sources/Typesense/Models/CurationSetCreateSchema.swift @@ -12,27 +12,27 @@ import AnyCodable public struct CurationSetCreateSchema: Codable { - /** Array of curation items */ - public var items: [CurationItemCreateSchema] /** Optional description for the curation set */ public var description: String? + /** Array of curation items */ + public var items: [CurationItemCreateSchema] - public init(items: [CurationItemCreateSchema], description: String? = nil) { - self.items = items + public init(description: String? = nil, items: [CurationItemCreateSchema]) { self.description = description + self.items = items } public enum CodingKeys: String, CodingKey, CaseIterable { - case items case description + case items } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(items, forKey: .items) try container.encodeIfPresent(description, forKey: .description) + try container.encode(items, forKey: .items) } } diff --git a/Sources/Typesense/Models/CurationSetSchema.swift b/Sources/Typesense/Models/CurationSetSchema.swift index b1edd35..dcd13d3 100644 --- a/Sources/Typesense/Models/CurationSetSchema.swift +++ b/Sources/Typesense/Models/CurationSetSchema.swift @@ -12,21 +12,21 @@ import AnyCodable public struct CurationSetSchema: Codable { - /** Array of curation items */ - public var items: [CurationItemCreateSchema] /** Optional description for the curation set */ public var description: String? + /** Array of curation items */ + public var items: [CurationItemCreateSchema] public var name: String - public init(items: [CurationItemCreateSchema], description: String? = nil, name: String) { - self.items = items + public init(description: String? = nil, items: [CurationItemCreateSchema], name: String) { self.description = description + self.items = items self.name = name } public enum CodingKeys: String, CodingKey, CaseIterable { - case items case description + case items case name } @@ -34,8 +34,8 @@ public struct CurationSetSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(items, forKey: .items) try container.encodeIfPresent(description, forKey: .description) + try container.encode(items, forKey: .items) try container.encode(name, forKey: .name) } } diff --git a/Sources/Typesense/Models/DeleteDocumentsDeleteDocumentsParametersParameter.swift b/Sources/Typesense/Models/DeleteDocumentsParameters.swift similarity index 88% rename from Sources/Typesense/Models/DeleteDocumentsDeleteDocumentsParametersParameter.swift rename to Sources/Typesense/Models/DeleteDocumentsParameters.swift index 509463a..f277651 100644 --- a/Sources/Typesense/Models/DeleteDocumentsDeleteDocumentsParametersParameter.swift +++ b/Sources/Typesense/Models/DeleteDocumentsParameters.swift @@ -1,5 +1,5 @@ // -// DeleteDocumentsDeleteDocumentsParametersParameter.swift +// DeleteDocumentsParameters.swift // // Generated by openapi-generator // https://openapi-generator.tech @@ -10,25 +10,25 @@ import Foundation import AnyCodable #endif -public struct DeleteDocumentsDeleteDocumentsParametersParameter: Codable { +public struct DeleteDocumentsParameters: Codable { - public var filterBy: 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. */ public var batchSize: Int? + public var filterBy: String public var ignoreNotFound: Bool? /** When true, removes all documents from the collection while preserving the collection and its schema. */ public var truncate: Bool? - public init(filterBy: String, batchSize: Int? = nil, ignoreNotFound: Bool? = nil, truncate: Bool? = nil) { - self.filterBy = filterBy + public init(batchSize: Int? = nil, filterBy: String, ignoreNotFound: Bool? = nil, truncate: Bool? = nil) { self.batchSize = batchSize + self.filterBy = filterBy self.ignoreNotFound = ignoreNotFound self.truncate = truncate } public enum CodingKeys: String, CodingKey, CaseIterable { - case filterBy = "filter_by" case batchSize = "batch_size" + case filterBy = "filter_by" case ignoreNotFound = "ignore_not_found" case truncate } @@ -37,8 +37,8 @@ public struct DeleteDocumentsDeleteDocumentsParametersParameter: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(filterBy, forKey: .filterBy) try container.encodeIfPresent(batchSize, forKey: .batchSize) + try container.encode(filterBy, forKey: .filterBy) try container.encodeIfPresent(ignoreNotFound, forKey: .ignoreNotFound) try container.encodeIfPresent(truncate, forKey: .truncate) } diff --git a/Sources/Typesense/Models/ExportDocumentsExportDocumentsParametersParameter.swift b/Sources/Typesense/Models/ExportDocumentsParameters.swift similarity index 83% rename from Sources/Typesense/Models/ExportDocumentsExportDocumentsParametersParameter.swift rename to Sources/Typesense/Models/ExportDocumentsParameters.swift index 7977a1b..da5f4ae 100644 --- a/Sources/Typesense/Models/ExportDocumentsExportDocumentsParametersParameter.swift +++ b/Sources/Typesense/Models/ExportDocumentsParameters.swift @@ -1,5 +1,5 @@ // -// ExportDocumentsExportDocumentsParametersParameter.swift +// ExportDocumentsParameters.swift // // Generated by openapi-generator // https://openapi-generator.tech @@ -10,34 +10,34 @@ import Foundation import AnyCodable #endif -public struct ExportDocumentsExportDocumentsParametersParameter: Codable { +public struct ExportDocumentsParameters: Codable { + /** List of fields from the document to exclude in the search result */ + public var excludeFields: String? /** Filter conditions for refining your search results. Separate multiple conditions with &&. */ public var filterBy: String? /** List of fields from the document to include in the search result */ public var includeFields: String? - /** List of fields from the document to exclude in the search result */ - public var excludeFields: String? - public init(filterBy: String? = nil, includeFields: String? = nil, excludeFields: String? = nil) { + public init(excludeFields: String? = nil, filterBy: String? = nil, includeFields: String? = nil) { + self.excludeFields = excludeFields self.filterBy = filterBy self.includeFields = includeFields - self.excludeFields = excludeFields } public enum CodingKeys: String, CodingKey, CaseIterable { + case excludeFields = "exclude_fields" case filterBy = "filter_by" case includeFields = "include_fields" - case excludeFields = "exclude_fields" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(excludeFields, forKey: .excludeFields) try container.encodeIfPresent(filterBy, forKey: .filterBy) try container.encodeIfPresent(includeFields, forKey: .includeFields) - try container.encodeIfPresent(excludeFields, forKey: .excludeFields) } } diff --git a/Sources/Typesense/Models/FacetCountsCountsInner.swift b/Sources/Typesense/Models/FacetCountsCountsInner.swift index 6228cfe..31c658e 100644 --- a/Sources/Typesense/Models/FacetCountsCountsInner.swift +++ b/Sources/Typesense/Models/FacetCountsCountsInner.swift @@ -14,21 +14,21 @@ public struct FacetCountsCountsInner: Codable { public var count: Int? public var highlighted: String? - public var value: String? public var parent: AnyCodable? + public var value: String? - public init(count: Int? = nil, highlighted: String? = nil, value: String? = nil, parent: AnyCodable? = nil) { + public init(count: Int? = nil, highlighted: String? = nil, parent: AnyCodable? = nil, value: String? = nil) { self.count = count self.highlighted = highlighted - self.value = value self.parent = parent + self.value = value } public enum CodingKeys: String, CodingKey, CaseIterable { case count case highlighted - case value case parent + case value } // Encodable protocol methods @@ -37,8 +37,8 @@ public struct FacetCountsCountsInner: Codable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(count, forKey: .count) try container.encodeIfPresent(highlighted, forKey: .highlighted) - try container.encodeIfPresent(value, forKey: .value) try container.encodeIfPresent(parent, forKey: .parent) + try container.encodeIfPresent(value, forKey: .value) } } diff --git a/Sources/Typesense/Models/FacetCountsStats.swift b/Sources/Typesense/Models/FacetCountsStats.swift index 780ba5c..56649a8 100644 --- a/Sources/Typesense/Models/FacetCountsStats.swift +++ b/Sources/Typesense/Models/FacetCountsStats.swift @@ -12,37 +12,37 @@ import AnyCodable public struct FacetCountsStats: Codable { + public var avg: Double? public var max: Double? public var min: Double? public var sum: Double? public var totalValues: Int? - public var avg: Double? - public init(max: Double? = nil, min: Double? = nil, sum: Double? = nil, totalValues: Int? = nil, avg: Double? = nil) { + public init(avg: Double? = nil, max: Double? = nil, min: Double? = nil, sum: Double? = nil, totalValues: Int? = nil) { + self.avg = avg self.max = max self.min = min self.sum = sum self.totalValues = totalValues - self.avg = avg } public enum CodingKeys: String, CodingKey, CaseIterable { + case avg case max case min case sum case totalValues = "total_values" - case avg } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(avg, forKey: .avg) try container.encodeIfPresent(max, forKey: .max) try container.encodeIfPresent(min, forKey: .min) try container.encodeIfPresent(sum, forKey: .sum) try container.encodeIfPresent(totalValues, forKey: .totalValues) - try container.encodeIfPresent(avg, forKey: .avg) } } diff --git a/Sources/Typesense/Models/Field.swift b/Sources/Typesense/Models/Field.swift index 6244553..b2cee30 100644 --- a/Sources/Typesense/Models/Field.swift +++ b/Sources/Typesense/Models/Field.swift @@ -12,101 +12,101 @@ import AnyCodable public struct Field: Codable { - public var name: String - public var type: String - public var _optional: Bool? + public var drop: Bool? + public var embed: FieldEmbed? public var facet: Bool? public var index: Bool? = true - public var locale: String? - public var sort: Bool? public var _infix: Bool? = false - /** Name of a field in another collection that should be linked to this collection so that it can be joined during query. */ - public var reference: String? + public var locale: String? + public var name: String public var numDim: Int? - public var drop: Bool? - /** When set to false, the field value will not be stored on disk. Default: true. */ - public var store: Bool? - /** The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. */ - public var vecDist: String? + public var _optional: Bool? /** Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. */ public var rangeIndex: Bool? + /** Name of a field in another collection that should be linked to this collection so that it can be joined during query. */ + public var reference: String? + public var sort: Bool? /** Values are stemmed before indexing in-memory. Default: false. */ public var stem: Bool? /** Name of the stemming dictionary to use for this field */ public var stemDictionary: String? - /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ - public var tokenSeparators: [String]? + /** When set to false, the field value will not be stored on disk. Default: true. */ + public var store: Bool? /** List of symbols or special characters to be indexed. */ public var symbolsToIndex: [String]? - public var embed: FieldEmbed? + /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ + public var tokenSeparators: [String]? + public var type: String + /** The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. */ + public var vecDist: String? - public init(name: String, type: String, _optional: Bool? = nil, facet: Bool? = nil, index: Bool? = true, locale: String? = nil, sort: Bool? = nil, _infix: Bool? = false, reference: String? = nil, numDim: Int? = nil, drop: Bool? = nil, store: Bool? = nil, vecDist: String? = nil, rangeIndex: Bool? = nil, stem: Bool? = nil, stemDictionary: String? = nil, tokenSeparators: [String]? = nil, symbolsToIndex: [String]? = nil, embed: FieldEmbed? = nil) { - self.name = name - self.type = type - self._optional = _optional + public init(drop: Bool? = nil, embed: FieldEmbed? = nil, facet: Bool? = nil, index: Bool? = true, _infix: Bool? = false, locale: String? = nil, name: String, numDim: Int? = nil, _optional: Bool? = nil, rangeIndex: Bool? = nil, reference: String? = nil, sort: Bool? = nil, stem: Bool? = nil, stemDictionary: String? = nil, store: Bool? = nil, symbolsToIndex: [String]? = nil, tokenSeparators: [String]? = nil, type: String, vecDist: String? = nil) { + self.drop = drop + self.embed = embed self.facet = facet self.index = index - self.locale = locale - self.sort = sort self._infix = _infix - self.reference = reference + self.locale = locale + self.name = name self.numDim = numDim - self.drop = drop - self.store = store - self.vecDist = vecDist + self._optional = _optional self.rangeIndex = rangeIndex + self.reference = reference + self.sort = sort self.stem = stem self.stemDictionary = stemDictionary - self.tokenSeparators = tokenSeparators + self.store = store self.symbolsToIndex = symbolsToIndex - self.embed = embed + self.tokenSeparators = tokenSeparators + self.type = type + self.vecDist = vecDist } public enum CodingKeys: String, CodingKey, CaseIterable { - case name - case type - case _optional = "optional" + case drop + case embed case facet case index - case locale - case sort case _infix = "infix" - case reference + case locale + case name case numDim = "num_dim" - case drop - case store - case vecDist = "vec_dist" + case _optional = "optional" case rangeIndex = "range_index" + case reference + case sort case stem case stemDictionary = "stem_dictionary" - case tokenSeparators = "token_separators" + case store case symbolsToIndex = "symbols_to_index" - case embed + case tokenSeparators = "token_separators" + case type + case vecDist = "vec_dist" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(name, forKey: .name) - try container.encode(type, forKey: .type) - try container.encodeIfPresent(_optional, forKey: ._optional) + try container.encodeIfPresent(drop, forKey: .drop) + try container.encodeIfPresent(embed, forKey: .embed) try container.encodeIfPresent(facet, forKey: .facet) try container.encodeIfPresent(index, forKey: .index) - try container.encodeIfPresent(locale, forKey: .locale) - try container.encodeIfPresent(sort, forKey: .sort) try container.encodeIfPresent(_infix, forKey: ._infix) - try container.encodeIfPresent(reference, forKey: .reference) + try container.encodeIfPresent(locale, forKey: .locale) + try container.encode(name, forKey: .name) try container.encodeIfPresent(numDim, forKey: .numDim) - try container.encodeIfPresent(drop, forKey: .drop) - try container.encodeIfPresent(store, forKey: .store) - try container.encodeIfPresent(vecDist, forKey: .vecDist) + try container.encodeIfPresent(_optional, forKey: ._optional) try container.encodeIfPresent(rangeIndex, forKey: .rangeIndex) + try container.encodeIfPresent(reference, forKey: .reference) + try container.encodeIfPresent(sort, forKey: .sort) try container.encodeIfPresent(stem, forKey: .stem) try container.encodeIfPresent(stemDictionary, forKey: .stemDictionary) - try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) + try container.encodeIfPresent(store, forKey: .store) try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) - try container.encodeIfPresent(embed, forKey: .embed) + try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) + try container.encode(type, forKey: .type) + try container.encodeIfPresent(vecDist, forKey: .vecDist) } } diff --git a/Sources/Typesense/Models/FieldEmbedModelConfig.swift b/Sources/Typesense/Models/FieldEmbedModelConfig.swift index d521f47..712392f 100644 --- a/Sources/Typesense/Models/FieldEmbedModelConfig.swift +++ b/Sources/Typesense/Models/FieldEmbedModelConfig.swift @@ -12,57 +12,57 @@ import AnyCodable public struct FieldEmbedModelConfig: Codable { - public var modelName: String - public var apiKey: String? - public var url: String? public var accessToken: String? - public var refreshToken: String? + public var apiKey: String? public var clientId: String? public var clientSecret: String? - public var projectId: String? public var indexingPrefix: String? + public var modelName: String + public var projectId: String? public var queryPrefix: String? + public var refreshToken: String? + public var url: String? - public init(modelName: String, apiKey: String? = nil, url: String? = nil, accessToken: String? = nil, refreshToken: String? = nil, clientId: String? = nil, clientSecret: String? = nil, projectId: String? = nil, indexingPrefix: String? = nil, queryPrefix: String? = nil) { - self.modelName = modelName - self.apiKey = apiKey - self.url = url + public init(accessToken: String? = nil, apiKey: String? = nil, clientId: String? = nil, clientSecret: String? = nil, indexingPrefix: String? = nil, modelName: String, projectId: String? = nil, queryPrefix: String? = nil, refreshToken: String? = nil, url: String? = nil) { self.accessToken = accessToken - self.refreshToken = refreshToken + self.apiKey = apiKey self.clientId = clientId self.clientSecret = clientSecret - self.projectId = projectId self.indexingPrefix = indexingPrefix + self.modelName = modelName + self.projectId = projectId self.queryPrefix = queryPrefix + self.refreshToken = refreshToken + self.url = url } public enum CodingKeys: String, CodingKey, CaseIterable { - case modelName = "model_name" - case apiKey = "api_key" - case url case accessToken = "access_token" - case refreshToken = "refresh_token" + case apiKey = "api_key" case clientId = "client_id" case clientSecret = "client_secret" - case projectId = "project_id" case indexingPrefix = "indexing_prefix" + case modelName = "model_name" + case projectId = "project_id" case queryPrefix = "query_prefix" + case refreshToken = "refresh_token" + case url } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(modelName, forKey: .modelName) - try container.encodeIfPresent(apiKey, forKey: .apiKey) - try container.encodeIfPresent(url, forKey: .url) try container.encodeIfPresent(accessToken, forKey: .accessToken) - try container.encodeIfPresent(refreshToken, forKey: .refreshToken) + try container.encodeIfPresent(apiKey, forKey: .apiKey) try container.encodeIfPresent(clientId, forKey: .clientId) try container.encodeIfPresent(clientSecret, forKey: .clientSecret) - try container.encodeIfPresent(projectId, forKey: .projectId) try container.encodeIfPresent(indexingPrefix, forKey: .indexingPrefix) + try container.encode(modelName, forKey: .modelName) + try container.encodeIfPresent(projectId, forKey: .projectId) try container.encodeIfPresent(queryPrefix, forKey: .queryPrefix) + try container.encodeIfPresent(refreshToken, forKey: .refreshToken) + try container.encodeIfPresent(url, forKey: .url) } } diff --git a/Sources/Typesense/Models/GetCollectionsGetCollectionsParametersParameter.swift b/Sources/Typesense/Models/GetCollectionsParameters.swift similarity index 90% rename from Sources/Typesense/Models/GetCollectionsGetCollectionsParametersParameter.swift rename to Sources/Typesense/Models/GetCollectionsParameters.swift index 4ee1266..52882cd 100644 --- a/Sources/Typesense/Models/GetCollectionsGetCollectionsParametersParameter.swift +++ b/Sources/Typesense/Models/GetCollectionsParameters.swift @@ -1,5 +1,5 @@ // -// GetCollectionsGetCollectionsParametersParameter.swift +// GetCollectionsParameters.swift // // Generated by openapi-generator // https://openapi-generator.tech @@ -10,7 +10,7 @@ import Foundation import AnyCodable #endif -public struct GetCollectionsGetCollectionsParametersParameter: Codable { +public struct GetCollectionsParameters: Codable { /** Comma-separated list of fields from the collection to exclude from the response */ public var excludeFields: String? diff --git a/Sources/Typesense/Models/ImportDocumentsImportDocumentsParametersParameter.swift b/Sources/Typesense/Models/ImportDocumentsParameters.swift similarity index 84% rename from Sources/Typesense/Models/ImportDocumentsImportDocumentsParametersParameter.swift rename to Sources/Typesense/Models/ImportDocumentsParameters.swift index 0b8342f..70b23cc 100644 --- a/Sources/Typesense/Models/ImportDocumentsImportDocumentsParametersParameter.swift +++ b/Sources/Typesense/Models/ImportDocumentsParameters.swift @@ -1,5 +1,5 @@ // -// ImportDocumentsImportDocumentsParametersParameter.swift +// ImportDocumentsParameters.swift // // Generated by openapi-generator // https://openapi-generator.tech @@ -10,44 +10,44 @@ import Foundation import AnyCodable #endif -public struct ImportDocumentsImportDocumentsParametersParameter: Codable { +public struct ImportDocumentsParameters: Codable { + public var action: IndexAction? public var batchSize: Int? - /** 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. */ - public var returnId: Bool? + public var dirtyValues: DirtyValues? public var remoteEmbeddingBatchSize: Int? public var returnDoc: Bool? - public var action: IndexAction? - public var dirtyValues: DirtyValues? + /** 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. */ + public var returnId: Bool? - public init(batchSize: Int? = nil, returnId: Bool? = nil, remoteEmbeddingBatchSize: Int? = nil, returnDoc: Bool? = nil, action: IndexAction? = nil, dirtyValues: DirtyValues? = nil) { + public init(action: IndexAction? = nil, batchSize: Int? = nil, dirtyValues: DirtyValues? = nil, remoteEmbeddingBatchSize: Int? = nil, returnDoc: Bool? = nil, returnId: Bool? = nil) { + self.action = action self.batchSize = batchSize - self.returnId = returnId + self.dirtyValues = dirtyValues self.remoteEmbeddingBatchSize = remoteEmbeddingBatchSize self.returnDoc = returnDoc - self.action = action - self.dirtyValues = dirtyValues + self.returnId = returnId } public enum CodingKeys: String, CodingKey, CaseIterable { + case action case batchSize = "batch_size" - case returnId = "return_id" + case dirtyValues = "dirty_values" case remoteEmbeddingBatchSize = "remote_embedding_batch_size" case returnDoc = "return_doc" - case action - case dirtyValues = "dirty_values" + case returnId = "return_id" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(action, forKey: .action) try container.encodeIfPresent(batchSize, forKey: .batchSize) - try container.encodeIfPresent(returnId, forKey: .returnId) + try container.encodeIfPresent(dirtyValues, forKey: .dirtyValues) try container.encodeIfPresent(remoteEmbeddingBatchSize, forKey: .remoteEmbeddingBatchSize) try container.encodeIfPresent(returnDoc, forKey: .returnDoc) - try container.encodeIfPresent(action, forKey: .action) - try container.encodeIfPresent(dirtyValues, forKey: .dirtyValues) + try container.encodeIfPresent(returnId, forKey: .returnId) } } diff --git a/Sources/Typesense/Models/MultiSearchCollectionParameters.swift b/Sources/Typesense/Models/MultiSearchCollectionParameters.swift index 1cebef9..74d18ca 100644 --- a/Sources/Typesense/Models/MultiSearchCollectionParameters.swift +++ b/Sources/Typesense/Models/MultiSearchCollectionParameters.swift @@ -12,351 +12,351 @@ import AnyCodable public struct MultiSearchCollectionParameters: Codable { - /** 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. */ - public var q: String? - /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ - public var queryBy: 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. */ - public var queryByWeights: 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. */ - public var textMatchType: 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. */ - public var _prefix: String? - /** 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 */ - public var _infix: String? - /** 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. */ - public var maxExtraPrefix: Int? - /** 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. */ - public var maxExtraSuffix: Int? - /** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */ - public var filterBy: 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` */ - public var sortBy: String? + /** 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. */ + public var cacheTtl: Int? + /** Enable conversational search. */ + public var conversation: Bool? + /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ + public var conversationId: String? + /** The Id of Conversation Model to be used. */ + public var conversationModelId: String? + public var dropTokensMode: DropTokensMode? + /** 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 */ + public var dropTokensThreshold: Int? + /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ + public var enableAnalytics: Bool? = true + /** 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 */ + public var enableOverrides: Bool? = false + /** 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 */ + public var enableSynonyms: Bool? + /** Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. */ + public var enableTyposForAlphaNumericalTokens: Bool? + /** Make Typesense disable typos for numerical tokens. */ + public var enableTyposForNumericalTokens: Bool? = true + /** List of fields from the document to exclude in the search result */ + public var excludeFields: String? + /** 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). */ + public var exhaustiveSearch: Bool? /** A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. */ public var facetBy: String? - /** Maximum number of facet values to be returned. */ - public var maxFacetValues: Int? /** 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\". */ public var facetQuery: String? - /** The number of typographical errors (1 or 2) that would be tolerated. Default: 2 */ - public var numTypos: String? - /** Results from this specific page number would be fetched. */ - public var page: Int? - /** Number of results to fetch per page. Default: 10 */ - public var perPage: Int? - /** Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. */ - public var limit: Int? - /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ - public var offset: Int? + /** Comma separated string of nested facet fields whose parent object should be returned in facet response. */ + public var facetReturnParent: String? + /** Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). */ + public var facetStrategy: String? + /** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */ + public var filterBy: String? + /** Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false */ + public var filterCuratedHits: Bool? /** 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. */ public var groupBy: String? /** 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 */ public var groupLimit: Int? /** 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 */ public var groupMissingValues: Bool? - /** List of fields from the document to include in the search result */ - public var includeFields: String? - /** List of fields from the document to exclude in the search result */ - public var excludeFields: String? - /** List of fields which should be highlighted fully without snippeting */ - public var highlightFullFields: 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`. */ + public var hiddenHits: String? /** The number of tokens that should surround the highlighted text on each side. Default: 4 */ public var highlightAffixNumTokens: Int? - /** The start tag used for the highlighted snippets. Default: `` */ - public var highlightStartTag: String? /** The end tag used for the highlighted snippets. Default: `` */ public var highlightEndTag: String? - /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ - public var snippetThreshold: Int? - /** 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 */ - public var dropTokensThreshold: Int? - public var dropTokensMode: DropTokensMode? - /** 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 */ - public var typoTokensThreshold: Int? - /** Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. */ - public var enableTyposForAlphaNumericalTokens: 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 */ - public var filterCuratedHits: 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 */ - public var enableSynonyms: Bool? - /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ - public var enableAnalytics: Bool? = true - /** Allow synonym resolution on word prefixes in the query. Default: false */ - public var synonymPrefix: Bool? - /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ - public var synonymNumTypos: Int? - /** 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`. */ - public var pinnedHits: 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`. */ - public var hiddenHits: String? - /** Comma separated list of tags to trigger the curations rules that match the tags. */ - public var overrideTags: String? /** A list of custom fields that must be highlighted even if you don't query for them */ public var highlightFields: String? + /** List of fields which should be highlighted fully without snippeting */ + public var highlightFullFields: String? + /** The start tag used for the highlighted snippets. Default: `` */ + public var highlightStartTag: String? + /** List of fields from the document to include in the search result */ + public var includeFields: String? + /** 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 */ + public var _infix: String? + /** Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. */ + public var limit: Int? + /** 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. */ + public var maxExtraPrefix: Int? + /** 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. */ + public var maxExtraSuffix: Int? + /** Maximum number of facet values to be returned. */ + public var maxFacetValues: Int? + /** Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ + public var minLen1typo: Int? + /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ + public var minLen2typo: Int? + /** The number of typographical errors (1 or 2) that would be tolerated. Default: 2 */ + public var numTypos: String? + /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ + public var offset: Int? + /** Comma separated list of tags to trigger the curations rules that match the tags. */ + public var overrideTags: String? + /** Results from this specific page number would be fetched. */ + public var page: Int? + /** Number of results to fetch per page. Default: 10 */ + public var perPage: Int? + /** 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`. */ + public var pinnedHits: String? /** 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 */ public var preSegmentedQuery: Bool? = false + /** 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. */ + public var _prefix: String? /** Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. */ public var preset: String? - /** 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 */ - public var enableOverrides: Bool? = false /** Set this parameter to true to ensure that an exact match is ranked above the others */ public var prioritizeExactMatch: Bool? = true - /** Make Typesense prioritize documents where the query words appear earlier in the text. */ - public var prioritizeTokenPosition: Bool? = false /** Make Typesense prioritize documents where the query words appear in more number of fields. */ public var prioritizeNumMatchingFields: Bool? = true - /** Make Typesense disable typos for numerical tokens. */ - public var enableTyposForNumericalTokens: Bool? = true - /** 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). */ - public var exhaustiveSearch: Bool? + /** Make Typesense prioritize documents where the query words appear earlier in the text. */ + public var prioritizeTokenPosition: Bool? = false + /** 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. */ + public var q: String? + /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ + public var queryBy: 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. */ + public var queryByWeights: String? + /** Number of times to retry fetching remote embeddings. */ + public var remoteEmbeddingNumTries: Int? + /** Timeout (in milliseconds) for fetching remote embeddings. */ + public var remoteEmbeddingTimeoutMs: Int? /** 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. */ public var searchCutoffMs: Int? + /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ + public var snippetThreshold: Int? + /** 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` */ + public var sortBy: String? + /** Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. */ + public var stopwords: String? + /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ + public var synonymNumTypos: Int? + /** Allow synonym resolution on word prefixes in the query. Default: false */ + public var synonymPrefix: Bool? + /** 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. */ + public var textMatchType: String? + /** 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 */ + public var typoTokensThreshold: Int? /** Enable server side caching of search query results. By default, caching is disabled. */ public var useCache: Bool? - /** 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. */ - public var cacheTtl: Int? - /** Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ - public var minLen1typo: Int? - /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ - public var minLen2typo: Int? /** Vector query expression for fetching documents \"closest\" to a given query/document vector. */ public var vectorQuery: String? - /** Timeout (in milliseconds) for fetching remote embeddings. */ - public var remoteEmbeddingTimeoutMs: Int? - /** Number of times to retry fetching remote embeddings. */ - public var remoteEmbeddingNumTries: Int? - /** Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). */ - public var facetStrategy: String? - /** Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. */ - public var stopwords: String? - /** Comma separated string of nested facet fields whose parent object should be returned in facet response. */ - public var facetReturnParent: String? /** The base64 encoded audio file in 16 khz 16-bit WAV format. */ public var voiceQuery: String? - /** Enable conversational search. */ - public var conversation: Bool? - /** The Id of Conversation Model to be used. */ - public var conversationModelId: String? - /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ - public var conversationId: String? /** The collection to search in. */ public var collection: String? - /** A separate search API key for each search within a multi_search request */ - public var xTypesenseApiKey: String? /** 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. */ public var rerankHybridMatches: Bool? = false + /** A separate search API key for each search within a multi_search request */ + public var xTypesenseApiKey: String? - public init(q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, textMatchType: String? = nil, _prefix: String? = nil, _infix: String? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, filterBy: String? = nil, sortBy: String? = nil, facetBy: String? = nil, maxFacetValues: Int? = nil, facetQuery: String? = nil, numTypos: String? = nil, page: Int? = nil, perPage: Int? = nil, limit: Int? = nil, offset: Int? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, includeFields: String? = nil, excludeFields: String? = nil, highlightFullFields: String? = nil, highlightAffixNumTokens: Int? = nil, highlightStartTag: String? = nil, highlightEndTag: String? = nil, snippetThreshold: Int? = nil, dropTokensThreshold: Int? = nil, dropTokensMode: DropTokensMode? = nil, typoTokensThreshold: Int? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, filterCuratedHits: Bool? = nil, enableSynonyms: Bool? = nil, enableAnalytics: Bool? = true, synonymPrefix: Bool? = nil, synonymNumTypos: Int? = nil, pinnedHits: String? = nil, hiddenHits: String? = nil, overrideTags: String? = nil, highlightFields: String? = nil, preSegmentedQuery: Bool? = false, preset: String? = nil, enableOverrides: Bool? = false, prioritizeExactMatch: Bool? = true, prioritizeTokenPosition: Bool? = false, prioritizeNumMatchingFields: Bool? = true, enableTyposForNumericalTokens: Bool? = true, exhaustiveSearch: Bool? = nil, searchCutoffMs: Int? = nil, useCache: Bool? = nil, cacheTtl: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, vectorQuery: String? = nil, remoteEmbeddingTimeoutMs: Int? = nil, remoteEmbeddingNumTries: Int? = nil, facetStrategy: String? = nil, stopwords: String? = nil, facetReturnParent: String? = nil, voiceQuery: String? = nil, conversation: Bool? = nil, conversationModelId: String? = nil, conversationId: String? = nil, collection: String? = nil, xTypesenseApiKey: String? = nil, rerankHybridMatches: Bool? = false) { - self.q = q - self.queryBy = queryBy - self.queryByWeights = queryByWeights - self.textMatchType = textMatchType - self._prefix = _prefix - self._infix = _infix - self.maxExtraPrefix = maxExtraPrefix - self.maxExtraSuffix = maxExtraSuffix - self.filterBy = filterBy - self.sortBy = sortBy + public init(cacheTtl: Int? = nil, conversation: Bool? = nil, conversationId: String? = nil, conversationModelId: String? = nil, dropTokensMode: DropTokensMode? = nil, dropTokensThreshold: Int? = nil, enableAnalytics: Bool? = true, enableOverrides: Bool? = false, enableSynonyms: Bool? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, enableTyposForNumericalTokens: Bool? = true, excludeFields: String? = nil, exhaustiveSearch: Bool? = nil, facetBy: String? = nil, facetQuery: String? = nil, facetReturnParent: String? = nil, facetStrategy: String? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, hiddenHits: String? = nil, highlightAffixNumTokens: Int? = nil, highlightEndTag: String? = nil, highlightFields: String? = nil, highlightFullFields: String? = nil, highlightStartTag: String? = nil, includeFields: String? = nil, _infix: String? = nil, limit: Int? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, maxFacetValues: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, numTypos: String? = nil, offset: Int? = nil, overrideTags: String? = nil, page: Int? = nil, perPage: Int? = nil, pinnedHits: String? = nil, preSegmentedQuery: Bool? = false, _prefix: String? = nil, preset: String? = nil, prioritizeExactMatch: Bool? = true, prioritizeNumMatchingFields: Bool? = true, prioritizeTokenPosition: Bool? = false, q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, remoteEmbeddingNumTries: Int? = nil, remoteEmbeddingTimeoutMs: Int? = nil, searchCutoffMs: Int? = nil, snippetThreshold: Int? = nil, sortBy: String? = nil, stopwords: String? = nil, synonymNumTypos: Int? = nil, synonymPrefix: Bool? = nil, textMatchType: String? = nil, typoTokensThreshold: Int? = nil, useCache: Bool? = nil, vectorQuery: String? = nil, voiceQuery: String? = nil, collection: String? = nil, rerankHybridMatches: Bool? = false, xTypesenseApiKey: String? = nil) { + self.cacheTtl = cacheTtl + self.conversation = conversation + self.conversationId = conversationId + self.conversationModelId = conversationModelId + self.dropTokensMode = dropTokensMode + self.dropTokensThreshold = dropTokensThreshold + self.enableAnalytics = enableAnalytics + self.enableOverrides = enableOverrides + self.enableSynonyms = enableSynonyms + self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens + self.enableTyposForNumericalTokens = enableTyposForNumericalTokens + self.excludeFields = excludeFields + self.exhaustiveSearch = exhaustiveSearch self.facetBy = facetBy - self.maxFacetValues = maxFacetValues self.facetQuery = facetQuery - self.numTypos = numTypos - self.page = page - self.perPage = perPage - self.limit = limit - self.offset = offset + self.facetReturnParent = facetReturnParent + self.facetStrategy = facetStrategy + self.filterBy = filterBy + self.filterCuratedHits = filterCuratedHits self.groupBy = groupBy self.groupLimit = groupLimit self.groupMissingValues = groupMissingValues - self.includeFields = includeFields - self.excludeFields = excludeFields - self.highlightFullFields = highlightFullFields + self.hiddenHits = hiddenHits self.highlightAffixNumTokens = highlightAffixNumTokens - self.highlightStartTag = highlightStartTag self.highlightEndTag = highlightEndTag - self.snippetThreshold = snippetThreshold - self.dropTokensThreshold = dropTokensThreshold - self.dropTokensMode = dropTokensMode - self.typoTokensThreshold = typoTokensThreshold - self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens - self.filterCuratedHits = filterCuratedHits - self.enableSynonyms = enableSynonyms - self.enableAnalytics = enableAnalytics - self.synonymPrefix = synonymPrefix - self.synonymNumTypos = synonymNumTypos - self.pinnedHits = pinnedHits - self.hiddenHits = hiddenHits - self.overrideTags = overrideTags self.highlightFields = highlightFields + self.highlightFullFields = highlightFullFields + self.highlightStartTag = highlightStartTag + self.includeFields = includeFields + self._infix = _infix + self.limit = limit + self.maxExtraPrefix = maxExtraPrefix + self.maxExtraSuffix = maxExtraSuffix + self.maxFacetValues = maxFacetValues + self.minLen1typo = minLen1typo + self.minLen2typo = minLen2typo + self.numTypos = numTypos + self.offset = offset + self.overrideTags = overrideTags + self.page = page + self.perPage = perPage + self.pinnedHits = pinnedHits self.preSegmentedQuery = preSegmentedQuery + self._prefix = _prefix self.preset = preset - self.enableOverrides = enableOverrides self.prioritizeExactMatch = prioritizeExactMatch - self.prioritizeTokenPosition = prioritizeTokenPosition self.prioritizeNumMatchingFields = prioritizeNumMatchingFields - self.enableTyposForNumericalTokens = enableTyposForNumericalTokens - self.exhaustiveSearch = exhaustiveSearch + self.prioritizeTokenPosition = prioritizeTokenPosition + self.q = q + self.queryBy = queryBy + self.queryByWeights = queryByWeights + self.remoteEmbeddingNumTries = remoteEmbeddingNumTries + self.remoteEmbeddingTimeoutMs = remoteEmbeddingTimeoutMs self.searchCutoffMs = searchCutoffMs + self.snippetThreshold = snippetThreshold + self.sortBy = sortBy + self.stopwords = stopwords + self.synonymNumTypos = synonymNumTypos + self.synonymPrefix = synonymPrefix + self.textMatchType = textMatchType + self.typoTokensThreshold = typoTokensThreshold self.useCache = useCache - self.cacheTtl = cacheTtl - self.minLen1typo = minLen1typo - self.minLen2typo = minLen2typo self.vectorQuery = vectorQuery - self.remoteEmbeddingTimeoutMs = remoteEmbeddingTimeoutMs - self.remoteEmbeddingNumTries = remoteEmbeddingNumTries - self.facetStrategy = facetStrategy - self.stopwords = stopwords - self.facetReturnParent = facetReturnParent self.voiceQuery = voiceQuery - self.conversation = conversation - self.conversationModelId = conversationModelId - self.conversationId = conversationId self.collection = collection - self.xTypesenseApiKey = xTypesenseApiKey self.rerankHybridMatches = rerankHybridMatches + self.xTypesenseApiKey = xTypesenseApiKey } public enum CodingKeys: String, CodingKey, CaseIterable { - case q - case queryBy = "query_by" - case queryByWeights = "query_by_weights" - case textMatchType = "text_match_type" - case _prefix = "prefix" - case _infix = "infix" - case maxExtraPrefix = "max_extra_prefix" - case maxExtraSuffix = "max_extra_suffix" - case filterBy = "filter_by" - case sortBy = "sort_by" + case cacheTtl = "cache_ttl" + case conversation + case conversationId = "conversation_id" + case conversationModelId = "conversation_model_id" + case dropTokensMode = "drop_tokens_mode" + case dropTokensThreshold = "drop_tokens_threshold" + case enableAnalytics = "enable_analytics" + case enableOverrides = "enable_overrides" + case enableSynonyms = "enable_synonyms" + case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" + case enableTyposForNumericalTokens = "enable_typos_for_numerical_tokens" + case excludeFields = "exclude_fields" + case exhaustiveSearch = "exhaustive_search" case facetBy = "facet_by" - case maxFacetValues = "max_facet_values" case facetQuery = "facet_query" - case numTypos = "num_typos" - case page - case perPage = "per_page" - case limit - case offset + case facetReturnParent = "facet_return_parent" + case facetStrategy = "facet_strategy" + case filterBy = "filter_by" + case filterCuratedHits = "filter_curated_hits" case groupBy = "group_by" case groupLimit = "group_limit" case groupMissingValues = "group_missing_values" - case includeFields = "include_fields" - case excludeFields = "exclude_fields" - case highlightFullFields = "highlight_full_fields" + case hiddenHits = "hidden_hits" case highlightAffixNumTokens = "highlight_affix_num_tokens" - case highlightStartTag = "highlight_start_tag" case highlightEndTag = "highlight_end_tag" - case snippetThreshold = "snippet_threshold" - case dropTokensThreshold = "drop_tokens_threshold" - case dropTokensMode = "drop_tokens_mode" - case typoTokensThreshold = "typo_tokens_threshold" - case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" - case filterCuratedHits = "filter_curated_hits" - case enableSynonyms = "enable_synonyms" - case enableAnalytics = "enable_analytics" - case synonymPrefix = "synonym_prefix" - case synonymNumTypos = "synonym_num_typos" - case pinnedHits = "pinned_hits" - case hiddenHits = "hidden_hits" - case overrideTags = "override_tags" case highlightFields = "highlight_fields" + case highlightFullFields = "highlight_full_fields" + case highlightStartTag = "highlight_start_tag" + case includeFields = "include_fields" + case _infix = "infix" + case limit + case maxExtraPrefix = "max_extra_prefix" + case maxExtraSuffix = "max_extra_suffix" + case maxFacetValues = "max_facet_values" + case minLen1typo = "min_len_1typo" + case minLen2typo = "min_len_2typo" + case numTypos = "num_typos" + case offset + case overrideTags = "override_tags" + case page + case perPage = "per_page" + case pinnedHits = "pinned_hits" case preSegmentedQuery = "pre_segmented_query" + case _prefix = "prefix" case preset - case enableOverrides = "enable_overrides" case prioritizeExactMatch = "prioritize_exact_match" - case prioritizeTokenPosition = "prioritize_token_position" case prioritizeNumMatchingFields = "prioritize_num_matching_fields" - case enableTyposForNumericalTokens = "enable_typos_for_numerical_tokens" - case exhaustiveSearch = "exhaustive_search" + case prioritizeTokenPosition = "prioritize_token_position" + case q + case queryBy = "query_by" + case queryByWeights = "query_by_weights" + case remoteEmbeddingNumTries = "remote_embedding_num_tries" + case remoteEmbeddingTimeoutMs = "remote_embedding_timeout_ms" case searchCutoffMs = "search_cutoff_ms" + case snippetThreshold = "snippet_threshold" + case sortBy = "sort_by" + case stopwords + case synonymNumTypos = "synonym_num_typos" + case synonymPrefix = "synonym_prefix" + case textMatchType = "text_match_type" + case typoTokensThreshold = "typo_tokens_threshold" case useCache = "use_cache" - case cacheTtl = "cache_ttl" - case minLen1typo = "min_len_1typo" - case minLen2typo = "min_len_2typo" case vectorQuery = "vector_query" - case remoteEmbeddingTimeoutMs = "remote_embedding_timeout_ms" - case remoteEmbeddingNumTries = "remote_embedding_num_tries" - case facetStrategy = "facet_strategy" - case stopwords - case facetReturnParent = "facet_return_parent" case voiceQuery = "voice_query" - case conversation - case conversationModelId = "conversation_model_id" - case conversationId = "conversation_id" case collection - case xTypesenseApiKey = "x-typesense-api-key" case rerankHybridMatches = "rerank_hybrid_matches" + case xTypesenseApiKey = "x-typesense-api-key" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(q, forKey: .q) - try container.encodeIfPresent(queryBy, forKey: .queryBy) - try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) - try container.encodeIfPresent(textMatchType, forKey: .textMatchType) - try container.encodeIfPresent(_prefix, forKey: ._prefix) - try container.encodeIfPresent(_infix, forKey: ._infix) - try container.encodeIfPresent(maxExtraPrefix, forKey: .maxExtraPrefix) - try container.encodeIfPresent(maxExtraSuffix, forKey: .maxExtraSuffix) - try container.encodeIfPresent(filterBy, forKey: .filterBy) - try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) + try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encodeIfPresent(conversationId, forKey: .conversationId) + try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) + try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) + try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) + try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) + try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) + try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) + try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) + try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) + try container.encodeIfPresent(excludeFields, forKey: .excludeFields) + try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) try container.encodeIfPresent(facetBy, forKey: .facetBy) - try container.encodeIfPresent(maxFacetValues, forKey: .maxFacetValues) try container.encodeIfPresent(facetQuery, forKey: .facetQuery) - try container.encodeIfPresent(numTypos, forKey: .numTypos) - try container.encodeIfPresent(page, forKey: .page) - try container.encodeIfPresent(perPage, forKey: .perPage) - try container.encodeIfPresent(limit, forKey: .limit) - try container.encodeIfPresent(offset, forKey: .offset) + try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) + try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) + try container.encodeIfPresent(filterBy, forKey: .filterBy) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) try container.encodeIfPresent(groupBy, forKey: .groupBy) try container.encodeIfPresent(groupLimit, forKey: .groupLimit) try container.encodeIfPresent(groupMissingValues, forKey: .groupMissingValues) - try container.encodeIfPresent(includeFields, forKey: .includeFields) - try container.encodeIfPresent(excludeFields, forKey: .excludeFields) - try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) + try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) try container.encodeIfPresent(highlightAffixNumTokens, forKey: .highlightAffixNumTokens) - try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) try container.encodeIfPresent(highlightEndTag, forKey: .highlightEndTag) - try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) - try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) - try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) - try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) - try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) - try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) - try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) - try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) - try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) - try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) - try container.encodeIfPresent(pinnedHits, forKey: .pinnedHits) - try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) - try container.encodeIfPresent(overrideTags, forKey: .overrideTags) try container.encodeIfPresent(highlightFields, forKey: .highlightFields) + try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) + try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) + try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(_infix, forKey: ._infix) + try container.encodeIfPresent(limit, forKey: .limit) + try container.encodeIfPresent(maxExtraPrefix, forKey: .maxExtraPrefix) + try container.encodeIfPresent(maxExtraSuffix, forKey: .maxExtraSuffix) + try container.encodeIfPresent(maxFacetValues, forKey: .maxFacetValues) + try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) + try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) + try container.encodeIfPresent(numTypos, forKey: .numTypos) + try container.encodeIfPresent(offset, forKey: .offset) + try container.encodeIfPresent(overrideTags, forKey: .overrideTags) + try container.encodeIfPresent(page, forKey: .page) + try container.encodeIfPresent(perPage, forKey: .perPage) + try container.encodeIfPresent(pinnedHits, forKey: .pinnedHits) try container.encodeIfPresent(preSegmentedQuery, forKey: .preSegmentedQuery) + try container.encodeIfPresent(_prefix, forKey: ._prefix) try container.encodeIfPresent(preset, forKey: .preset) - try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) try container.encodeIfPresent(prioritizeExactMatch, forKey: .prioritizeExactMatch) - try container.encodeIfPresent(prioritizeTokenPosition, forKey: .prioritizeTokenPosition) try container.encodeIfPresent(prioritizeNumMatchingFields, forKey: .prioritizeNumMatchingFields) - try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) - try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) + try container.encodeIfPresent(prioritizeTokenPosition, forKey: .prioritizeTokenPosition) + try container.encodeIfPresent(q, forKey: .q) + try container.encodeIfPresent(queryBy, forKey: .queryBy) + try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) + try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) + try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) try container.encodeIfPresent(searchCutoffMs, forKey: .searchCutoffMs) + try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) + try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(stopwords, forKey: .stopwords) + try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) + try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) + try container.encodeIfPresent(textMatchType, forKey: .textMatchType) + try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) try container.encodeIfPresent(useCache, forKey: .useCache) - try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) - try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) - try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) try container.encodeIfPresent(vectorQuery, forKey: .vectorQuery) - try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) - try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) - try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) - try container.encodeIfPresent(stopwords, forKey: .stopwords) - try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) - try container.encodeIfPresent(conversation, forKey: .conversation) - try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) - try container.encodeIfPresent(conversationId, forKey: .conversationId) try container.encodeIfPresent(collection, forKey: .collection) - try container.encodeIfPresent(xTypesenseApiKey, forKey: .xTypesenseApiKey) try container.encodeIfPresent(rerankHybridMatches, forKey: .rerankHybridMatches) + try container.encodeIfPresent(xTypesenseApiKey, forKey: .xTypesenseApiKey) } } diff --git a/Sources/Typesense/Models/MultiSearchParameters.swift b/Sources/Typesense/Models/MultiSearchParameters.swift index e1e5765..9ccfeea 100644 --- a/Sources/Typesense/Models/MultiSearchParameters.swift +++ b/Sources/Typesense/Models/MultiSearchParameters.swift @@ -13,336 +13,336 @@ import AnyCodable /** Parameters for the multi search API. */ public struct MultiSearchParameters: Codable { - /** 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. */ - public var q: String? - /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ - public var queryBy: 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. */ - public var queryByWeights: 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. */ - public var textMatchType: 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. */ - public var _prefix: String? - /** 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 */ - public var _infix: String? - /** 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. */ - public var maxExtraPrefix: Int? - /** 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. */ - public var maxExtraSuffix: Int? - /** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */ - public var filterBy: 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` */ - public var sortBy: String? + /** 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. */ + public var cacheTtl: Int? + /** Enable conversational search. */ + public var conversation: Bool? + /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ + public var conversationId: String? + /** The Id of Conversation Model to be used. */ + public var conversationModelId: String? + public var dropTokensMode: DropTokensMode? + /** 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 */ + public var dropTokensThreshold: Int? + /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ + public var enableAnalytics: Bool? = true + /** 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 */ + public var enableOverrides: Bool? = false + /** 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 */ + public var enableSynonyms: Bool? + /** Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. */ + public var enableTyposForAlphaNumericalTokens: Bool? + /** Make Typesense disable typos for numerical tokens. */ + public var enableTyposForNumericalTokens: Bool? = true + /** List of fields from the document to exclude in the search result */ + public var excludeFields: String? + /** 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). */ + public var exhaustiveSearch: Bool? /** A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. */ public var facetBy: String? - /** Maximum number of facet values to be returned. */ - public var maxFacetValues: Int? /** 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\". */ public var facetQuery: String? - /** The number of typographical errors (1 or 2) that would be tolerated. Default: 2 */ - public var numTypos: String? - /** Results from this specific page number would be fetched. */ - public var page: Int? - /** Number of results to fetch per page. Default: 10 */ - public var perPage: Int? - /** Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. */ - public var limit: Int? - /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ - public var offset: Int? + /** Comma separated string of nested facet fields whose parent object should be returned in facet response. */ + public var facetReturnParent: String? + /** Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). */ + public var facetStrategy: String? + /** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */ + public var filterBy: String? + /** Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false */ + public var filterCuratedHits: Bool? /** 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. */ public var groupBy: String? /** 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 */ public var groupLimit: Int? /** 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 */ public var groupMissingValues: Bool? - /** List of fields from the document to include in the search result */ - public var includeFields: String? - /** List of fields from the document to exclude in the search result */ - public var excludeFields: String? - /** List of fields which should be highlighted fully without snippeting */ - public var highlightFullFields: 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`. */ + public var hiddenHits: String? /** The number of tokens that should surround the highlighted text on each side. Default: 4 */ public var highlightAffixNumTokens: Int? - /** The start tag used for the highlighted snippets. Default: `` */ - public var highlightStartTag: String? /** The end tag used for the highlighted snippets. Default: `` */ public var highlightEndTag: String? - /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ - public var snippetThreshold: Int? - /** 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 */ - public var dropTokensThreshold: Int? - public var dropTokensMode: DropTokensMode? - /** 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 */ - public var typoTokensThreshold: Int? - /** Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. */ - public var enableTyposForAlphaNumericalTokens: 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 */ - public var filterCuratedHits: 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 */ - public var enableSynonyms: Bool? - /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ - public var enableAnalytics: Bool? = true - /** Allow synonym resolution on word prefixes in the query. Default: false */ - public var synonymPrefix: Bool? - /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ - public var synonymNumTypos: Int? - /** 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`. */ - public var pinnedHits: 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`. */ - public var hiddenHits: String? - /** Comma separated list of tags to trigger the curations rules that match the tags. */ - public var overrideTags: String? /** A list of custom fields that must be highlighted even if you don't query for them */ public var highlightFields: String? + /** List of fields which should be highlighted fully without snippeting */ + public var highlightFullFields: String? + /** The start tag used for the highlighted snippets. Default: `` */ + public var highlightStartTag: String? + /** List of fields from the document to include in the search result */ + public var includeFields: String? + /** 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 */ + public var _infix: String? + /** Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. */ + public var limit: Int? + /** 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. */ + public var maxExtraPrefix: Int? + /** 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. */ + public var maxExtraSuffix: Int? + /** Maximum number of facet values to be returned. */ + public var maxFacetValues: Int? + /** Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ + public var minLen1typo: Int? + /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ + public var minLen2typo: Int? + /** The number of typographical errors (1 or 2) that would be tolerated. Default: 2 */ + public var numTypos: String? + /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ + public var offset: Int? + /** Comma separated list of tags to trigger the curations rules that match the tags. */ + public var overrideTags: String? + /** Results from this specific page number would be fetched. */ + public var page: Int? + /** Number of results to fetch per page. Default: 10 */ + public var perPage: Int? + /** 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`. */ + public var pinnedHits: String? /** 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 */ public var preSegmentedQuery: Bool? = false + /** 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. */ + public var _prefix: String? /** Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. */ public var preset: String? - /** 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 */ - public var enableOverrides: Bool? = false /** Set this parameter to true to ensure that an exact match is ranked above the others */ public var prioritizeExactMatch: Bool? = true - /** Make Typesense prioritize documents where the query words appear earlier in the text. */ - public var prioritizeTokenPosition: Bool? = false /** Make Typesense prioritize documents where the query words appear in more number of fields. */ public var prioritizeNumMatchingFields: Bool? = true - /** Make Typesense disable typos for numerical tokens. */ - public var enableTyposForNumericalTokens: Bool? = true - /** 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). */ - public var exhaustiveSearch: Bool? + /** Make Typesense prioritize documents where the query words appear earlier in the text. */ + public var prioritizeTokenPosition: Bool? = false + /** 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. */ + public var q: String? + /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ + public var queryBy: 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. */ + public var queryByWeights: String? + /** Number of times to retry fetching remote embeddings. */ + public var remoteEmbeddingNumTries: Int? + /** Timeout (in milliseconds) for fetching remote embeddings. */ + public var remoteEmbeddingTimeoutMs: Int? /** 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. */ public var searchCutoffMs: Int? + /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ + public var snippetThreshold: Int? + /** 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` */ + public var sortBy: String? + /** Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. */ + public var stopwords: String? + /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ + public var synonymNumTypos: Int? + /** Allow synonym resolution on word prefixes in the query. Default: false */ + public var synonymPrefix: Bool? + /** 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. */ + public var textMatchType: String? + /** 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 */ + public var typoTokensThreshold: Int? /** Enable server side caching of search query results. By default, caching is disabled. */ public var useCache: Bool? - /** 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. */ - public var cacheTtl: Int? - /** Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ - public var minLen1typo: Int? - /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ - public var minLen2typo: Int? /** Vector query expression for fetching documents \"closest\" to a given query/document vector. */ public var vectorQuery: String? - /** Timeout (in milliseconds) for fetching remote embeddings. */ - public var remoteEmbeddingTimeoutMs: Int? - /** Number of times to retry fetching remote embeddings. */ - public var remoteEmbeddingNumTries: Int? - /** Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). */ - public var facetStrategy: String? - /** Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. */ - public var stopwords: String? - /** Comma separated string of nested facet fields whose parent object should be returned in facet response. */ - public var facetReturnParent: String? /** The base64 encoded audio file in 16 khz 16-bit WAV format. */ public var voiceQuery: String? - /** Enable conversational search. */ - public var conversation: Bool? - /** The Id of Conversation Model to be used. */ - public var conversationModelId: String? - /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ - public var conversationId: String? - public init(q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, textMatchType: String? = nil, _prefix: String? = nil, _infix: String? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, filterBy: String? = nil, sortBy: String? = nil, facetBy: String? = nil, maxFacetValues: Int? = nil, facetQuery: String? = nil, numTypos: String? = nil, page: Int? = nil, perPage: Int? = nil, limit: Int? = nil, offset: Int? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, includeFields: String? = nil, excludeFields: String? = nil, highlightFullFields: String? = nil, highlightAffixNumTokens: Int? = nil, highlightStartTag: String? = nil, highlightEndTag: String? = nil, snippetThreshold: Int? = nil, dropTokensThreshold: Int? = nil, dropTokensMode: DropTokensMode? = nil, typoTokensThreshold: Int? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, filterCuratedHits: Bool? = nil, enableSynonyms: Bool? = nil, enableAnalytics: Bool? = true, synonymPrefix: Bool? = nil, synonymNumTypos: Int? = nil, pinnedHits: String? = nil, hiddenHits: String? = nil, overrideTags: String? = nil, highlightFields: String? = nil, preSegmentedQuery: Bool? = false, preset: String? = nil, enableOverrides: Bool? = false, prioritizeExactMatch: Bool? = true, prioritizeTokenPosition: Bool? = false, prioritizeNumMatchingFields: Bool? = true, enableTyposForNumericalTokens: Bool? = true, exhaustiveSearch: Bool? = nil, searchCutoffMs: Int? = nil, useCache: Bool? = nil, cacheTtl: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, vectorQuery: String? = nil, remoteEmbeddingTimeoutMs: Int? = nil, remoteEmbeddingNumTries: Int? = nil, facetStrategy: String? = nil, stopwords: String? = nil, facetReturnParent: String? = nil, voiceQuery: String? = nil, conversation: Bool? = nil, conversationModelId: String? = nil, conversationId: String? = nil) { - self.q = q - self.queryBy = queryBy - self.queryByWeights = queryByWeights - self.textMatchType = textMatchType - self._prefix = _prefix - self._infix = _infix - self.maxExtraPrefix = maxExtraPrefix - self.maxExtraSuffix = maxExtraSuffix - self.filterBy = filterBy - self.sortBy = sortBy + public init(cacheTtl: Int? = nil, conversation: Bool? = nil, conversationId: String? = nil, conversationModelId: String? = nil, dropTokensMode: DropTokensMode? = nil, dropTokensThreshold: Int? = nil, enableAnalytics: Bool? = true, enableOverrides: Bool? = false, enableSynonyms: Bool? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, enableTyposForNumericalTokens: Bool? = true, excludeFields: String? = nil, exhaustiveSearch: Bool? = nil, facetBy: String? = nil, facetQuery: String? = nil, facetReturnParent: String? = nil, facetStrategy: String? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, hiddenHits: String? = nil, highlightAffixNumTokens: Int? = nil, highlightEndTag: String? = nil, highlightFields: String? = nil, highlightFullFields: String? = nil, highlightStartTag: String? = nil, includeFields: String? = nil, _infix: String? = nil, limit: Int? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, maxFacetValues: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, numTypos: String? = nil, offset: Int? = nil, overrideTags: String? = nil, page: Int? = nil, perPage: Int? = nil, pinnedHits: String? = nil, preSegmentedQuery: Bool? = false, _prefix: String? = nil, preset: String? = nil, prioritizeExactMatch: Bool? = true, prioritizeNumMatchingFields: Bool? = true, prioritizeTokenPosition: Bool? = false, q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, remoteEmbeddingNumTries: Int? = nil, remoteEmbeddingTimeoutMs: Int? = nil, searchCutoffMs: Int? = nil, snippetThreshold: Int? = nil, sortBy: String? = nil, stopwords: String? = nil, synonymNumTypos: Int? = nil, synonymPrefix: Bool? = nil, textMatchType: String? = nil, typoTokensThreshold: Int? = nil, useCache: Bool? = nil, vectorQuery: String? = nil, voiceQuery: String? = nil) { + self.cacheTtl = cacheTtl + self.conversation = conversation + self.conversationId = conversationId + self.conversationModelId = conversationModelId + self.dropTokensMode = dropTokensMode + self.dropTokensThreshold = dropTokensThreshold + self.enableAnalytics = enableAnalytics + self.enableOverrides = enableOverrides + self.enableSynonyms = enableSynonyms + self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens + self.enableTyposForNumericalTokens = enableTyposForNumericalTokens + self.excludeFields = excludeFields + self.exhaustiveSearch = exhaustiveSearch self.facetBy = facetBy - self.maxFacetValues = maxFacetValues self.facetQuery = facetQuery - self.numTypos = numTypos - self.page = page - self.perPage = perPage - self.limit = limit - self.offset = offset + self.facetReturnParent = facetReturnParent + self.facetStrategy = facetStrategy + self.filterBy = filterBy + self.filterCuratedHits = filterCuratedHits self.groupBy = groupBy self.groupLimit = groupLimit self.groupMissingValues = groupMissingValues - self.includeFields = includeFields - self.excludeFields = excludeFields - self.highlightFullFields = highlightFullFields + self.hiddenHits = hiddenHits self.highlightAffixNumTokens = highlightAffixNumTokens - self.highlightStartTag = highlightStartTag self.highlightEndTag = highlightEndTag - self.snippetThreshold = snippetThreshold - self.dropTokensThreshold = dropTokensThreshold - self.dropTokensMode = dropTokensMode - self.typoTokensThreshold = typoTokensThreshold - self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens - self.filterCuratedHits = filterCuratedHits - self.enableSynonyms = enableSynonyms - self.enableAnalytics = enableAnalytics - self.synonymPrefix = synonymPrefix - self.synonymNumTypos = synonymNumTypos - self.pinnedHits = pinnedHits - self.hiddenHits = hiddenHits - self.overrideTags = overrideTags self.highlightFields = highlightFields + self.highlightFullFields = highlightFullFields + self.highlightStartTag = highlightStartTag + self.includeFields = includeFields + self._infix = _infix + self.limit = limit + self.maxExtraPrefix = maxExtraPrefix + self.maxExtraSuffix = maxExtraSuffix + self.maxFacetValues = maxFacetValues + self.minLen1typo = minLen1typo + self.minLen2typo = minLen2typo + self.numTypos = numTypos + self.offset = offset + self.overrideTags = overrideTags + self.page = page + self.perPage = perPage + self.pinnedHits = pinnedHits self.preSegmentedQuery = preSegmentedQuery + self._prefix = _prefix self.preset = preset - self.enableOverrides = enableOverrides self.prioritizeExactMatch = prioritizeExactMatch - self.prioritizeTokenPosition = prioritizeTokenPosition self.prioritizeNumMatchingFields = prioritizeNumMatchingFields - self.enableTyposForNumericalTokens = enableTyposForNumericalTokens - self.exhaustiveSearch = exhaustiveSearch + self.prioritizeTokenPosition = prioritizeTokenPosition + self.q = q + self.queryBy = queryBy + self.queryByWeights = queryByWeights + self.remoteEmbeddingNumTries = remoteEmbeddingNumTries + self.remoteEmbeddingTimeoutMs = remoteEmbeddingTimeoutMs self.searchCutoffMs = searchCutoffMs + self.snippetThreshold = snippetThreshold + self.sortBy = sortBy + self.stopwords = stopwords + self.synonymNumTypos = synonymNumTypos + self.synonymPrefix = synonymPrefix + self.textMatchType = textMatchType + self.typoTokensThreshold = typoTokensThreshold self.useCache = useCache - self.cacheTtl = cacheTtl - self.minLen1typo = minLen1typo - self.minLen2typo = minLen2typo self.vectorQuery = vectorQuery - self.remoteEmbeddingTimeoutMs = remoteEmbeddingTimeoutMs - self.remoteEmbeddingNumTries = remoteEmbeddingNumTries - self.facetStrategy = facetStrategy - self.stopwords = stopwords - self.facetReturnParent = facetReturnParent self.voiceQuery = voiceQuery - self.conversation = conversation - self.conversationModelId = conversationModelId - self.conversationId = conversationId } public enum CodingKeys: String, CodingKey, CaseIterable { - case q - case queryBy = "query_by" - case queryByWeights = "query_by_weights" - case textMatchType = "text_match_type" - case _prefix = "prefix" - case _infix = "infix" - case maxExtraPrefix = "max_extra_prefix" - case maxExtraSuffix = "max_extra_suffix" - case filterBy = "filter_by" - case sortBy = "sort_by" + case cacheTtl = "cache_ttl" + case conversation + case conversationId = "conversation_id" + case conversationModelId = "conversation_model_id" + case dropTokensMode = "drop_tokens_mode" + case dropTokensThreshold = "drop_tokens_threshold" + case enableAnalytics = "enable_analytics" + case enableOverrides = "enable_overrides" + case enableSynonyms = "enable_synonyms" + case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" + case enableTyposForNumericalTokens = "enable_typos_for_numerical_tokens" + case excludeFields = "exclude_fields" + case exhaustiveSearch = "exhaustive_search" case facetBy = "facet_by" - case maxFacetValues = "max_facet_values" case facetQuery = "facet_query" - case numTypos = "num_typos" - case page - case perPage = "per_page" - case limit - case offset + case facetReturnParent = "facet_return_parent" + case facetStrategy = "facet_strategy" + case filterBy = "filter_by" + case filterCuratedHits = "filter_curated_hits" case groupBy = "group_by" case groupLimit = "group_limit" case groupMissingValues = "group_missing_values" - case includeFields = "include_fields" - case excludeFields = "exclude_fields" - case highlightFullFields = "highlight_full_fields" + case hiddenHits = "hidden_hits" case highlightAffixNumTokens = "highlight_affix_num_tokens" - case highlightStartTag = "highlight_start_tag" case highlightEndTag = "highlight_end_tag" - case snippetThreshold = "snippet_threshold" - case dropTokensThreshold = "drop_tokens_threshold" - case dropTokensMode = "drop_tokens_mode" - case typoTokensThreshold = "typo_tokens_threshold" - case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" - case filterCuratedHits = "filter_curated_hits" - case enableSynonyms = "enable_synonyms" - case enableAnalytics = "enable_analytics" - case synonymPrefix = "synonym_prefix" - case synonymNumTypos = "synonym_num_typos" - case pinnedHits = "pinned_hits" - case hiddenHits = "hidden_hits" - case overrideTags = "override_tags" case highlightFields = "highlight_fields" + case highlightFullFields = "highlight_full_fields" + case highlightStartTag = "highlight_start_tag" + case includeFields = "include_fields" + case _infix = "infix" + case limit + case maxExtraPrefix = "max_extra_prefix" + case maxExtraSuffix = "max_extra_suffix" + case maxFacetValues = "max_facet_values" + case minLen1typo = "min_len_1typo" + case minLen2typo = "min_len_2typo" + case numTypos = "num_typos" + case offset + case overrideTags = "override_tags" + case page + case perPage = "per_page" + case pinnedHits = "pinned_hits" case preSegmentedQuery = "pre_segmented_query" + case _prefix = "prefix" case preset - case enableOverrides = "enable_overrides" case prioritizeExactMatch = "prioritize_exact_match" - case prioritizeTokenPosition = "prioritize_token_position" case prioritizeNumMatchingFields = "prioritize_num_matching_fields" - case enableTyposForNumericalTokens = "enable_typos_for_numerical_tokens" - case exhaustiveSearch = "exhaustive_search" + case prioritizeTokenPosition = "prioritize_token_position" + case q + case queryBy = "query_by" + case queryByWeights = "query_by_weights" + case remoteEmbeddingNumTries = "remote_embedding_num_tries" + case remoteEmbeddingTimeoutMs = "remote_embedding_timeout_ms" case searchCutoffMs = "search_cutoff_ms" + case snippetThreshold = "snippet_threshold" + case sortBy = "sort_by" + case stopwords + case synonymNumTypos = "synonym_num_typos" + case synonymPrefix = "synonym_prefix" + case textMatchType = "text_match_type" + case typoTokensThreshold = "typo_tokens_threshold" case useCache = "use_cache" - case cacheTtl = "cache_ttl" - case minLen1typo = "min_len_1typo" - case minLen2typo = "min_len_2typo" case vectorQuery = "vector_query" - case remoteEmbeddingTimeoutMs = "remote_embedding_timeout_ms" - case remoteEmbeddingNumTries = "remote_embedding_num_tries" - case facetStrategy = "facet_strategy" - case stopwords - case facetReturnParent = "facet_return_parent" case voiceQuery = "voice_query" - case conversation - case conversationModelId = "conversation_model_id" - case conversationId = "conversation_id" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(q, forKey: .q) - try container.encodeIfPresent(queryBy, forKey: .queryBy) - try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) - try container.encodeIfPresent(textMatchType, forKey: .textMatchType) - try container.encodeIfPresent(_prefix, forKey: ._prefix) - try container.encodeIfPresent(_infix, forKey: ._infix) - try container.encodeIfPresent(maxExtraPrefix, forKey: .maxExtraPrefix) - try container.encodeIfPresent(maxExtraSuffix, forKey: .maxExtraSuffix) - try container.encodeIfPresent(filterBy, forKey: .filterBy) - try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) + try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encodeIfPresent(conversationId, forKey: .conversationId) + try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) + try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) + try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) + try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) + try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) + try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) + try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) + try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) + try container.encodeIfPresent(excludeFields, forKey: .excludeFields) + try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) try container.encodeIfPresent(facetBy, forKey: .facetBy) - try container.encodeIfPresent(maxFacetValues, forKey: .maxFacetValues) try container.encodeIfPresent(facetQuery, forKey: .facetQuery) - try container.encodeIfPresent(numTypos, forKey: .numTypos) - try container.encodeIfPresent(page, forKey: .page) - try container.encodeIfPresent(perPage, forKey: .perPage) - try container.encodeIfPresent(limit, forKey: .limit) - try container.encodeIfPresent(offset, forKey: .offset) + try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) + try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) + try container.encodeIfPresent(filterBy, forKey: .filterBy) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) try container.encodeIfPresent(groupBy, forKey: .groupBy) try container.encodeIfPresent(groupLimit, forKey: .groupLimit) try container.encodeIfPresent(groupMissingValues, forKey: .groupMissingValues) - try container.encodeIfPresent(includeFields, forKey: .includeFields) - try container.encodeIfPresent(excludeFields, forKey: .excludeFields) - try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) + try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) try container.encodeIfPresent(highlightAffixNumTokens, forKey: .highlightAffixNumTokens) - try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) try container.encodeIfPresent(highlightEndTag, forKey: .highlightEndTag) - try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) - try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) - try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) - try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) - try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) - try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) - try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) - try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) - try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) - try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) - try container.encodeIfPresent(pinnedHits, forKey: .pinnedHits) - try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) - try container.encodeIfPresent(overrideTags, forKey: .overrideTags) try container.encodeIfPresent(highlightFields, forKey: .highlightFields) + try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) + try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) + try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(_infix, forKey: ._infix) + try container.encodeIfPresent(limit, forKey: .limit) + try container.encodeIfPresent(maxExtraPrefix, forKey: .maxExtraPrefix) + try container.encodeIfPresent(maxExtraSuffix, forKey: .maxExtraSuffix) + try container.encodeIfPresent(maxFacetValues, forKey: .maxFacetValues) + try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) + try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) + try container.encodeIfPresent(numTypos, forKey: .numTypos) + try container.encodeIfPresent(offset, forKey: .offset) + try container.encodeIfPresent(overrideTags, forKey: .overrideTags) + try container.encodeIfPresent(page, forKey: .page) + try container.encodeIfPresent(perPage, forKey: .perPage) + try container.encodeIfPresent(pinnedHits, forKey: .pinnedHits) try container.encodeIfPresent(preSegmentedQuery, forKey: .preSegmentedQuery) + try container.encodeIfPresent(_prefix, forKey: ._prefix) try container.encodeIfPresent(preset, forKey: .preset) - try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) try container.encodeIfPresent(prioritizeExactMatch, forKey: .prioritizeExactMatch) - try container.encodeIfPresent(prioritizeTokenPosition, forKey: .prioritizeTokenPosition) try container.encodeIfPresent(prioritizeNumMatchingFields, forKey: .prioritizeNumMatchingFields) - try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) - try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) + try container.encodeIfPresent(prioritizeTokenPosition, forKey: .prioritizeTokenPosition) + try container.encodeIfPresent(q, forKey: .q) + try container.encodeIfPresent(queryBy, forKey: .queryBy) + try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) + try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) + try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) try container.encodeIfPresent(searchCutoffMs, forKey: .searchCutoffMs) + try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) + try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(stopwords, forKey: .stopwords) + try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) + try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) + try container.encodeIfPresent(textMatchType, forKey: .textMatchType) + try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) try container.encodeIfPresent(useCache, forKey: .useCache) - try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) - try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) - try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) try container.encodeIfPresent(vectorQuery, forKey: .vectorQuery) - try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) - try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) - try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) - try container.encodeIfPresent(stopwords, forKey: .stopwords) - try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) - try container.encodeIfPresent(conversation, forKey: .conversation) - try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) - try container.encodeIfPresent(conversationId, forKey: .conversationId) } } diff --git a/Sources/Typesense/Models/MultiSearchResult.swift b/Sources/Typesense/Models/MultiSearchResult.swift index c99c372..7a30625 100644 --- a/Sources/Typesense/Models/MultiSearchResult.swift +++ b/Sources/Typesense/Models/MultiSearchResult.swift @@ -10,27 +10,27 @@ import Foundation import AnyCodable #endif -public struct MultiSearchResult: Codable { +public struct MultiSearchResult: Codable { - public var results: [MultiSearchResultItem] public var conversation: SearchResultConversation? + public var results: [MultiSearchResultItem] - public init(results: [MultiSearchResultItem], conversation: SearchResultConversation? = nil) { - self.results = results + public init(conversation: SearchResultConversation? = nil, results: [MultiSearchResultItem]) { self.conversation = conversation + self.results = results } public enum CodingKeys: String, CodingKey, CaseIterable { - case results case conversation + case results } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(results, forKey: .results) try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encode(results, forKey: .results) } } diff --git a/Sources/Typesense/Models/MultiSearchResultItem.swift b/Sources/Typesense/Models/MultiSearchResultItem.swift index 8e3cdae..af71d04 100644 --- a/Sources/Typesense/Models/MultiSearchResultItem.swift +++ b/Sources/Typesense/Models/MultiSearchResultItem.swift @@ -12,64 +12,64 @@ import AnyCodable public struct MultiSearchResultItem: Codable { + public var conversation: SearchResultConversation? public var facetCounts: [FacetCounts]? /** The number of documents found */ public var found: Int? public var foundDocs: Int? - /** The number of milliseconds the search took */ - public var searchTimeMs: Int? + public var groupedHits: [SearchGroupedHit]? + /** The documents that matched the search query */ + public var hits: [SearchResultHit]? + /** Custom JSON object that can be returned in the search response */ + public var metadata: [String: AnyCodable]? /** The total number of documents in the collection */ public var outOf: Int? - /** Whether the search was cut off */ - public var searchCutoff: Bool? /** The search result page number */ public var page: Int? - public var groupedHits: [SearchGroupedHit]? - /** The documents that matched the search query */ - public var hits: [SearchResultHit]? public var requestParams: SearchRequestParams? - public var conversation: SearchResultConversation? + /** Whether the search was cut off */ + public var searchCutoff: Bool? + /** The number of milliseconds the search took */ + public var searchTimeMs: Int? /** Returned only for union query response. */ public var unionRequestParams: [SearchRequestParams]? - /** Custom JSON object that can be returned in the search response */ - public var metadata: [String: AnyCodable]? /** HTTP error code */ public var code: Int64? /** Error description */ public var error: String? - public init(facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, searchTimeMs: Int? = nil, outOf: Int? = nil, searchCutoff: Bool? = nil, page: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, requestParams: SearchRequestParams? = nil, conversation: SearchResultConversation? = nil, unionRequestParams: [SearchRequestParams]? = nil, metadata: [String: AnyCodable]? = nil, code: Int64? = nil, error: String? = nil) { + public init(conversation: SearchResultConversation? = nil, facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, metadata: [String: AnyCodable]? = nil, outOf: Int? = nil, page: Int? = nil, requestParams: SearchRequestParams? = nil, searchCutoff: Bool? = nil, searchTimeMs: Int? = nil, unionRequestParams: [SearchRequestParams]? = nil, code: Int64? = nil, error: String? = nil) { + self.conversation = conversation self.facetCounts = facetCounts self.found = found self.foundDocs = foundDocs - self.searchTimeMs = searchTimeMs - self.outOf = outOf - self.searchCutoff = searchCutoff - self.page = page self.groupedHits = groupedHits self.hits = hits + self.metadata = metadata + self.outOf = outOf + self.page = page self.requestParams = requestParams - self.conversation = conversation + self.searchCutoff = searchCutoff + self.searchTimeMs = searchTimeMs self.unionRequestParams = unionRequestParams - self.metadata = metadata self.code = code self.error = error } public enum CodingKeys: String, CodingKey, CaseIterable { + case conversation case facetCounts = "facet_counts" case found case foundDocs = "found_docs" - case searchTimeMs = "search_time_ms" - case outOf = "out_of" - case searchCutoff = "search_cutoff" - case page case groupedHits = "grouped_hits" case hits + case metadata + case outOf = "out_of" + case page case requestParams = "request_params" - case conversation + case searchCutoff = "search_cutoff" + case searchTimeMs = "search_time_ms" case unionRequestParams = "union_request_params" - case metadata case code case error } @@ -78,19 +78,19 @@ public struct MultiSearchResultItem: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(conversation, forKey: .conversation) try container.encodeIfPresent(facetCounts, forKey: .facetCounts) try container.encodeIfPresent(found, forKey: .found) try container.encodeIfPresent(foundDocs, forKey: .foundDocs) - try container.encodeIfPresent(searchTimeMs, forKey: .searchTimeMs) - try container.encodeIfPresent(outOf, forKey: .outOf) - try container.encodeIfPresent(searchCutoff, forKey: .searchCutoff) - try container.encodeIfPresent(page, forKey: .page) try container.encodeIfPresent(groupedHits, forKey: .groupedHits) try container.encodeIfPresent(hits, forKey: .hits) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encodeIfPresent(outOf, forKey: .outOf) + try container.encodeIfPresent(page, forKey: .page) try container.encodeIfPresent(requestParams, forKey: .requestParams) - try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encodeIfPresent(searchCutoff, forKey: .searchCutoff) + try container.encodeIfPresent(searchTimeMs, forKey: .searchTimeMs) try container.encodeIfPresent(unionRequestParams, forKey: .unionRequestParams) - try container.encodeIfPresent(metadata, forKey: .metadata) try container.encodeIfPresent(code, forKey: .code) try container.encodeIfPresent(error, forKey: .error) } diff --git a/Sources/Typesense/Models/MultiSearchSearchesParameter.swift b/Sources/Typesense/Models/MultiSearchSearchesParameter.swift index 045612f..b21185f 100644 --- a/Sources/Typesense/Models/MultiSearchSearchesParameter.swift +++ b/Sources/Typesense/Models/MultiSearchSearchesParameter.swift @@ -12,26 +12,26 @@ import AnyCodable public struct MultiSearchSearchesParameter: Codable { + public var searches: [MultiSearchCollectionParameters] /** When true, merges the search results from each search query into a single ordered set of hits. */ public var union: Bool? = false - public var searches: [MultiSearchCollectionParameters] - public init(union: Bool? = false, searches: [MultiSearchCollectionParameters]) { - self.union = union + public init(searches: [MultiSearchCollectionParameters], union: Bool? = false) { self.searches = searches + self.union = union } public enum CodingKeys: String, CodingKey, CaseIterable { - case union case searches + case union } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(union, forKey: .union) try container.encode(searches, forKey: .searches) + try container.encodeIfPresent(union, forKey: .union) } } diff --git a/Sources/Typesense/Models/NLSearchModelBase.swift b/Sources/Typesense/Models/NLSearchModelBase.swift index b356eee..5f37a11 100644 --- a/Sources/Typesense/Models/NLSearchModelBase.swift +++ b/Sources/Typesense/Models/NLSearchModelBase.swift @@ -12,107 +12,107 @@ import AnyCodable public struct NLSearchModelBase: Codable { - /** Name of the NL model to use */ - public var modelName: String? + /** Access token for GCP Vertex AI */ + public var accessToken: String? + /** Account ID for Cloudflare-specific models */ + public var accountId: String? /** API key for the NL model service */ public var apiKey: String? /** Custom API URL for the NL model service */ public var apiUrl: String? - /** Maximum number of bytes to process */ - public var maxBytes: Int? - /** Temperature parameter for the NL model */ - public var temperature: Double? - /** System prompt for the NL model */ - public var systemPrompt: String? - /** Top-p parameter for the NL model (Google-specific) */ - public var topP: Double? - /** Top-k parameter for the NL model (Google-specific) */ - public var topK: Int? - /** Stop sequences for the NL model (Google-specific) */ - public var stopSequences: [String]? /** API version for the NL model service */ public var apiVersion: String? - /** Project ID for GCP Vertex AI */ - public var projectId: String? - /** Access token for GCP Vertex AI */ - public var accessToken: String? - /** Refresh token for GCP Vertex AI */ - public var refreshToken: String? /** Client ID for GCP Vertex AI */ public var clientId: String? /** Client secret for GCP Vertex AI */ public var clientSecret: String? - /** Region for GCP Vertex AI */ - public var region: String? + /** Maximum number of bytes to process */ + public var maxBytes: Int? /** Maximum output tokens for GCP Vertex AI */ public var maxOutputTokens: Int? - /** Account ID for Cloudflare-specific models */ - public var accountId: String? + /** Name of the NL model to use */ + public var modelName: String? + /** Project ID for GCP Vertex AI */ + public var projectId: String? + /** Refresh token for GCP Vertex AI */ + public var refreshToken: String? + /** Region for GCP Vertex AI */ + public var region: String? + /** Stop sequences for the NL model (Google-specific) */ + public var stopSequences: [String]? + /** System prompt for the NL model */ + public var systemPrompt: String? + /** Temperature parameter for the NL model */ + public var temperature: Double? + /** Top-k parameter for the NL model (Google-specific) */ + public var topK: Int? + /** Top-p parameter for the NL model (Google-specific) */ + public var topP: Double? - public init(modelName: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, maxBytes: Int? = nil, temperature: Double? = nil, systemPrompt: String? = nil, topP: Double? = nil, topK: Int? = nil, stopSequences: [String]? = nil, apiVersion: String? = nil, projectId: String? = nil, accessToken: String? = nil, refreshToken: String? = nil, clientId: String? = nil, clientSecret: String? = nil, region: String? = nil, maxOutputTokens: Int? = nil, accountId: String? = nil) { - self.modelName = modelName + public init(accessToken: String? = nil, accountId: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, apiVersion: String? = nil, clientId: String? = nil, clientSecret: String? = nil, maxBytes: Int? = nil, maxOutputTokens: Int? = nil, modelName: String? = nil, projectId: String? = nil, refreshToken: String? = nil, region: String? = nil, stopSequences: [String]? = nil, systemPrompt: String? = nil, temperature: Double? = nil, topK: Int? = nil, topP: Double? = nil) { + self.accessToken = accessToken + self.accountId = accountId self.apiKey = apiKey self.apiUrl = apiUrl - self.maxBytes = maxBytes - self.temperature = temperature - self.systemPrompt = systemPrompt - self.topP = topP - self.topK = topK - self.stopSequences = stopSequences self.apiVersion = apiVersion - self.projectId = projectId - self.accessToken = accessToken - self.refreshToken = refreshToken self.clientId = clientId self.clientSecret = clientSecret - self.region = region + self.maxBytes = maxBytes self.maxOutputTokens = maxOutputTokens - self.accountId = accountId + self.modelName = modelName + self.projectId = projectId + self.refreshToken = refreshToken + self.region = region + self.stopSequences = stopSequences + self.systemPrompt = systemPrompt + self.temperature = temperature + self.topK = topK + self.topP = topP } public enum CodingKeys: String, CodingKey, CaseIterable { - case modelName = "model_name" + case accessToken = "access_token" + case accountId = "account_id" case apiKey = "api_key" case apiUrl = "api_url" - case maxBytes = "max_bytes" - case temperature - case systemPrompt = "system_prompt" - case topP = "top_p" - case topK = "top_k" - case stopSequences = "stop_sequences" case apiVersion = "api_version" - case projectId = "project_id" - case accessToken = "access_token" - case refreshToken = "refresh_token" case clientId = "client_id" case clientSecret = "client_secret" - case region + case maxBytes = "max_bytes" case maxOutputTokens = "max_output_tokens" - case accountId = "account_id" + case modelName = "model_name" + case projectId = "project_id" + case refreshToken = "refresh_token" + case region + case stopSequences = "stop_sequences" + case systemPrompt = "system_prompt" + case temperature + case topK = "top_k" + case topP = "top_p" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(accessToken, forKey: .accessToken) + try container.encodeIfPresent(accountId, forKey: .accountId) try container.encodeIfPresent(apiKey, forKey: .apiKey) try container.encodeIfPresent(apiUrl, forKey: .apiUrl) - try container.encodeIfPresent(maxBytes, forKey: .maxBytes) - try container.encodeIfPresent(temperature, forKey: .temperature) - try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) - try container.encodeIfPresent(topP, forKey: .topP) - try container.encodeIfPresent(topK, forKey: .topK) - try container.encodeIfPresent(stopSequences, forKey: .stopSequences) try container.encodeIfPresent(apiVersion, forKey: .apiVersion) - try container.encodeIfPresent(projectId, forKey: .projectId) - try container.encodeIfPresent(accessToken, forKey: .accessToken) - try container.encodeIfPresent(refreshToken, forKey: .refreshToken) try container.encodeIfPresent(clientId, forKey: .clientId) try container.encodeIfPresent(clientSecret, forKey: .clientSecret) - try container.encodeIfPresent(region, forKey: .region) + try container.encodeIfPresent(maxBytes, forKey: .maxBytes) try container.encodeIfPresent(maxOutputTokens, forKey: .maxOutputTokens) - try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(projectId, forKey: .projectId) + try container.encodeIfPresent(refreshToken, forKey: .refreshToken) + try container.encodeIfPresent(region, forKey: .region) + try container.encodeIfPresent(stopSequences, forKey: .stopSequences) + try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) + try container.encodeIfPresent(temperature, forKey: .temperature) + try container.encodeIfPresent(topK, forKey: .topK) + try container.encodeIfPresent(topP, forKey: .topP) } } diff --git a/Sources/Typesense/Models/NLSearchModelCreateSchema.swift b/Sources/Typesense/Models/NLSearchModelCreateSchema.swift index bbd1dd0..f7bbf95 100644 --- a/Sources/Typesense/Models/NLSearchModelCreateSchema.swift +++ b/Sources/Typesense/Models/NLSearchModelCreateSchema.swift @@ -12,86 +12,86 @@ import AnyCodable public struct NLSearchModelCreateSchema: Codable { - /** Name of the NL model to use */ - public var modelName: String? + /** Access token for GCP Vertex AI */ + public var accessToken: String? + /** Account ID for Cloudflare-specific models */ + public var accountId: String? /** API key for the NL model service */ public var apiKey: String? /** Custom API URL for the NL model service */ public var apiUrl: String? - /** Maximum number of bytes to process */ - public var maxBytes: Int? - /** Temperature parameter for the NL model */ - public var temperature: Double? - /** System prompt for the NL model */ - public var systemPrompt: String? - /** Top-p parameter for the NL model (Google-specific) */ - public var topP: Double? - /** Top-k parameter for the NL model (Google-specific) */ - public var topK: Int? - /** Stop sequences for the NL model (Google-specific) */ - public var stopSequences: [String]? /** API version for the NL model service */ public var apiVersion: String? - /** Project ID for GCP Vertex AI */ - public var projectId: String? - /** Access token for GCP Vertex AI */ - public var accessToken: String? - /** Refresh token for GCP Vertex AI */ - public var refreshToken: String? /** Client ID for GCP Vertex AI */ public var clientId: String? /** Client secret for GCP Vertex AI */ public var clientSecret: String? - /** Region for GCP Vertex AI */ - public var region: String? + /** Maximum number of bytes to process */ + public var maxBytes: Int? /** Maximum output tokens for GCP Vertex AI */ public var maxOutputTokens: Int? - /** Account ID for Cloudflare-specific models */ - public var accountId: String? + /** Name of the NL model to use */ + public var modelName: String? + /** Project ID for GCP Vertex AI */ + public var projectId: String? + /** Refresh token for GCP Vertex AI */ + public var refreshToken: String? + /** Region for GCP Vertex AI */ + public var region: String? + /** Stop sequences for the NL model (Google-specific) */ + public var stopSequences: [String]? + /** System prompt for the NL model */ + public var systemPrompt: String? + /** Temperature parameter for the NL model */ + public var temperature: Double? + /** Top-k parameter for the NL model (Google-specific) */ + public var topK: Int? + /** Top-p parameter for the NL model (Google-specific) */ + public var topP: Double? /** Optional ID for the NL search model */ public var id: String? - public init(modelName: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, maxBytes: Int? = nil, temperature: Double? = nil, systemPrompt: String? = nil, topP: Double? = nil, topK: Int? = nil, stopSequences: [String]? = nil, apiVersion: String? = nil, projectId: String? = nil, accessToken: String? = nil, refreshToken: String? = nil, clientId: String? = nil, clientSecret: String? = nil, region: String? = nil, maxOutputTokens: Int? = nil, accountId: String? = nil, id: String? = nil) { - self.modelName = modelName + public init(accessToken: String? = nil, accountId: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, apiVersion: String? = nil, clientId: String? = nil, clientSecret: String? = nil, maxBytes: Int? = nil, maxOutputTokens: Int? = nil, modelName: String? = nil, projectId: String? = nil, refreshToken: String? = nil, region: String? = nil, stopSequences: [String]? = nil, systemPrompt: String? = nil, temperature: Double? = nil, topK: Int? = nil, topP: Double? = nil, id: String? = nil) { + self.accessToken = accessToken + self.accountId = accountId self.apiKey = apiKey self.apiUrl = apiUrl - self.maxBytes = maxBytes - self.temperature = temperature - self.systemPrompt = systemPrompt - self.topP = topP - self.topK = topK - self.stopSequences = stopSequences self.apiVersion = apiVersion - self.projectId = projectId - self.accessToken = accessToken - self.refreshToken = refreshToken self.clientId = clientId self.clientSecret = clientSecret - self.region = region + self.maxBytes = maxBytes self.maxOutputTokens = maxOutputTokens - self.accountId = accountId + self.modelName = modelName + self.projectId = projectId + self.refreshToken = refreshToken + self.region = region + self.stopSequences = stopSequences + self.systemPrompt = systemPrompt + self.temperature = temperature + self.topK = topK + self.topP = topP self.id = id } public enum CodingKeys: String, CodingKey, CaseIterable { - case modelName = "model_name" + case accessToken = "access_token" + case accountId = "account_id" case apiKey = "api_key" case apiUrl = "api_url" - case maxBytes = "max_bytes" - case temperature - case systemPrompt = "system_prompt" - case topP = "top_p" - case topK = "top_k" - case stopSequences = "stop_sequences" case apiVersion = "api_version" - case projectId = "project_id" - case accessToken = "access_token" - case refreshToken = "refresh_token" case clientId = "client_id" case clientSecret = "client_secret" - case region + case maxBytes = "max_bytes" case maxOutputTokens = "max_output_tokens" - case accountId = "account_id" + case modelName = "model_name" + case projectId = "project_id" + case refreshToken = "refresh_token" + case region + case stopSequences = "stop_sequences" + case systemPrompt = "system_prompt" + case temperature + case topK = "top_k" + case topP = "top_p" case id } @@ -99,24 +99,24 @@ public struct NLSearchModelCreateSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(accessToken, forKey: .accessToken) + try container.encodeIfPresent(accountId, forKey: .accountId) try container.encodeIfPresent(apiKey, forKey: .apiKey) try container.encodeIfPresent(apiUrl, forKey: .apiUrl) - try container.encodeIfPresent(maxBytes, forKey: .maxBytes) - try container.encodeIfPresent(temperature, forKey: .temperature) - try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) - try container.encodeIfPresent(topP, forKey: .topP) - try container.encodeIfPresent(topK, forKey: .topK) - try container.encodeIfPresent(stopSequences, forKey: .stopSequences) try container.encodeIfPresent(apiVersion, forKey: .apiVersion) - try container.encodeIfPresent(projectId, forKey: .projectId) - try container.encodeIfPresent(accessToken, forKey: .accessToken) - try container.encodeIfPresent(refreshToken, forKey: .refreshToken) try container.encodeIfPresent(clientId, forKey: .clientId) try container.encodeIfPresent(clientSecret, forKey: .clientSecret) - try container.encodeIfPresent(region, forKey: .region) + try container.encodeIfPresent(maxBytes, forKey: .maxBytes) try container.encodeIfPresent(maxOutputTokens, forKey: .maxOutputTokens) - try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(projectId, forKey: .projectId) + try container.encodeIfPresent(refreshToken, forKey: .refreshToken) + try container.encodeIfPresent(region, forKey: .region) + try container.encodeIfPresent(stopSequences, forKey: .stopSequences) + try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) + try container.encodeIfPresent(temperature, forKey: .temperature) + try container.encodeIfPresent(topK, forKey: .topK) + try container.encodeIfPresent(topP, forKey: .topP) try container.encodeIfPresent(id, forKey: .id) } } diff --git a/Sources/Typesense/Models/NLSearchModelSchema.swift b/Sources/Typesense/Models/NLSearchModelSchema.swift index 48f5cdd..34f633d 100644 --- a/Sources/Typesense/Models/NLSearchModelSchema.swift +++ b/Sources/Typesense/Models/NLSearchModelSchema.swift @@ -12,86 +12,86 @@ import AnyCodable public struct NLSearchModelSchema: Codable { - /** Name of the NL model to use */ - public var modelName: String? + /** Access token for GCP Vertex AI */ + public var accessToken: String? + /** Account ID for Cloudflare-specific models */ + public var accountId: String? /** API key for the NL model service */ public var apiKey: String? /** Custom API URL for the NL model service */ public var apiUrl: String? - /** Maximum number of bytes to process */ - public var maxBytes: Int? - /** Temperature parameter for the NL model */ - public var temperature: Double? - /** System prompt for the NL model */ - public var systemPrompt: String? - /** Top-p parameter for the NL model (Google-specific) */ - public var topP: Double? - /** Top-k parameter for the NL model (Google-specific) */ - public var topK: Int? - /** Stop sequences for the NL model (Google-specific) */ - public var stopSequences: [String]? /** API version for the NL model service */ public var apiVersion: String? - /** Project ID for GCP Vertex AI */ - public var projectId: String? - /** Access token for GCP Vertex AI */ - public var accessToken: String? - /** Refresh token for GCP Vertex AI */ - public var refreshToken: String? /** Client ID for GCP Vertex AI */ public var clientId: String? /** Client secret for GCP Vertex AI */ public var clientSecret: String? - /** Region for GCP Vertex AI */ - public var region: String? + /** Maximum number of bytes to process */ + public var maxBytes: Int? /** Maximum output tokens for GCP Vertex AI */ public var maxOutputTokens: Int? - /** Account ID for Cloudflare-specific models */ - public var accountId: String? + /** Name of the NL model to use */ + public var modelName: String? + /** Project ID for GCP Vertex AI */ + public var projectId: String? + /** Refresh token for GCP Vertex AI */ + public var refreshToken: String? + /** Region for GCP Vertex AI */ + public var region: String? + /** Stop sequences for the NL model (Google-specific) */ + public var stopSequences: [String]? + /** System prompt for the NL model */ + public var systemPrompt: String? + /** Temperature parameter for the NL model */ + public var temperature: Double? + /** Top-k parameter for the NL model (Google-specific) */ + public var topK: Int? + /** Top-p parameter for the NL model (Google-specific) */ + public var topP: Double? /** ID of the NL search model */ public var id: String - public init(modelName: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, maxBytes: Int? = nil, temperature: Double? = nil, systemPrompt: String? = nil, topP: Double? = nil, topK: Int? = nil, stopSequences: [String]? = nil, apiVersion: String? = nil, projectId: String? = nil, accessToken: String? = nil, refreshToken: String? = nil, clientId: String? = nil, clientSecret: String? = nil, region: String? = nil, maxOutputTokens: Int? = nil, accountId: String? = nil, id: String) { - self.modelName = modelName + public init(accessToken: String? = nil, accountId: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, apiVersion: String? = nil, clientId: String? = nil, clientSecret: String? = nil, maxBytes: Int? = nil, maxOutputTokens: Int? = nil, modelName: String? = nil, projectId: String? = nil, refreshToken: String? = nil, region: String? = nil, stopSequences: [String]? = nil, systemPrompt: String? = nil, temperature: Double? = nil, topK: Int? = nil, topP: Double? = nil, id: String) { + self.accessToken = accessToken + self.accountId = accountId self.apiKey = apiKey self.apiUrl = apiUrl - self.maxBytes = maxBytes - self.temperature = temperature - self.systemPrompt = systemPrompt - self.topP = topP - self.topK = topK - self.stopSequences = stopSequences self.apiVersion = apiVersion - self.projectId = projectId - self.accessToken = accessToken - self.refreshToken = refreshToken self.clientId = clientId self.clientSecret = clientSecret - self.region = region + self.maxBytes = maxBytes self.maxOutputTokens = maxOutputTokens - self.accountId = accountId + self.modelName = modelName + self.projectId = projectId + self.refreshToken = refreshToken + self.region = region + self.stopSequences = stopSequences + self.systemPrompt = systemPrompt + self.temperature = temperature + self.topK = topK + self.topP = topP self.id = id } public enum CodingKeys: String, CodingKey, CaseIterable { - case modelName = "model_name" + case accessToken = "access_token" + case accountId = "account_id" case apiKey = "api_key" case apiUrl = "api_url" - case maxBytes = "max_bytes" - case temperature - case systemPrompt = "system_prompt" - case topP = "top_p" - case topK = "top_k" - case stopSequences = "stop_sequences" case apiVersion = "api_version" - case projectId = "project_id" - case accessToken = "access_token" - case refreshToken = "refresh_token" case clientId = "client_id" case clientSecret = "client_secret" - case region + case maxBytes = "max_bytes" case maxOutputTokens = "max_output_tokens" - case accountId = "account_id" + case modelName = "model_name" + case projectId = "project_id" + case refreshToken = "refresh_token" + case region + case stopSequences = "stop_sequences" + case systemPrompt = "system_prompt" + case temperature + case topK = "top_k" + case topP = "top_p" case id } @@ -99,24 +99,24 @@ public struct NLSearchModelSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(accessToken, forKey: .accessToken) + try container.encodeIfPresent(accountId, forKey: .accountId) try container.encodeIfPresent(apiKey, forKey: .apiKey) try container.encodeIfPresent(apiUrl, forKey: .apiUrl) - try container.encodeIfPresent(maxBytes, forKey: .maxBytes) - try container.encodeIfPresent(temperature, forKey: .temperature) - try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) - try container.encodeIfPresent(topP, forKey: .topP) - try container.encodeIfPresent(topK, forKey: .topK) - try container.encodeIfPresent(stopSequences, forKey: .stopSequences) try container.encodeIfPresent(apiVersion, forKey: .apiVersion) - try container.encodeIfPresent(projectId, forKey: .projectId) - try container.encodeIfPresent(accessToken, forKey: .accessToken) - try container.encodeIfPresent(refreshToken, forKey: .refreshToken) try container.encodeIfPresent(clientId, forKey: .clientId) try container.encodeIfPresent(clientSecret, forKey: .clientSecret) - try container.encodeIfPresent(region, forKey: .region) + try container.encodeIfPresent(maxBytes, forKey: .maxBytes) try container.encodeIfPresent(maxOutputTokens, forKey: .maxOutputTokens) - try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(projectId, forKey: .projectId) + try container.encodeIfPresent(refreshToken, forKey: .refreshToken) + try container.encodeIfPresent(region, forKey: .region) + try container.encodeIfPresent(stopSequences, forKey: .stopSequences) + try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) + try container.encodeIfPresent(temperature, forKey: .temperature) + try container.encodeIfPresent(topK, forKey: .topK) + try container.encodeIfPresent(topP, forKey: .topP) try container.encode(id, forKey: .id) } } diff --git a/Sources/Typesense/Models/PresetUpsertSchemaValue.swift b/Sources/Typesense/Models/PresetUpsertSchemaValue.swift index 4e899a8..3730fa6 100644 --- a/Sources/Typesense/Models/PresetUpsertSchemaValue.swift +++ b/Sources/Typesense/Models/PresetUpsertSchemaValue.swift @@ -10,7 +10,7 @@ import Foundation import AnyCodable #endif -public enum PresetUpsertSchemaValue: Codable, JSONEncodable { +public enum PresetUpsertSchemaValue: Codable { case typeMultiSearchSearchesParameter(MultiSearchSearchesParameter) case typeSearchParameters(SearchParameters) diff --git a/Sources/Typesense/Models/SchemaChangeStatus.swift b/Sources/Typesense/Models/SchemaChangeStatus.swift index 3db6bce..da9155b 100644 --- a/Sources/Typesense/Models/SchemaChangeStatus.swift +++ b/Sources/Typesense/Models/SchemaChangeStatus.swift @@ -12,32 +12,32 @@ import AnyCodable public struct SchemaChangeStatus: Codable { + /** Number of documents that have been altered */ + public var alteredDocs: Int? /** Name of the collection being modified */ public var collection: String? /** Number of documents that have been validated */ public var validatedDocs: Int? - /** Number of documents that have been altered */ - public var alteredDocs: Int? - public init(collection: String? = nil, validatedDocs: Int? = nil, alteredDocs: Int? = nil) { + public init(alteredDocs: Int? = nil, collection: String? = nil, validatedDocs: Int? = nil) { + self.alteredDocs = alteredDocs self.collection = collection self.validatedDocs = validatedDocs - self.alteredDocs = alteredDocs } public enum CodingKeys: String, CodingKey, CaseIterable { + case alteredDocs = "altered_docs" case collection case validatedDocs = "validated_docs" - case alteredDocs = "altered_docs" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(alteredDocs, forKey: .alteredDocs) try container.encodeIfPresent(collection, forKey: .collection) try container.encodeIfPresent(validatedDocs, forKey: .validatedDocs) - try container.encodeIfPresent(alteredDocs, forKey: .alteredDocs) } } diff --git a/Sources/Typesense/Models/SearchGroupedHit.swift b/Sources/Typesense/Models/SearchGroupedHit.swift index 517a73a..20f2a1b 100644 --- a/Sources/Typesense/Models/SearchGroupedHit.swift +++ b/Sources/Typesense/Models/SearchGroupedHit.swift @@ -10,14 +10,14 @@ import Foundation import AnyCodable #endif -public struct SearchGroupedHit: Codable { +public struct SearchGroupedHit: Codable { public var found: Int? public var groupKey: [AnyCodable] /** The documents that matched the search query */ - public var hits: [SearchResultHit] + public var hits: [SearchResultHit] - public init(found: Int? = nil, groupKey: [AnyCodable], hits: [SearchResultHit]) { + public init(found: Int? = nil, groupKey: [AnyCodable], hits: [SearchResultHit]) { self.found = found self.groupKey = groupKey self.hits = hits diff --git a/Sources/Typesense/Models/SearchHighlight.swift b/Sources/Typesense/Models/SearchHighlight.swift index 3b4ff70..ae2a072 100644 --- a/Sources/Typesense/Models/SearchHighlight.swift +++ b/Sources/Typesense/Models/SearchHighlight.swift @@ -13,6 +13,9 @@ import AnyCodable public struct SearchHighlight: Codable { public var field: String? + /** The indices property will be present only for string[] fields and will contain the corresponding indices of the snippets in the search field */ + public var indices: [Int]? + public var matchedTokens: [AnyCodable]? /** Present only for (non-array) string fields */ public var snippet: String? /** Present only for (array) string[] fields */ @@ -21,28 +24,25 @@ public struct SearchHighlight: Codable { public var value: String? /** Full field value with highlighting, present only for (array) string[] fields */ public var values: [String]? - /** The indices property will be present only for string[] fields and will contain the corresponding indices of the snippets in the search field */ - public var indices: [Int]? - public var matchedTokens: [AnyCodable]? - public init(field: String? = nil, snippet: String? = nil, snippets: [String]? = nil, value: String? = nil, values: [String]? = nil, indices: [Int]? = nil, matchedTokens: [AnyCodable]? = nil) { + public init(field: String? = nil, indices: [Int]? = nil, matchedTokens: [AnyCodable]? = nil, snippet: String? = nil, snippets: [String]? = nil, value: String? = nil, values: [String]? = nil) { self.field = field + self.indices = indices + self.matchedTokens = matchedTokens self.snippet = snippet self.snippets = snippets self.value = value self.values = values - self.indices = indices - self.matchedTokens = matchedTokens } public enum CodingKeys: String, CodingKey, CaseIterable { case field + case indices + case matchedTokens = "matched_tokens" case snippet case snippets case value case values - case indices - case matchedTokens = "matched_tokens" } // Encodable protocol methods @@ -50,12 +50,12 @@ public struct SearchHighlight: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(field, forKey: .field) + try container.encodeIfPresent(indices, forKey: .indices) + try container.encodeIfPresent(matchedTokens, forKey: .matchedTokens) try container.encodeIfPresent(snippet, forKey: .snippet) try container.encodeIfPresent(snippets, forKey: .snippets) try container.encodeIfPresent(value, forKey: .value) try container.encodeIfPresent(values, forKey: .values) - try container.encodeIfPresent(indices, forKey: .indices) - try container.encodeIfPresent(matchedTokens, forKey: .matchedTokens) } } diff --git a/Sources/Typesense/Models/SearchParameters.swift b/Sources/Typesense/Models/SearchParameters.swift index 295cba8..e4dae94 100644 --- a/Sources/Typesense/Models/SearchParameters.swift +++ b/Sources/Typesense/Models/SearchParameters.swift @@ -12,371 +12,371 @@ import AnyCodable public struct SearchParameters: Codable { - /** 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. */ - public var q: String? - /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ - public var queryBy: String? - /** Whether to use natural language processing to parse the query. */ - public var nlQuery: Bool? - /** The ID of the natural language model to use. */ - public var nlModelId: 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. */ - public var queryByWeights: 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. */ - public var textMatchType: 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. */ - public var _prefix: String? - /** 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 */ - public var _infix: String? - /** 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. */ - public var maxExtraPrefix: Int? - /** 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. */ - public var maxExtraSuffix: Int? - /** Filter conditions for refining your open api validator search results. Separate multiple conditions with &&. */ - public var filterBy: String? - /** 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*. */ - public var maxFilterByCandidates: Int? - /** 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` */ - public var sortBy: String? + /** 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. */ + public var cacheTtl: Int? + /** Enable conversational search. */ + public var conversation: Bool? + /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ + public var conversationId: String? + /** The Id of Conversation Model to be used. */ + public var conversationModelId: String? + public var dropTokensMode: DropTokensMode? + /** 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 */ + public var dropTokensThreshold: Int? + /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ + public var enableAnalytics: Bool? = true + /** Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true */ + public var enableHighlightV1: Bool? = true + /** 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 */ + public var enableOverrides: Bool? = false + /** 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 */ + public var enableSynonyms: Bool? + /** Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. */ + public var enableTyposForAlphaNumericalTokens: Bool? + /** Make Typesense disable typos for numerical tokens. */ + public var enableTyposForNumericalTokens: Bool? = true + /** List of fields from the document to exclude in the search result */ + public var excludeFields: String? + /** 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). */ + public var exhaustiveSearch: Bool? /** A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. */ public var facetBy: String? - /** Maximum number of facet values to be returned. */ - public var maxFacetValues: Int? /** 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\". */ public var facetQuery: String? - /** The number of typographical errors (1 or 2) that would be tolerated. Default: 2 */ - public var numTypos: String? - /** Results from this specific page number would be fetched. */ - public var page: Int? - /** Number of results to fetch per page. Default: 10 */ - public var perPage: Int? - /** Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. */ - public var limit: Int? - /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ - public var offset: Int? + /** Comma separated string of nested facet fields whose parent object should be returned in facet response. */ + public var facetReturnParent: String? + /** Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). */ + public var facetStrategy: String? + /** Filter conditions for refining your open api validator search results. Separate multiple conditions with &&. */ + public var filterBy: String? + /** Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false */ + public var filterCuratedHits: Bool? /** 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. */ public var groupBy: String? /** 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 */ public var groupLimit: Int? /** 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 */ public var groupMissingValues: Bool? - /** List of fields from the document to include in the search result */ - public var includeFields: String? - /** List of fields from the document to exclude in the search result */ - public var excludeFields: String? - /** List of fields which should be highlighted fully without snippeting */ - public var highlightFullFields: 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`. */ + public var hiddenHits: String? /** The number of tokens that should surround the highlighted text on each side. Default: 4 */ public var highlightAffixNumTokens: Int? - /** The start tag used for the highlighted snippets. Default: `` */ - public var highlightStartTag: String? /** The end tag used for the highlighted snippets. Default: `` */ public var highlightEndTag: String? - /** Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true */ - public var enableHighlightV1: Bool? = true - /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ - public var enableAnalytics: Bool? = true - /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ - public var snippetThreshold: Int? - /** List of synonym set names to associate with this search query */ - public var synonymSets: String? - /** 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 */ - public var dropTokensThreshold: Int? - public var dropTokensMode: DropTokensMode? - /** 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 */ - public var typoTokensThreshold: Int? - /** Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. */ - public var enableTyposForAlphaNumericalTokens: 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 */ - public var filterCuratedHits: 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 */ - public var enableSynonyms: Bool? - /** Allow synonym resolution on word prefixes in the query. Default: false */ - public var synonymPrefix: Bool? - /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ - public var synonymNumTypos: Int? - /** 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`. */ - public var pinnedHits: 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`. */ - public var hiddenHits: String? - /** Comma separated list of tags to trigger the curations rules that match the tags. */ - public var overrideTags: String? /** A list of custom fields that must be highlighted even if you don't query for them */ public var highlightFields: 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`. */ - public var splitJoinTokens: String? + /** List of fields which should be highlighted fully without snippeting */ + public var highlightFullFields: String? + /** The start tag used for the highlighted snippets. Default: `` */ + public var highlightStartTag: String? + /** List of fields from the document to include in the search result */ + public var includeFields: String? + /** 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 */ + public var _infix: String? + /** Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. */ + public var limit: Int? + /** Control the number of words that Typesense considers for typo and prefix searching. */ + public var maxCandidates: Int? + /** 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. */ + public var maxExtraPrefix: Int? + /** 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. */ + public var maxExtraSuffix: Int? + /** Maximum number of facet values to be returned. */ + public var maxFacetValues: Int? + /** 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*. */ + public var maxFilterByCandidates: Int? + /** Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ + public var minLen1typo: Int? + /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ + public var minLen2typo: Int? + /** The ID of the natural language model to use. */ + public var nlModelId: String? + /** Whether to use natural language processing to parse the query. */ + public var nlQuery: Bool? + /** The number of typographical errors (1 or 2) that would be tolerated. Default: 2 */ + public var numTypos: String? + /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ + public var offset: Int? + /** Comma separated list of tags to trigger the curations rules that match the tags. */ + public var overrideTags: String? + /** Results from this specific page number would be fetched. */ + public var page: Int? + /** Number of results to fetch per page. Default: 10 */ + public var perPage: Int? + /** 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`. */ + public var pinnedHits: String? /** 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 */ public var preSegmentedQuery: Bool? + /** 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. */ + public var _prefix: String? /** Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. */ public var preset: String? - /** 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 */ - public var enableOverrides: Bool? = false /** Set this parameter to true to ensure that an exact match is ranked above the others */ public var prioritizeExactMatch: Bool? = true - /** Control the number of words that Typesense considers for typo and prefix searching. */ - public var maxCandidates: Int? - /** Make Typesense prioritize documents where the query words appear earlier in the text. */ - public var prioritizeTokenPosition: Bool? = false /** Make Typesense prioritize documents where the query words appear in more number of fields. */ public var prioritizeNumMatchingFields: Bool? = true - /** Make Typesense disable typos for numerical tokens. */ - public var enableTyposForNumericalTokens: Bool? = true - /** 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). */ - public var exhaustiveSearch: Bool? + /** Make Typesense prioritize documents where the query words appear earlier in the text. */ + public var prioritizeTokenPosition: Bool? = false + /** 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. */ + public var q: String? + /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ + public var queryBy: 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. */ + public var queryByWeights: String? + /** Number of times to retry fetching remote embeddings. */ + public var remoteEmbeddingNumTries: Int? + /** Timeout (in milliseconds) for fetching remote embeddings. */ + public var remoteEmbeddingTimeoutMs: Int? /** 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. */ public var searchCutoffMs: Int? + /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ + public var snippetThreshold: Int? + /** 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` */ + public var sortBy: 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`. */ + public var splitJoinTokens: String? + /** Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. */ + public var stopwords: String? + /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ + public var synonymNumTypos: Int? + /** Allow synonym resolution on word prefixes in the query. Default: false */ + public var synonymPrefix: Bool? + /** List of synonym set names to associate with this search query */ + public var synonymSets: 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. */ + public var textMatchType: String? + /** 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 */ + public var typoTokensThreshold: Int? /** Enable server side caching of search query results. By default, caching is disabled. */ public var useCache: Bool? - /** 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. */ - public var cacheTtl: Int? - /** Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ - public var minLen1typo: Int? - /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ - public var minLen2typo: Int? /** Vector query expression for fetching documents \"closest\" to a given query/document vector. */ public var vectorQuery: String? - /** Timeout (in milliseconds) for fetching remote embeddings. */ - public var remoteEmbeddingTimeoutMs: Int? - /** Number of times to retry fetching remote embeddings. */ - public var remoteEmbeddingNumTries: Int? - /** Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). */ - public var facetStrategy: String? - /** Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. */ - public var stopwords: String? - /** Comma separated string of nested facet fields whose parent object should be returned in facet response. */ - public var facetReturnParent: String? /** The base64 encoded audio file in 16 khz 16-bit WAV format. */ public var voiceQuery: String? - /** Enable conversational search. */ - public var conversation: Bool? - /** The Id of Conversation Model to be used. */ - public var conversationModelId: String? - /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ - public var conversationId: String? - public init(q: String? = nil, queryBy: String? = nil, nlQuery: Bool? = nil, nlModelId: String? = nil, queryByWeights: String? = nil, textMatchType: String? = nil, _prefix: String? = nil, _infix: String? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, filterBy: String? = nil, maxFilterByCandidates: Int? = nil, sortBy: String? = nil, facetBy: String? = nil, maxFacetValues: Int? = nil, facetQuery: String? = nil, numTypos: String? = nil, page: Int? = nil, perPage: Int? = nil, limit: Int? = nil, offset: Int? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, includeFields: String? = nil, excludeFields: String? = nil, highlightFullFields: String? = nil, highlightAffixNumTokens: Int? = nil, highlightStartTag: String? = nil, highlightEndTag: String? = nil, enableHighlightV1: Bool? = true, enableAnalytics: Bool? = true, snippetThreshold: Int? = nil, synonymSets: String? = nil, dropTokensThreshold: Int? = nil, dropTokensMode: DropTokensMode? = nil, typoTokensThreshold: Int? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, filterCuratedHits: Bool? = nil, enableSynonyms: Bool? = nil, synonymPrefix: Bool? = nil, synonymNumTypos: Int? = nil, pinnedHits: String? = nil, hiddenHits: String? = nil, overrideTags: String? = nil, highlightFields: String? = nil, splitJoinTokens: String? = nil, preSegmentedQuery: Bool? = nil, preset: String? = nil, enableOverrides: Bool? = false, prioritizeExactMatch: Bool? = true, maxCandidates: Int? = nil, prioritizeTokenPosition: Bool? = false, prioritizeNumMatchingFields: Bool? = true, enableTyposForNumericalTokens: Bool? = true, exhaustiveSearch: Bool? = nil, searchCutoffMs: Int? = nil, useCache: Bool? = nil, cacheTtl: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, vectorQuery: String? = nil, remoteEmbeddingTimeoutMs: Int? = nil, remoteEmbeddingNumTries: Int? = nil, facetStrategy: String? = nil, stopwords: String? = nil, facetReturnParent: String? = nil, voiceQuery: String? = nil, conversation: Bool? = nil, conversationModelId: String? = nil, conversationId: String? = nil) { - self.q = q - self.queryBy = queryBy - self.nlQuery = nlQuery - self.nlModelId = nlModelId - self.queryByWeights = queryByWeights - self.textMatchType = textMatchType - self._prefix = _prefix - self._infix = _infix - self.maxExtraPrefix = maxExtraPrefix - self.maxExtraSuffix = maxExtraSuffix - self.filterBy = filterBy - self.maxFilterByCandidates = maxFilterByCandidates - self.sortBy = sortBy + public init(cacheTtl: Int? = nil, conversation: Bool? = nil, conversationId: String? = nil, conversationModelId: String? = nil, dropTokensMode: DropTokensMode? = nil, dropTokensThreshold: Int? = nil, enableAnalytics: Bool? = true, enableHighlightV1: Bool? = true, enableOverrides: Bool? = false, enableSynonyms: Bool? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, enableTyposForNumericalTokens: Bool? = true, excludeFields: String? = nil, exhaustiveSearch: Bool? = nil, facetBy: String? = nil, facetQuery: String? = nil, facetReturnParent: String? = nil, facetStrategy: String? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, hiddenHits: String? = nil, highlightAffixNumTokens: Int? = nil, highlightEndTag: String? = nil, highlightFields: String? = nil, highlightFullFields: String? = nil, highlightStartTag: String? = nil, includeFields: String? = nil, _infix: String? = nil, limit: Int? = nil, maxCandidates: Int? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, maxFacetValues: Int? = nil, maxFilterByCandidates: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, nlModelId: String? = nil, nlQuery: Bool? = nil, numTypos: String? = nil, offset: Int? = nil, overrideTags: String? = nil, page: Int? = nil, perPage: Int? = nil, pinnedHits: String? = nil, preSegmentedQuery: Bool? = nil, _prefix: String? = nil, preset: String? = nil, prioritizeExactMatch: Bool? = true, prioritizeNumMatchingFields: Bool? = true, prioritizeTokenPosition: Bool? = false, q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, remoteEmbeddingNumTries: Int? = nil, remoteEmbeddingTimeoutMs: Int? = nil, searchCutoffMs: Int? = nil, snippetThreshold: Int? = nil, sortBy: String? = nil, splitJoinTokens: String? = nil, stopwords: String? = nil, synonymNumTypos: Int? = nil, synonymPrefix: Bool? = nil, synonymSets: String? = nil, textMatchType: String? = nil, typoTokensThreshold: Int? = nil, useCache: Bool? = nil, vectorQuery: String? = nil, voiceQuery: String? = nil) { + self.cacheTtl = cacheTtl + self.conversation = conversation + self.conversationId = conversationId + self.conversationModelId = conversationModelId + self.dropTokensMode = dropTokensMode + self.dropTokensThreshold = dropTokensThreshold + self.enableAnalytics = enableAnalytics + self.enableHighlightV1 = enableHighlightV1 + self.enableOverrides = enableOverrides + self.enableSynonyms = enableSynonyms + self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens + self.enableTyposForNumericalTokens = enableTyposForNumericalTokens + self.excludeFields = excludeFields + self.exhaustiveSearch = exhaustiveSearch self.facetBy = facetBy - self.maxFacetValues = maxFacetValues self.facetQuery = facetQuery - self.numTypos = numTypos - self.page = page - self.perPage = perPage - self.limit = limit - self.offset = offset + self.facetReturnParent = facetReturnParent + self.facetStrategy = facetStrategy + self.filterBy = filterBy + self.filterCuratedHits = filterCuratedHits self.groupBy = groupBy self.groupLimit = groupLimit self.groupMissingValues = groupMissingValues - self.includeFields = includeFields - self.excludeFields = excludeFields - self.highlightFullFields = highlightFullFields + self.hiddenHits = hiddenHits self.highlightAffixNumTokens = highlightAffixNumTokens - self.highlightStartTag = highlightStartTag self.highlightEndTag = highlightEndTag - self.enableHighlightV1 = enableHighlightV1 - self.enableAnalytics = enableAnalytics - self.snippetThreshold = snippetThreshold - self.synonymSets = synonymSets - self.dropTokensThreshold = dropTokensThreshold - self.dropTokensMode = dropTokensMode - self.typoTokensThreshold = typoTokensThreshold - self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens - self.filterCuratedHits = filterCuratedHits - self.enableSynonyms = enableSynonyms - self.synonymPrefix = synonymPrefix - self.synonymNumTypos = synonymNumTypos + self.highlightFields = highlightFields + self.highlightFullFields = highlightFullFields + self.highlightStartTag = highlightStartTag + self.includeFields = includeFields + self._infix = _infix + self.limit = limit + self.maxCandidates = maxCandidates + self.maxExtraPrefix = maxExtraPrefix + self.maxExtraSuffix = maxExtraSuffix + self.maxFacetValues = maxFacetValues + self.maxFilterByCandidates = maxFilterByCandidates + self.minLen1typo = minLen1typo + self.minLen2typo = minLen2typo + self.nlModelId = nlModelId + self.nlQuery = nlQuery + self.numTypos = numTypos + self.offset = offset + self.overrideTags = overrideTags + self.page = page + self.perPage = perPage self.pinnedHits = pinnedHits - self.hiddenHits = hiddenHits - self.overrideTags = overrideTags - self.highlightFields = highlightFields - self.splitJoinTokens = splitJoinTokens self.preSegmentedQuery = preSegmentedQuery + self._prefix = _prefix self.preset = preset - self.enableOverrides = enableOverrides self.prioritizeExactMatch = prioritizeExactMatch - self.maxCandidates = maxCandidates - self.prioritizeTokenPosition = prioritizeTokenPosition self.prioritizeNumMatchingFields = prioritizeNumMatchingFields - self.enableTyposForNumericalTokens = enableTyposForNumericalTokens - self.exhaustiveSearch = exhaustiveSearch + self.prioritizeTokenPosition = prioritizeTokenPosition + self.q = q + self.queryBy = queryBy + self.queryByWeights = queryByWeights + self.remoteEmbeddingNumTries = remoteEmbeddingNumTries + self.remoteEmbeddingTimeoutMs = remoteEmbeddingTimeoutMs self.searchCutoffMs = searchCutoffMs + self.snippetThreshold = snippetThreshold + self.sortBy = sortBy + self.splitJoinTokens = splitJoinTokens + self.stopwords = stopwords + self.synonymNumTypos = synonymNumTypos + self.synonymPrefix = synonymPrefix + self.synonymSets = synonymSets + self.textMatchType = textMatchType + self.typoTokensThreshold = typoTokensThreshold self.useCache = useCache - self.cacheTtl = cacheTtl - self.minLen1typo = minLen1typo - self.minLen2typo = minLen2typo self.vectorQuery = vectorQuery - self.remoteEmbeddingTimeoutMs = remoteEmbeddingTimeoutMs - self.remoteEmbeddingNumTries = remoteEmbeddingNumTries - self.facetStrategy = facetStrategy - self.stopwords = stopwords - self.facetReturnParent = facetReturnParent self.voiceQuery = voiceQuery - self.conversation = conversation - self.conversationModelId = conversationModelId - self.conversationId = conversationId } public enum CodingKeys: String, CodingKey, CaseIterable { - case q - case queryBy = "query_by" - case nlQuery = "nl_query" - case nlModelId = "nl_model_id" - case queryByWeights = "query_by_weights" - case textMatchType = "text_match_type" - case _prefix = "prefix" - case _infix = "infix" - case maxExtraPrefix = "max_extra_prefix" - case maxExtraSuffix = "max_extra_suffix" - case filterBy = "filter_by" - case maxFilterByCandidates = "max_filter_by_candidates" - case sortBy = "sort_by" + case cacheTtl = "cache_ttl" + case conversation + case conversationId = "conversation_id" + case conversationModelId = "conversation_model_id" + case dropTokensMode = "drop_tokens_mode" + case dropTokensThreshold = "drop_tokens_threshold" + case enableAnalytics = "enable_analytics" + case enableHighlightV1 = "enable_highlight_v1" + case enableOverrides = "enable_overrides" + case enableSynonyms = "enable_synonyms" + case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" + case enableTyposForNumericalTokens = "enable_typos_for_numerical_tokens" + case excludeFields = "exclude_fields" + case exhaustiveSearch = "exhaustive_search" case facetBy = "facet_by" - case maxFacetValues = "max_facet_values" case facetQuery = "facet_query" - case numTypos = "num_typos" - case page - case perPage = "per_page" - case limit - case offset + case facetReturnParent = "facet_return_parent" + case facetStrategy = "facet_strategy" + case filterBy = "filter_by" + case filterCuratedHits = "filter_curated_hits" case groupBy = "group_by" case groupLimit = "group_limit" case groupMissingValues = "group_missing_values" - case includeFields = "include_fields" - case excludeFields = "exclude_fields" - case highlightFullFields = "highlight_full_fields" + case hiddenHits = "hidden_hits" case highlightAffixNumTokens = "highlight_affix_num_tokens" - case highlightStartTag = "highlight_start_tag" case highlightEndTag = "highlight_end_tag" - case enableHighlightV1 = "enable_highlight_v1" - case enableAnalytics = "enable_analytics" - case snippetThreshold = "snippet_threshold" - case synonymSets = "synonym_sets" - case dropTokensThreshold = "drop_tokens_threshold" - case dropTokensMode = "drop_tokens_mode" - case typoTokensThreshold = "typo_tokens_threshold" - case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" - case filterCuratedHits = "filter_curated_hits" - case enableSynonyms = "enable_synonyms" - case synonymPrefix = "synonym_prefix" - case synonymNumTypos = "synonym_num_typos" - case pinnedHits = "pinned_hits" - case hiddenHits = "hidden_hits" - case overrideTags = "override_tags" case highlightFields = "highlight_fields" - case splitJoinTokens = "split_join_tokens" + case highlightFullFields = "highlight_full_fields" + case highlightStartTag = "highlight_start_tag" + case includeFields = "include_fields" + case _infix = "infix" + case limit + case maxCandidates = "max_candidates" + case maxExtraPrefix = "max_extra_prefix" + case maxExtraSuffix = "max_extra_suffix" + case maxFacetValues = "max_facet_values" + case maxFilterByCandidates = "max_filter_by_candidates" + case minLen1typo = "min_len_1typo" + case minLen2typo = "min_len_2typo" + case nlModelId = "nl_model_id" + case nlQuery = "nl_query" + case numTypos = "num_typos" + case offset + case overrideTags = "override_tags" + case page + case perPage = "per_page" + case pinnedHits = "pinned_hits" case preSegmentedQuery = "pre_segmented_query" + case _prefix = "prefix" case preset - case enableOverrides = "enable_overrides" case prioritizeExactMatch = "prioritize_exact_match" - case maxCandidates = "max_candidates" - case prioritizeTokenPosition = "prioritize_token_position" case prioritizeNumMatchingFields = "prioritize_num_matching_fields" - case enableTyposForNumericalTokens = "enable_typos_for_numerical_tokens" - case exhaustiveSearch = "exhaustive_search" + case prioritizeTokenPosition = "prioritize_token_position" + case q + case queryBy = "query_by" + case queryByWeights = "query_by_weights" + case remoteEmbeddingNumTries = "remote_embedding_num_tries" + case remoteEmbeddingTimeoutMs = "remote_embedding_timeout_ms" case searchCutoffMs = "search_cutoff_ms" + case snippetThreshold = "snippet_threshold" + case sortBy = "sort_by" + case splitJoinTokens = "split_join_tokens" + case stopwords + case synonymNumTypos = "synonym_num_typos" + case synonymPrefix = "synonym_prefix" + case synonymSets = "synonym_sets" + case textMatchType = "text_match_type" + case typoTokensThreshold = "typo_tokens_threshold" case useCache = "use_cache" - case cacheTtl = "cache_ttl" - case minLen1typo = "min_len_1typo" - case minLen2typo = "min_len_2typo" case vectorQuery = "vector_query" - case remoteEmbeddingTimeoutMs = "remote_embedding_timeout_ms" - case remoteEmbeddingNumTries = "remote_embedding_num_tries" - case facetStrategy = "facet_strategy" - case stopwords - case facetReturnParent = "facet_return_parent" case voiceQuery = "voice_query" - case conversation - case conversationModelId = "conversation_model_id" - case conversationId = "conversation_id" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(q, forKey: .q) - try container.encodeIfPresent(queryBy, forKey: .queryBy) - try container.encodeIfPresent(nlQuery, forKey: .nlQuery) - try container.encodeIfPresent(nlModelId, forKey: .nlModelId) - try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) - try container.encodeIfPresent(textMatchType, forKey: .textMatchType) - try container.encodeIfPresent(_prefix, forKey: ._prefix) - try container.encodeIfPresent(_infix, forKey: ._infix) - try container.encodeIfPresent(maxExtraPrefix, forKey: .maxExtraPrefix) - try container.encodeIfPresent(maxExtraSuffix, forKey: .maxExtraSuffix) - try container.encodeIfPresent(filterBy, forKey: .filterBy) - try container.encodeIfPresent(maxFilterByCandidates, forKey: .maxFilterByCandidates) - try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) + try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encodeIfPresent(conversationId, forKey: .conversationId) + try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) + try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) + try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) + try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) + try container.encodeIfPresent(enableHighlightV1, forKey: .enableHighlightV1) + try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) + try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) + try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) + try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) + try container.encodeIfPresent(excludeFields, forKey: .excludeFields) + try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) try container.encodeIfPresent(facetBy, forKey: .facetBy) - try container.encodeIfPresent(maxFacetValues, forKey: .maxFacetValues) try container.encodeIfPresent(facetQuery, forKey: .facetQuery) - try container.encodeIfPresent(numTypos, forKey: .numTypos) - try container.encodeIfPresent(page, forKey: .page) - try container.encodeIfPresent(perPage, forKey: .perPage) - try container.encodeIfPresent(limit, forKey: .limit) - try container.encodeIfPresent(offset, forKey: .offset) + try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) + try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) + try container.encodeIfPresent(filterBy, forKey: .filterBy) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) try container.encodeIfPresent(groupBy, forKey: .groupBy) try container.encodeIfPresent(groupLimit, forKey: .groupLimit) try container.encodeIfPresent(groupMissingValues, forKey: .groupMissingValues) - try container.encodeIfPresent(includeFields, forKey: .includeFields) - try container.encodeIfPresent(excludeFields, forKey: .excludeFields) - try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) + try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) try container.encodeIfPresent(highlightAffixNumTokens, forKey: .highlightAffixNumTokens) - try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) try container.encodeIfPresent(highlightEndTag, forKey: .highlightEndTag) - try container.encodeIfPresent(enableHighlightV1, forKey: .enableHighlightV1) - try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) - try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) - try container.encodeIfPresent(synonymSets, forKey: .synonymSets) - try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) - try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) - try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) - try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) - try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) - try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) - try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) - try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) - try container.encodeIfPresent(pinnedHits, forKey: .pinnedHits) - try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) - try container.encodeIfPresent(overrideTags, forKey: .overrideTags) try container.encodeIfPresent(highlightFields, forKey: .highlightFields) - try container.encodeIfPresent(splitJoinTokens, forKey: .splitJoinTokens) + try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) + try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) + try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(_infix, forKey: ._infix) + try container.encodeIfPresent(limit, forKey: .limit) + try container.encodeIfPresent(maxCandidates, forKey: .maxCandidates) + try container.encodeIfPresent(maxExtraPrefix, forKey: .maxExtraPrefix) + try container.encodeIfPresent(maxExtraSuffix, forKey: .maxExtraSuffix) + try container.encodeIfPresent(maxFacetValues, forKey: .maxFacetValues) + try container.encodeIfPresent(maxFilterByCandidates, forKey: .maxFilterByCandidates) + try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) + try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) + try container.encodeIfPresent(nlModelId, forKey: .nlModelId) + try container.encodeIfPresent(nlQuery, forKey: .nlQuery) + try container.encodeIfPresent(numTypos, forKey: .numTypos) + try container.encodeIfPresent(offset, forKey: .offset) + try container.encodeIfPresent(overrideTags, forKey: .overrideTags) + try container.encodeIfPresent(page, forKey: .page) + try container.encodeIfPresent(perPage, forKey: .perPage) + try container.encodeIfPresent(pinnedHits, forKey: .pinnedHits) try container.encodeIfPresent(preSegmentedQuery, forKey: .preSegmentedQuery) + try container.encodeIfPresent(_prefix, forKey: ._prefix) try container.encodeIfPresent(preset, forKey: .preset) - try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) try container.encodeIfPresent(prioritizeExactMatch, forKey: .prioritizeExactMatch) - try container.encodeIfPresent(maxCandidates, forKey: .maxCandidates) - try container.encodeIfPresent(prioritizeTokenPosition, forKey: .prioritizeTokenPosition) try container.encodeIfPresent(prioritizeNumMatchingFields, forKey: .prioritizeNumMatchingFields) - try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) - try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) + try container.encodeIfPresent(prioritizeTokenPosition, forKey: .prioritizeTokenPosition) + try container.encodeIfPresent(q, forKey: .q) + try container.encodeIfPresent(queryBy, forKey: .queryBy) + try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) + try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) + try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) try container.encodeIfPresent(searchCutoffMs, forKey: .searchCutoffMs) + try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) + try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(splitJoinTokens, forKey: .splitJoinTokens) + try container.encodeIfPresent(stopwords, forKey: .stopwords) + try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) + try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) + try container.encodeIfPresent(synonymSets, forKey: .synonymSets) + try container.encodeIfPresent(textMatchType, forKey: .textMatchType) + try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) try container.encodeIfPresent(useCache, forKey: .useCache) - try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) - try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) - try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) try container.encodeIfPresent(vectorQuery, forKey: .vectorQuery) - try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) - try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) - try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) - try container.encodeIfPresent(stopwords, forKey: .stopwords) - try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) - try container.encodeIfPresent(conversation, forKey: .conversation) - try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) - try container.encodeIfPresent(conversationId, forKey: .conversationId) } } diff --git a/Sources/Typesense/Models/SearchRequestParams.swift b/Sources/Typesense/Models/SearchRequestParams.swift index 11e81b5..c6c0274 100644 --- a/Sources/Typesense/Models/SearchRequestParams.swift +++ b/Sources/Typesense/Models/SearchRequestParams.swift @@ -13,21 +13,21 @@ import AnyCodable public struct SearchRequestParams: Codable { public var collectionName: String - public var q: String public var perPage: Int + public var q: String public var voiceQuery: SearchRequestParamsVoiceQuery? - public init(collectionName: String, q: String, perPage: Int, voiceQuery: SearchRequestParamsVoiceQuery? = nil) { + public init(collectionName: String, perPage: Int, q: String, voiceQuery: SearchRequestParamsVoiceQuery? = nil) { self.collectionName = collectionName - self.q = q self.perPage = perPage + self.q = q self.voiceQuery = voiceQuery } public enum CodingKeys: String, CodingKey, CaseIterable { case collectionName = "collection_name" - case q case perPage = "per_page" + case q case voiceQuery = "voice_query" } @@ -36,8 +36,8 @@ public struct SearchRequestParams: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(collectionName, forKey: .collectionName) - try container.encode(q, forKey: .q) try container.encode(perPage, forKey: .perPage) + try container.encode(q, forKey: .q) try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) } } diff --git a/Sources/Typesense/Models/SearchResult.swift b/Sources/Typesense/Models/SearchResult.swift index 84d5de9..bcb00ab 100644 --- a/Sources/Typesense/Models/SearchResult.swift +++ b/Sources/Typesense/Models/SearchResult.swift @@ -12,77 +12,77 @@ import AnyCodable public struct SearchResult: Codable { + public var conversation: SearchResultConversation? public var facetCounts: [FacetCounts]? /** The number of documents found */ public var found: Int? public var foundDocs: Int? - /** The number of milliseconds the search took */ - public var searchTimeMs: Int? + public var groupedHits: [SearchGroupedHit]? + /** The documents that matched the search query */ + public var hits: [SearchResultHit]? + /** Custom JSON object that can be returned in the search response */ + public var metadata: [String: AnyCodable]? /** The total number of documents in the collection */ public var outOf: Int? - /** Whether the search was cut off */ - public var searchCutoff: Bool? /** The search result page number */ public var page: Int? - public var groupedHits: [SearchGroupedHit]? - /** The documents that matched the search query */ - public var hits: [SearchResultHit]? public var requestParams: SearchRequestParams? - public var conversation: SearchResultConversation? + /** Whether the search was cut off */ + public var searchCutoff: Bool? + /** The number of milliseconds the search took */ + public var searchTimeMs: Int? /** Returned only for union query response. */ public var unionRequestParams: [SearchRequestParams]? - /** Custom JSON object that can be returned in the search response */ - public var metadata: [String: AnyCodable]? - public init(facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, searchTimeMs: Int? = nil, outOf: Int? = nil, searchCutoff: Bool? = nil, page: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, requestParams: SearchRequestParams? = nil, conversation: SearchResultConversation? = nil, unionRequestParams: [SearchRequestParams]? = nil, metadata: [String: AnyCodable]? = nil) { + public init(conversation: SearchResultConversation? = nil, facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, metadata: [String: AnyCodable]? = nil, outOf: Int? = nil, page: Int? = nil, requestParams: SearchRequestParams? = nil, searchCutoff: Bool? = nil, searchTimeMs: Int? = nil, unionRequestParams: [SearchRequestParams]? = nil) { + self.conversation = conversation self.facetCounts = facetCounts self.found = found self.foundDocs = foundDocs - self.searchTimeMs = searchTimeMs - self.outOf = outOf - self.searchCutoff = searchCutoff - self.page = page self.groupedHits = groupedHits self.hits = hits + self.metadata = metadata + self.outOf = outOf + self.page = page self.requestParams = requestParams - self.conversation = conversation + self.searchCutoff = searchCutoff + self.searchTimeMs = searchTimeMs self.unionRequestParams = unionRequestParams - self.metadata = metadata } public enum CodingKeys: String, CodingKey, CaseIterable { + case conversation case facetCounts = "facet_counts" case found case foundDocs = "found_docs" - case searchTimeMs = "search_time_ms" - case outOf = "out_of" - case searchCutoff = "search_cutoff" - case page case groupedHits = "grouped_hits" case hits + case metadata + case outOf = "out_of" + case page case requestParams = "request_params" - case conversation + case searchCutoff = "search_cutoff" + case searchTimeMs = "search_time_ms" case unionRequestParams = "union_request_params" - case metadata } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(conversation, forKey: .conversation) try container.encodeIfPresent(facetCounts, forKey: .facetCounts) try container.encodeIfPresent(found, forKey: .found) try container.encodeIfPresent(foundDocs, forKey: .foundDocs) - try container.encodeIfPresent(searchTimeMs, forKey: .searchTimeMs) - try container.encodeIfPresent(outOf, forKey: .outOf) - try container.encodeIfPresent(searchCutoff, forKey: .searchCutoff) - try container.encodeIfPresent(page, forKey: .page) try container.encodeIfPresent(groupedHits, forKey: .groupedHits) try container.encodeIfPresent(hits, forKey: .hits) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encodeIfPresent(outOf, forKey: .outOf) + try container.encodeIfPresent(page, forKey: .page) try container.encodeIfPresent(requestParams, forKey: .requestParams) - try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encodeIfPresent(searchCutoff, forKey: .searchCutoff) + try container.encodeIfPresent(searchTimeMs, forKey: .searchTimeMs) try container.encodeIfPresent(unionRequestParams, forKey: .unionRequestParams) - try container.encodeIfPresent(metadata, forKey: .metadata) } } diff --git a/Sources/Typesense/Models/SearchResultHit.swift b/Sources/Typesense/Models/SearchResultHit.swift index 01a9d57..4ac7486 100644 --- a/Sources/Typesense/Models/SearchResultHit.swift +++ b/Sources/Typesense/Models/SearchResultHit.swift @@ -10,61 +10,61 @@ import Foundation import AnyCodable #endif -public struct SearchResultHit: Codable { +public struct SearchResultHit: Codable { - /** (Deprecated) Contains highlighted portions of the search fields */ - public var highlights: [SearchHighlight]? - /** Highlighted version of the matching document */ - public var highlight: [String: AnyCodable]? /** Can be any key-value pair */ public var document: [String: AnyCodable]? - public var textMatch: Int64? - public var textMatchInfo: SearchResultHitTextMatchInfo? /** Can be any key-value pair */ public var geoDistanceMeters: [String: Int]? - /** Distance between the query vector and matching document's vector value */ - public var vectorDistance: Float? + /** Highlighted version of the matching document */ + public var highlight: [String: AnyCodable]? + /** (Deprecated) Contains highlighted portions of the search fields */ + public var highlights: [SearchHighlight]? public var hybridSearchInfo: SearchResultHitHybridSearchInfo? /** Returned only for union query response. Indicates the index of the query which this document matched to. */ public var searchIndex: Int? + public var textMatch: Int64? + public var textMatchInfo: SearchResultHitTextMatchInfo? + /** Distance between the query vector and matching document's vector value */ + public var vectorDistance: Float? - public init(highlights: [SearchHighlight]? = nil, highlight: [String: AnyCodable]? = nil, document: [String: AnyCodable]? = nil, textMatch: Int64? = nil, textMatchInfo: SearchResultHitTextMatchInfo? = nil, geoDistanceMeters: [String: Int]? = nil, vectorDistance: Float? = nil, hybridSearchInfo: SearchResultHitHybridSearchInfo? = nil, searchIndex: Int? = nil) { - self.highlights = highlights - self.highlight = highlight + public init(document: [String: AnyCodable]? = nil, geoDistanceMeters: [String: Int]? = nil, highlight: [String: AnyCodable]? = nil, highlights: [SearchHighlight]? = nil, hybridSearchInfo: SearchResultHitHybridSearchInfo? = nil, searchIndex: Int? = nil, textMatch: Int64? = nil, textMatchInfo: SearchResultHitTextMatchInfo? = nil, vectorDistance: Float? = nil) { self.document = document - self.textMatch = textMatch - self.textMatchInfo = textMatchInfo self.geoDistanceMeters = geoDistanceMeters - self.vectorDistance = vectorDistance + self.highlight = highlight + self.highlights = highlights self.hybridSearchInfo = hybridSearchInfo self.searchIndex = searchIndex + self.textMatch = textMatch + self.textMatchInfo = textMatchInfo + self.vectorDistance = vectorDistance } public enum CodingKeys: String, CodingKey, CaseIterable { - case highlights - case highlight case document - case textMatch = "text_match" - case textMatchInfo = "text_match_info" case geoDistanceMeters = "geo_distance_meters" - case vectorDistance = "vector_distance" + case highlight + case highlights case hybridSearchInfo = "hybrid_search_info" case searchIndex = "search_index" + case textMatch = "text_match" + case textMatchInfo = "text_match_info" + case vectorDistance = "vector_distance" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(highlights, forKey: .highlights) - try container.encodeIfPresent(highlight, forKey: .highlight) try container.encodeIfPresent(document, forKey: .document) - try container.encodeIfPresent(textMatch, forKey: .textMatch) - try container.encodeIfPresent(textMatchInfo, forKey: .textMatchInfo) try container.encodeIfPresent(geoDistanceMeters, forKey: .geoDistanceMeters) - try container.encodeIfPresent(vectorDistance, forKey: .vectorDistance) + try container.encodeIfPresent(highlight, forKey: .highlight) + try container.encodeIfPresent(highlights, forKey: .highlights) try container.encodeIfPresent(hybridSearchInfo, forKey: .hybridSearchInfo) try container.encodeIfPresent(searchIndex, forKey: .searchIndex) + try container.encodeIfPresent(textMatch, forKey: .textMatch) + try container.encodeIfPresent(textMatchInfo, forKey: .textMatchInfo) + try container.encodeIfPresent(vectorDistance, forKey: .vectorDistance) } } diff --git a/Sources/Typesense/Models/SearchSynonym.swift b/Sources/Typesense/Models/SearchSynonym.swift index 4cd1d3d..394a4a4 100644 --- a/Sources/Typesense/Models/SearchSynonym.swift +++ b/Sources/Typesense/Models/SearchSynonym.swift @@ -12,29 +12,29 @@ import AnyCodable public struct SearchSynonym: Codable { - /** For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. */ - public var root: String? - /** Array of words that should be considered as synonyms. */ - public var synonyms: [String] /** Locale for the synonym, leave blank to use the standard tokenizer. */ public var locale: String? + /** For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. */ + public var root: String? /** By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. */ public var symbolsToIndex: [String]? + /** Array of words that should be considered as synonyms. */ + public var synonyms: [String] public var id: String - public init(root: String? = nil, synonyms: [String], locale: String? = nil, symbolsToIndex: [String]? = nil, id: String) { - self.root = root - self.synonyms = synonyms + public init(locale: String? = nil, root: String? = nil, symbolsToIndex: [String]? = nil, synonyms: [String], id: String) { self.locale = locale + self.root = root self.symbolsToIndex = symbolsToIndex + self.synonyms = synonyms self.id = id } public enum CodingKeys: String, CodingKey, CaseIterable { - case root - case synonyms case locale + case root case symbolsToIndex = "symbols_to_index" + case synonyms case id } @@ -42,10 +42,10 @@ public struct SearchSynonym: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(root, forKey: .root) - try container.encode(synonyms, forKey: .synonyms) try container.encodeIfPresent(locale, forKey: .locale) + try container.encodeIfPresent(root, forKey: .root) try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) + try container.encode(synonyms, forKey: .synonyms) try container.encode(id, forKey: .id) } } diff --git a/Sources/Typesense/Models/SearchSynonymSchema.swift b/Sources/Typesense/Models/SearchSynonymSchema.swift index fdcbfb0..2db0379 100644 --- a/Sources/Typesense/Models/SearchSynonymSchema.swift +++ b/Sources/Typesense/Models/SearchSynonymSchema.swift @@ -12,37 +12,37 @@ import AnyCodable public struct SearchSynonymSchema: Codable { - /** For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. */ - public var root: String? - /** Array of words that should be considered as synonyms. */ - public var synonyms: [String] /** Locale for the synonym, leave blank to use the standard tokenizer. */ public var locale: String? + /** For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. */ + public var root: String? /** By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. */ public var symbolsToIndex: [String]? + /** Array of words that should be considered as synonyms. */ + public var synonyms: [String] - public init(root: String? = nil, synonyms: [String], locale: String? = nil, symbolsToIndex: [String]? = nil) { - self.root = root - self.synonyms = synonyms + public init(locale: String? = nil, root: String? = nil, symbolsToIndex: [String]? = nil, synonyms: [String]) { self.locale = locale + self.root = root self.symbolsToIndex = symbolsToIndex + self.synonyms = synonyms } public enum CodingKeys: String, CodingKey, CaseIterable { - case root - case synonyms case locale + case root case symbolsToIndex = "symbols_to_index" + case synonyms } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(root, forKey: .root) - try container.encode(synonyms, forKey: .synonyms) try container.encodeIfPresent(locale, forKey: .locale) + try container.encodeIfPresent(root, forKey: .root) try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) + try container.encode(synonyms, forKey: .synonyms) } } diff --git a/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift b/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift index 69bb4e8..1000478 100644 --- a/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift +++ b/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift @@ -12,27 +12,27 @@ import AnyCodable public struct StemmingDictionaryWordsInner: Codable { - /** The word form to be stemmed */ - public var word: String /** The root form of the word */ public var root: String + /** The word form to be stemmed */ + public var word: String - public init(word: String, root: String) { - self.word = word + public init(root: String, word: String) { self.root = root + self.word = word } public enum CodingKeys: String, CodingKey, CaseIterable { - case word case root + case word } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(word, forKey: .word) try container.encode(root, forKey: .root) + try container.encode(word, forKey: .word) } } diff --git a/Sources/Typesense/Models/StopwordsSetSchema.swift b/Sources/Typesense/Models/StopwordsSetSchema.swift index 2b45970..19fd21a 100644 --- a/Sources/Typesense/Models/StopwordsSetSchema.swift +++ b/Sources/Typesense/Models/StopwordsSetSchema.swift @@ -13,19 +13,19 @@ import AnyCodable public struct StopwordsSetSchema: Codable { public var id: String - public var stopwords: [String] public var locale: String? + public var stopwords: [String] - public init(id: String, stopwords: [String], locale: String? = nil) { + public init(id: String, locale: String? = nil, stopwords: [String]) { self.id = id - self.stopwords = stopwords self.locale = locale + self.stopwords = stopwords } public enum CodingKeys: String, CodingKey, CaseIterable { case id - case stopwords case locale + case stopwords } // Encodable protocol methods @@ -33,8 +33,8 @@ public struct StopwordsSetSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) - try container.encode(stopwords, forKey: .stopwords) try container.encodeIfPresent(locale, forKey: .locale) + try container.encode(stopwords, forKey: .stopwords) } } diff --git a/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift b/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift index 9112fd2..4c7c4e4 100644 --- a/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift +++ b/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift @@ -12,25 +12,25 @@ import AnyCodable public struct StopwordsSetUpsertSchema: Codable { - public var stopwords: [String] public var locale: String? + public var stopwords: [String] - public init(stopwords: [String], locale: String? = nil) { - self.stopwords = stopwords + public init(locale: String? = nil, stopwords: [String]) { self.locale = locale + self.stopwords = stopwords } public enum CodingKeys: String, CodingKey, CaseIterable { - case stopwords case locale + case stopwords } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(stopwords, forKey: .stopwords) try container.encodeIfPresent(locale, forKey: .locale) + try container.encode(stopwords, forKey: .stopwords) } } diff --git a/Sources/Typesense/Models/SynonymItemSchema.swift b/Sources/Typesense/Models/SynonymItemSchema.swift index 7c00f6c..8a50178 100644 --- a/Sources/Typesense/Models/SynonymItemSchema.swift +++ b/Sources/Typesense/Models/SynonymItemSchema.swift @@ -14,29 +14,29 @@ public struct SynonymItemSchema: Codable { /** Unique identifier for the synonym item */ public var id: String - /** Array of words that should be considered as synonyms */ - public var synonyms: [String] - /** For 1-way synonyms, indicates the root word that words in the synonyms parameter map to */ - public var root: String? /** Locale for the synonym, leave blank to use the standard tokenizer */ public var locale: String? + /** For 1-way synonyms, indicates the root word that words in the synonyms parameter map to */ + public var root: String? /** By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is */ public var symbolsToIndex: [String]? + /** Array of words that should be considered as synonyms */ + public var synonyms: [String] - public init(id: String, synonyms: [String], root: String? = nil, locale: String? = nil, symbolsToIndex: [String]? = nil) { + public init(id: String, locale: String? = nil, root: String? = nil, symbolsToIndex: [String]? = nil, synonyms: [String]) { self.id = id - self.synonyms = synonyms - self.root = root self.locale = locale + self.root = root self.symbolsToIndex = symbolsToIndex + self.synonyms = synonyms } public enum CodingKeys: String, CodingKey, CaseIterable { case id - case synonyms - case root case locale + case root case symbolsToIndex = "symbols_to_index" + case synonyms } // Encodable protocol methods @@ -44,10 +44,10 @@ public struct SynonymItemSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) - try container.encode(synonyms, forKey: .synonyms) - try container.encodeIfPresent(root, forKey: .root) try container.encodeIfPresent(locale, forKey: .locale) + try container.encodeIfPresent(root, forKey: .root) try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) + try container.encode(synonyms, forKey: .synonyms) } } diff --git a/Sources/Typesense/Models/UpdateDocumentsUpdateDocumentsParametersParameter.swift b/Sources/Typesense/Models/UpdateDocumentsParameters.swift similarity index 81% rename from Sources/Typesense/Models/UpdateDocumentsUpdateDocumentsParametersParameter.swift rename to Sources/Typesense/Models/UpdateDocumentsParameters.swift index 9e65bea..dd2d4a2 100644 --- a/Sources/Typesense/Models/UpdateDocumentsUpdateDocumentsParametersParameter.swift +++ b/Sources/Typesense/Models/UpdateDocumentsParameters.swift @@ -1,5 +1,5 @@ // -// UpdateDocumentsUpdateDocumentsParametersParameter.swift +// UpdateDocumentsParameters.swift // // Generated by openapi-generator // https://openapi-generator.tech @@ -10,7 +10,7 @@ import Foundation import AnyCodable #endif -public struct UpdateDocumentsUpdateDocumentsParametersParameter: Codable { +public struct UpdateDocumentsParameters: Codable { public var filterBy: String? diff --git a/Sources/Typesense/MultiSearch.swift b/Sources/Typesense/MultiSearch.swift index a502fec..ef95d1e 100644 --- a/Sources/Typesense/MultiSearch.swift +++ b/Sources/Typesense/MultiSearch.swift @@ -11,7 +11,7 @@ public struct MultiSearch { self.apiCall = apiCall } - public func perform(searchRequests: [MultiSearchCollectionParameters], commonParameters: MultiSearchParameters) async throws -> (Data?, URLResponse?) { + public func perform(searchRequests: [MultiSearchCollectionParameters], commonParameters: MultiSearchParameters, union: Bool = false) async throws -> (Data?, URLResponse?) { let queryParams = try createURLQuery(forSchema: commonParameters) let searchesData = try encoder.encode(MultiSearchSearchesParameter(searches: searchRequests)) diff --git a/Sources/Typesense/Operations.swift b/Sources/Typesense/Operations.swift index a11acb4..6973c09 100644 --- a/Sources/Typesense/Operations.swift +++ b/Sources/Typesense/Operations.swift @@ -31,10 +31,10 @@ public struct Operations { return (data, response) } - public func getDebug() async throws -> (DebugRetrieveSchema?, URLResponse?) { + public func getDebug() async throws -> (Debug200Response?, URLResponse?) { let (data, response) = try await apiCall.get(endPoint: "debug") if let result = data { - let decodedData = try decoder.decode(DebugRetrieveSchema.self, from: result) + let decodedData = try decoder.decode(Debug200Response.self, from: result) return (decodedData, response) } return (nil, response) diff --git a/Sources/Typesense/Override.swift b/Sources/Typesense/Override.swift index 9551615..6af1470 100644 --- a/Sources/Typesense/Override.swift +++ b/Sources/Typesense/Override.swift @@ -15,24 +15,24 @@ public struct Override { self.overrideId = overrideId } - public func retrieve(metadataType: T.Type) async throws -> (SearchOverride?, URLResponse?) { - let (data, response) = try await apiCall.get(endPoint: endpointPath()) - if let result = data { - let override = try decoder.decode(SearchOverride.self, from: result) - return (override, response) - } - - return (nil, response) - } - - public func delete() async throws -> (SearchOverrideDeleteResponse?, URLResponse?) { - let (data, response) = try await apiCall.delete(endPoint: endpointPath()) - if let result = data { - let decodedData = try decoder.decode(SearchOverrideDeleteResponse.self, from: result) - return (decodedData, response) - } - return (nil, response) - } + // public func retrieve(metadataType: T.Type) async throws -> (SearchOverride?, URLResponse?) { + // let (data, response) = try await apiCall.get(endPoint: endpointPath()) + // if let result = data { + // let override = try decoder.decode(SearchOverride.self, from: result) + // return (override, response) + // } + + // return (nil, response) + // } + + // public func delete() async throws -> (SearchOverrideDeleteResponse?, URLResponse?) { + // let (data, response) = try await apiCall.delete(endPoint: endpointPath()) + // if let result = data { + // let decodedData = try decoder.decode(SearchOverrideDeleteResponse.self, from: result) + // return (decodedData, response) + // } + // return (nil, response) + // } private func endpointPath() throws -> String { return try "\(Collections.RESOURCEPATH)/\(collectionName.encodeURL())/\(Overrides.RESOURCEPATH)/\(overrideId.encodeURL())" diff --git a/Sources/Typesense/Overrides.swift b/Sources/Typesense/Overrides.swift index 722064c..4e8ea75 100644 --- a/Sources/Typesense/Overrides.swift +++ b/Sources/Typesense/Overrides.swift @@ -14,26 +14,26 @@ public struct Overrides { self.collectionName = collectionName } - public func upsert(overrideId: String, params: SearchOverrideSchema) async throws -> (SearchOverride?, URLResponse?) { - let schemaData = try encoder.encode(params) - let (data, response) = try await self.apiCall.put(endPoint: endpointPath(overrideId), body: schemaData) - - if let result = data { - let override = try decoder.decode(SearchOverride.self, from: result) - return (override, response) - } - - return (nil, response) - } - - public func retrieve(metadataType: T.Type) async throws -> (SearchOverridesResponse?, URLResponse?) { - let (data, response) = try await self.apiCall.get(endPoint: endpointPath()) - if let result = data { - let overrides = try decoder.decode(SearchOverridesResponse.self, from: result) - return (overrides, response) - } - return (nil, nil) - } + // public func upsert(overrideId: String, params: SearchOverrideSchema) async throws -> (SearchOverride?, URLResponse?) { + // let schemaData = try encoder.encode(params) + // let (data, response) = try await self.apiCall.put(endPoint: endpointPath(overrideId), body: schemaData) + + // if let result = data { + // let override = try decoder.decode(SearchOverride.self, from: result) + // return (override, response) + // } + + // return (nil, response) + // } + + // public func retrieve(metadataType: T.Type) async throws -> (SearchOverridesResponse?, URLResponse?) { + // let (data, response) = try await self.apiCall.get(endPoint: endpointPath()) + // if let result = data { + // let overrides = try decoder.decode(SearchOverridesResponse.self, from: result) + // return (overrides, response) + // } + // return (nil, nil) + // } private func endpointPath(_ operation: String? = nil) throws -> String { let baseEndpoint = try "\(Collections.RESOURCEPATH)/\(collectionName.encodeURL())/\(Overrides.RESOURCEPATH)" diff --git a/Sources/Typesense/Shared/DocumentIndexParameters.swift b/Sources/Typesense/Shared/DocumentIndexParameters.swift new file mode 100644 index 0000000..7d71e89 --- /dev/null +++ b/Sources/Typesense/Shared/DocumentIndexParameters.swift @@ -0,0 +1,13 @@ +public struct DocumentIndexParameters: Codable { + + public var dirtyValues: DirtyValues? + + public init(dirtyValues: DirtyValues? = nil) { + self.dirtyValues = dirtyValues + } + + public enum CodingKeys: String, CodingKey { + case dirtyValues = "dirty_values" + } + +} \ No newline at end of file diff --git a/Sources/Typesense/Shared/Enums.swift b/Sources/Typesense/Shared/Enums.swift deleted file mode 100644 index 2fb16f1..0000000 --- a/Sources/Typesense/Shared/Enums.swift +++ /dev/null @@ -1,13 +0,0 @@ -public enum IndexAction: String, Codable { - case create = "create" - case update = "update" - case upsert = "upsert" - case emplace = "emplace" -} - -public enum DirtyValues: String, Codable { - case coerceOrReject = "coerce_or_reject" - case coerceOrDrop = "coerce_or_drop" - case drop = "drop" - case reject = "reject" -} \ No newline at end of file diff --git a/Sources/Typesense/Stopword.swift b/Sources/Typesense/Stopword.swift index e8ef103..926acf4 100644 --- a/Sources/Typesense/Stopword.swift +++ b/Sources/Typesense/Stopword.swift @@ -22,10 +22,10 @@ public struct Stopword { return (nil, response) } - public func delete() async throws -> (StopwordsSetDeleteSchema?, URLResponse?) { + public func delete() async throws -> (DeleteStopwordsSet200Response?, URLResponse?) { let (data, response) = try await apiCall.delete(endPoint: endpointPath()) if let result = data { - let decodedData = try decoder.decode(StopwordsSetDeleteSchema.self, from: result) + let decodedData = try decoder.decode(DeleteStopwordsSet200Response.self, from: result) return (decodedData, response) } return (nil, response) diff --git a/Sources/Typesense/utils/Extensions.swift b/Sources/Typesense/utils/Extensions.swift index 7366700..ebf6745 100644 --- a/Sources/Typesense/utils/Extensions.swift +++ b/Sources/Typesense/utils/Extensions.swift @@ -70,8 +70,6 @@ extension MultiSearchSearchesParameter { collectionParams.stopwords = params.stopwords collectionParams.facetReturnParent = params.facetReturnParent collectionParams.voiceQuery = params.voiceQuery - collectionParams.rerankHybridMatches = params.rerankHybridMatches - collectionParams.xTypesenseApiKey = params.xTypesenseApiKey return collectionParams } } diff --git a/Tasks/AddVendorAttributes.swift b/Tasks/AddVendorAttributes.swift new file mode 100644 index 0000000..4936798 --- /dev/null +++ b/Tasks/AddVendorAttributes.swift @@ -0,0 +1,41 @@ +func addVendorAttributes(_ doc: inout [String: Any]) throws { + print("Adding custom x-* vendor attributes...") + let attrs = VendorAttributes(doc: doc) + + // Generic Parameters + // Setting "x-swift-generic-parameter" + try attrs.schemaGenericParameter([ + ("SearchResult", "T"), + ("SearchGroupedHit", "T"), + ("SearchResultHit", "T"), + ("MultiSearchResult", "T"), + ("MultiSearchResultItem", "T"), + ]) + + // Field Type Overrides + try attrs.schemaFieldTypeOverrides( + schema: "SearchResult", + overrides: [ + ("hits", "[SearchResultHit]"), + ("grouped_hits", "[SearchGroupedHit]"), + ] + ) + + try attrs.schemaFieldTypeOverrides( + schema: "SearchGroupedHit", + overrides: [("hits", "[SearchResultHit]")] + ) + + try attrs.schemaFieldTypeOverrides( + schema: "SearchResultHit", + overrides: [("document", "T")] + ) + + try attrs.schemaFieldTypeOverrides( + schema: "MultiSearchResult", + overrides: [("results", "[MultiSearchResultItem]")] + ) + + // Save changes back to the inout parameter + doc = attrs.doc +} diff --git a/Tasks/PreprocessOpenAPI.swift b/Tasks/PreprocessOpenAPI.swift new file mode 100644 index 0000000..a627a7e --- /dev/null +++ b/Tasks/PreprocessOpenAPI.swift @@ -0,0 +1,168 @@ +import Foundation +import Yams + +struct PreprocessOpenAPI { + + // Typealias for our Generic JSON/YAML object + typealias Node = [String: Any] + + static func process(input: String, output: String) throws { + print("Reading OpenAPI spec from \(input)...") + let yamlString = try String(contentsOfFile: input, encoding: .utf8) + + // Load as a Generic Dictionary + guard var doc = try Yams.load(yaml: yamlString) as? Node else { + throw StringError("Failed to parse YAML as a dictionary") + } + + print("Preprocessing the spec...") + + // Add Vendor Attributes + try addVendorAttributes(&doc) + + // Unwrap Parameters + try unwrapParametersByPath(&doc, path: "/collections/{collectionName}/documents/import", method: "post", paramName: "importDocumentsParameters", newComponentName: "ImportDocumentsParameters") + + try unwrapParametersByPath(&doc, path: "/collections/{collectionName}/documents/export", method: "get", paramName: "exportDocumentsParameters", newComponentName: "ExportDocumentsParameters") + + try unwrapParametersByPath(&doc, path: "/collections/{collectionName}/documents", method: "patch", paramName: "updateDocumentsParameters", newComponentName: "UpdateDocumentsParameters") + + try unwrapParametersByPath(&doc, path: "/collections/{collectionName}/documents", method: "delete", paramName: "deleteDocumentsParameters", newComponentName: "DeleteDocumentsParameters") + + try unwrapParametersByPath(&doc, path: "/collections", method: "get", paramName: "getCollectionsParameters", newComponentName: "GetCollectionsParameters") + + try unwrapSearchParameters(&doc) + try unwrapMultiSearchParameters(&doc) + + + print("Writing processed spec to \(output)...") + let outputYaml = try Yams.dump(object: doc) + try outputYaml.write(toFile: output, atomically: true, encoding: .utf8) + print("Successfully created \(output).") + } + + // MARK: - Logic Implementation + + static func unwrapParametersByPath(_ doc: inout Node, path: String, method: String, paramName: String, newComponentName: String?) throws { + + // Navigate to Paths -> Path -> Method -> Parameters + guard var paths = doc["paths"] as? Node, + var pathItem = paths[path] as? Node, + var operation = pathItem[method] as? Node, + var parameters = operation["parameters"] as? [Node] else { + // Path might not exist, simply return or log warning + print("Warning: Could not find parameters for \(method) \(path)") + return + } + + // Find the parameter to unwrap + guard let index = parameters.firstIndex(where: { ($0["name"] as? String) == paramName }), + let paramObject = parameters[index] as Node? else { + throw StringError("Parameter '\(paramName)' not found in \(path)") + } + + // Extract Schema + guard let schema = paramObject["schema"] as? Node, + let properties = schema["properties"] as? Node else { + throw StringError("Could not extract properties from '\(paramName)'") + } + + // Copy to Components (Optional) + if let compName = newComponentName { + print("- Copying inline schema for '\(paramName)' to components.schemas.\(compName)...") + var components = doc["components"] as? Node ?? [:] + var schemas = components["schemas"] as? Node ?? [:] + schemas[compName] = schema + components["schemas"] = schemas + doc["components"] = components + } + + print("- Unwrapping parameter object '\(paramName)'...") + + // Remove the object parameter + parameters.remove(at: index) + + // Add flattened properties + for (key, value) in properties { + let newParam: Node = [ + "name": key, + "in": "query", + "schema": value + ] + parameters.append(newParam) + } + + // Save back up the tree + operation["parameters"] = parameters + pathItem[method] = operation + paths[path] = pathItem + doc["paths"] = paths + } + + static func unwrapSearchParameters(_ doc: inout Node) throws { + // Reusing the generic logic to modify the Search path + + guard let components = doc["components"] as? Node, + let schemas = components["schemas"] as? Node, + let searchParams = schemas["SearchParameters"] as? Node, + let properties = searchParams["properties"] as? Node else { + throw StringError("Could not find schema for SearchParameters") + } + + let path = "/collections/{collectionName}/documents/search" + let method = "get" + + try injectPropertiesAsParams(&doc, path: path, method: method, removeParam: "searchParameters", properties: properties) + } + + static func unwrapMultiSearchParameters(_ doc: inout Node) throws { + guard let components = doc["components"] as? Node, + let schemas = components["schemas"] as? Node, + let searchParams = schemas["MultiSearchParameters"] as? Node, + let properties = searchParams["properties"] as? Node else { + throw StringError("Could not find schema for MultiSearchParameters") + } + + let path = "/multi_search" + let method = "post" + + try injectPropertiesAsParams(&doc, path: path, method: method, removeParam: "multiSearchParameters", properties: properties) + } + + // Helper for the search/multi-search unwrap + static func injectPropertiesAsParams(_ doc: inout Node, path: String, method: String, removeParam: String, properties: Node) throws { + print("- Unwrapping \(removeParam)...") + + guard var paths = doc["paths"] as? Node, + var pathItem = paths[path] as? Node, + var operation = pathItem[method] as? Node, + var parameters = operation["parameters"] as? [Node] else { + return + } + + if let idx = parameters.firstIndex(where: { ($0["name"] as? String) == removeParam }) { + parameters.remove(at: idx) + } + + for (key, value) in properties { + let newParam: Node = [ + "name": key, + "in": "query", + "schema": value + ] + parameters.append(newParam) + } + + operation["parameters"] = parameters + pathItem[method] = operation + paths[path] = pathItem + doc["paths"] = paths + } + +} + +struct StringError: Error, CustomStringConvertible { + let message: String + var description: String { return message } + init(_ message: String) { self.message = message } +} \ No newline at end of file diff --git a/Tasks/VendorAttributes.swift b/Tasks/VendorAttributes.swift new file mode 100644 index 0000000..d5bc6ab --- /dev/null +++ b/Tasks/VendorAttributes.swift @@ -0,0 +1,71 @@ +import Foundation +import Yams + +/// Helper class to manipulate the nested Dictionary structure +class VendorAttributes { + var doc: [String: Any] + + // Quick accessors for Components -> Schemas + var schemas: [String: Any] { + get { + guard let components = doc["components"] as? [String: Any], + let schemas = components["schemas"] as? [String: Any] else { + return [:] + } + return schemas + } + set { + var components = doc["components"] as? [String: Any] ?? [:] + components["schemas"] = newValue + doc["components"] = components + } + } + + init(doc: [String: Any]) { + self.doc = doc + } + + /// Helper to modify a specific schema in place + private func modifySchema(_ name: String, closure: (inout [String: Any]) -> Void) throws { + var currentSchemas = self.schemas + + guard var schema = currentSchemas[name] as? [String: Any] else { + throw StringError( "Schema not found: \(name)") + } + + closure(&schema) + + currentSchemas[name] = schema + self.schemas = currentSchemas + } + + /// Adds x-swift-generic-parameter to the schema + func schemaGenericParameter(_ items: [(String, String)]) throws { + for (schemaName, generic) in items { + try modifySchema(schemaName) { schema in + schema["x-swift-generic-parameter"] = generic + } + } + } + + /// Overrides field types in a schema + func schemaFieldTypeOverrides(schema: String, overrides: [(String, String)]) throws { + try modifySchema(schema) { schemaDict in + var properties = schemaDict["properties"] as? [String: Any] ?? [:] + + for (field, swiftType) in overrides { + if var existingProp = properties[field] as? [String: Any] { + // Update existing + existingProp["x-swift-type"] = swiftType + properties[field] = existingProp + } else { + // Create new if missing (matches Rust 'None' branch) + let newProp: [String: Any] = ["x-swift-type": swiftType] + properties[field] = newProp + } + } + + schemaDict["properties"] = properties + } + } +} diff --git a/Tasks/main.swift b/Tasks/main.swift new file mode 100644 index 0000000..87d7e34 --- /dev/null +++ b/Tasks/main.swift @@ -0,0 +1,139 @@ +import Foundation +import ArgumentParser +import Yams + +let specUrl = "https://raw.githubusercontent.com/typesense/typesense-api-spec/master/openapi.yml" +let inputSpecFile = "openapi.yml" +let outputPreprocessedFile = "preprocessed_openapi.yml" +let customTemplatesDir = "openapi-generator-template" +let outputDir = "typesense_codegen" + +struct Tasks: ParsableCommand { + static var configuration = CommandConfiguration( + abstract: "A task runner for the typesense-swift project", + subcommands: [CodeGen.self, Fetch.self, Preprocess.self] + ) +} + +// MARK: - Tasks + +struct CodeGen: ParsableCommand { + static var configuration = CommandConfiguration(abstract: "Generates client code using Docker and moves Models to Sources.") + + func run() throws { + print("▶️ Running codegen task via Docker...") + + let fileManager = FileManager.default + let currentPath = fileManager.currentDirectoryPath + + let volumeMount = "\(currentPath):/local" + + let dockerArgs = [ + "run", "--rm", + "-v", volumeMount, + "openapitools/openapi-generator-cli", + "generate", + "-i", "/local/\(outputPreprocessedFile)", + "-g", "swift5", + "-o", "/local/output", + "--additional-properties", "useJsonEncodable=false", + "--additional-properties", "hashableModels=false", + "--additional-properties", "identifiableModels=false" + ] + + print(" - Executing Docker generate command...") + try Shell.run("docker", args: dockerArgs) + + // Define paths for file operations + // Path logic based on: cd output/OpenAPIClient/Classes/OpenAPIs + let generatedModelsPath = "output/OpenAPIClient/Classes/OpenAPIs/Models" + let tempModelsPath = "Models" + let outputDir = "output" + let finalDestination = "Sources/Typesense" + let finalModelsPath = "\(finalDestination)/Models" + + // rm -rf Models (Clean up any existing temp folder in root) + if fileManager.fileExists(atPath: tempModelsPath) { + print(" - Cleaning up temporary Models directory...") + try Shell.run("rm", args: ["-rf", tempModelsPath]) + } + + // mv ./output/.../Models ../../../../ (Move generated models to root) + print(" - Extracting Models from generated output...") + // We verify the generated path exists first to avoid confusing errors + if !fileManager.fileExists(atPath: generatedModelsPath) { + print("❌ Error: Generated models not found at \(generatedModelsPath). Docker generation might have failed.") + throw ExitCode.failure + } + try Shell.run("mv", args: [generatedModelsPath, "."]) + + // rm -rf output + print(" - Removing raw output directory...") + try Shell.run("rm", args: ["-rf", outputDir]) + + // rm -rf Sources/Typesense/Models + print(" - Removing old Models from \(finalDestination)...") + try Shell.run("rm", args: ["-rf", finalModelsPath]) + + // mv ./Models ./Sources/Typesense + print(" - Moving new Models to \(finalDestination)...") + + // Ensure destination folder exists, otherwise mv will fail or rename the folder to Typesense + var isDir: ObjCBool = false + if !fileManager.fileExists(atPath: finalDestination, isDirectory: &isDir) || !isDir.boolValue { + print("❌ Error: Destination directory '\(finalDestination)' does not exist.") + throw ExitCode.failure + } + + try Shell.run("mv", args: [tempModelsPath, finalDestination]) + + print("✅ Codegen and file movement finished successfully.") + } +} + +struct Fetch: ParsableCommand { + static var configuration = CommandConfiguration(abstract: "Fetches the latest OpenAPI spec.") + + func run() throws { + print("▶️ Running fetch task...") + print(" - Downloading spec from \(specUrl)") + + guard let url = URL(string: specUrl), + let data = try? Data(contentsOf: url) else { + print("❌ Failed to download spec.") + throw ExitCode.failure + } + + try data.write(to: URL(fileURLWithPath: inputSpecFile)) + print(" - Spec saved to \(inputSpecFile)") + print("✅ Fetch API spec task finished successfully.") + } +} + +struct Preprocess: ParsableCommand { + static var configuration = CommandConfiguration(abstract: "Preprocesses the OpenAPI spec.") + + func run() throws { + print("▶️ Preprocessing OpenAPI file...") + try PreprocessOpenAPI.process(input: inputSpecFile, output: outputPreprocessedFile) + print("✅ Preprocessing complete.") + } +} + +// MARK: - Helpers + +struct Shell { + static func run(_ command: String, args: [String]) throws { + let task = Process() + task.launchPath = "/usr/bin/env" + task.arguments = [command] + args + try task.run() + task.waitUntilExit() + + if task.terminationStatus != 0 { + throw ExitCode(task.terminationStatus) + } + } +} + +Tasks.main() diff --git a/Tests/TypesenseTests/AnalyticsTests.swift b/Tests/TypesenseTests/AnalyticsTests.swift index af31c4f..b2d035c 100644 --- a/Tests/TypesenseTests/AnalyticsTests.swift +++ b/Tests/TypesenseTests/AnalyticsTests.swift @@ -13,19 +13,66 @@ final class AnalyticsTests: XCTestCase { } func testAnalyticsRuleCreate() async { - let destination = AnalyticsRuleParametersDestination(collection: "product_queries") - let source = AnalyticsRuleParametersSource(collections: ["products"]) - let schema = AnalyticsRuleSchema(name: "product_queries_aggregation", type: .popularQueries, params: AnalyticsRuleParameters(source: source, destination: destination, limit: 1000)) + let schema = AnalyticsRuleCreate( + name: "test_rule", + type: .popularQueries, + collection: "products", + eventType: "search", + ruleTag: "homepage", + params: AnalyticsRuleCreateParams( + destinationCollection: "product_queries", + limit: 100, + ) + ) do { - let (rule, _) = try await client.analytics().rules().upsert(params: schema) + let (rule, _) = try await utilClient.analytics().rules().create(schema) XCTAssertNotNil(rule) guard let validRule = rule else { throw DataError.dataNotFound } print(validRule) XCTAssertEqual(validRule.name, schema.name) - XCTAssertEqual(validRule.params.limit, schema.params.limit) - XCTAssertEqual(validRule.params.destination.collection, schema.params.destination.collection) + XCTAssertEqual(validRule.params?.limit, schema.params?.limit) + XCTAssertEqual(validRule.params?.destinationCollection, schema.params?.destinationCollection) + } catch (let error) { + print(error.localizedDescription) + XCTAssertTrue(false) + } + } + + func testAnalyticsRuleCreateMany() async { + let schema1 = AnalyticsRuleCreate( + name: "test_rule_1", + type: .popularQueries, + collection: "products", + eventType: "search", + ruleTag: "homepage", + params: AnalyticsRuleCreateParams( + destinationCollection: "product_queries", + limit: 100, + ) + ) + let schema2 = AnalyticsRuleCreate( + name: "test_rule_2", + type: .popularQueries, + collection: "products", + eventType: "any", + ruleTag: "homepage", + params: AnalyticsRuleCreateParams( + destinationCollection: "product_queries", + limit: 100, + ) + ) + + do { + let (rules, _) = try await utilClient.analytics().rules().createMany([schema1, schema2]) + XCTAssertNotNil(rules) + guard let validRule = rules else { + throw DataError.dataNotFound + } + print(validRule) + XCTAssertEqual(validRule[0].name, schema1.name) + XCTAssertEqual(validRule[1].name, schema2.name) } catch (let error) { print(error.localizedDescription) XCTAssertTrue(false) @@ -34,12 +81,12 @@ final class AnalyticsTests: XCTestCase { func testAnalyticsRuleRetrieve() async { do { - let (rule, _) = try await client.analytics().rule(id: "product_queries_aggregation").retrieve() + let (rule, _) = try await client.analytics().rule("homepage_popular_queries").retrieve() guard let validRule = rule else { throw DataError.dataNotFound } print(validRule) - XCTAssertEqual(validRule.name, "product_queries_aggregation") + XCTAssertEqual(validRule.name, "homepage_popular_queries") } catch (let error) { print(error.localizedDescription) XCTAssertTrue(false) @@ -50,11 +97,11 @@ final class AnalyticsTests: XCTestCase { do { let (rules, _) = try await client.analytics().rules().retrieveAll() XCTAssertNotNil(rules) - guard let validRules = rules?.rules else { + guard let validRules = rules else { throw DataError.dataNotFound } print(validRules) - XCTAssertEqual(validRules[0].name, "product_queries_aggregation") + XCTAssertEqual(validRules[0].name, "homepage_popular_queries") } catch (let error) { print(error.localizedDescription) XCTAssertTrue(false) @@ -63,13 +110,13 @@ final class AnalyticsTests: XCTestCase { func testAnalyticsRuleDelete() async { do { - let (deletedRule, _) = try await client.analytics().rule(id: "product_queries_aggregation").delete() + let (deletedRule, _) = try await client.analytics().rule( "homepage_popular_queries").delete() XCTAssertNotNil(deletedRule) guard let validRule = deletedRule else { throw DataError.dataNotFound } print(validRule) - XCTAssertEqual(validRule.name, "product_queries_aggregation") + XCTAssertEqual(validRule.name, "homepage_popular_queries") } catch (let error) { print(error.localizedDescription) XCTAssertTrue(false) @@ -78,14 +125,13 @@ final class AnalyticsTests: XCTestCase { func testAnalyticsEventsCreate() async { do { - let (res, _) = try await client.analytics().events().create(params: AnalyticsEventCreateSchema( - type: "click", - name: "products_click_event", - data: [ - "q": "nike shoes", - "doc_id": "1024", - "user_id": "111112" - ] + let (res, _) = try await client.analytics().events().create( AnalyticsEvent( + name: "product_queries_aggregation", + eventType: "popular_queries", + data: AnalyticsEventData( + userId: "111112", + q: "nike shoes", + ) )) guard let validRes = res else { throw DataError.dataNotFound diff --git a/Tests/TypesenseTests/ApiKeyTests.swift b/Tests/TypesenseTests/ApiKeyTests.swift index ed0bf61..5a72553 100644 --- a/Tests/TypesenseTests/ApiKeyTests.swift +++ b/Tests/TypesenseTests/ApiKeyTests.swift @@ -8,14 +8,14 @@ final class ApiKeyTests: XCTestCase { func testKeyCreate() async { do { - let adminKey = ApiKeySchema(_description: "Test key with all privileges", actions: ["*"], collections: ["*"]) + let adminKey = ApiKeySchema(description: "Test key with all privileges", actions: ["*"], collections: ["*"]) let (data, _) = try await client.keys().create(adminKey) XCTAssertNotNil(data) guard let validData = data else { throw DataError.dataNotFound } print(validData) - XCTAssertEqual(validData._description, "Test key with all privileges") + XCTAssertEqual(validData.description, "Test key with all privileges") XCTAssertEqual(validData.actions, ["*"]) XCTAssertEqual(validData.collections, ["*"]) } catch (let error) { @@ -27,13 +27,13 @@ final class ApiKeyTests: XCTestCase { func testKeyRetrieve() async { do { let key = try await createAPIKey() - let (data, _) = try await client.keys().retrieve(id: key._id) + let (data, _) = try await client.keys().retrieve(id: key.id!) XCTAssertNotNil(data) guard let validData = data else { throw DataError.dataNotFound } print(validData) - XCTAssertEqual(validData._description, "Test key with all privileges") + XCTAssertEqual(validData.description, "Test key with all privileges") XCTAssertEqual(validData.actions, ["*"]) XCTAssertEqual(validData.collections, ["*"]) } catch (let error) { @@ -51,7 +51,7 @@ final class ApiKeyTests: XCTestCase { throw DataError.dataNotFound } print(validData) - XCTAssertEqual(validData[0]._id, key._id) + XCTAssertEqual(validData[0].id, key.id) } catch (let error) { print(error.localizedDescription) XCTAssertTrue(false) //To prevent this, check availability of Typesense Server and retry @@ -61,7 +61,7 @@ final class ApiKeyTests: XCTestCase { func testKeyDelete() async { do { let key = try await createAPIKey() - let (data, _) = try await client.keys().delete(id: key._id) + let (data, _) = try await client.keys().delete(id: key.id!) XCTAssertNotNil(data) guard let validData = data else { throw DataError.dataNotFound diff --git a/Tests/TypesenseTests/ConversationModelTests.swift b/Tests/TypesenseTests/ConversationModelTests.swift index 19c3308..13fd289 100644 --- a/Tests/TypesenseTests/ConversationModelTests.swift +++ b/Tests/TypesenseTests/ConversationModelTests.swift @@ -4,7 +4,7 @@ import XCTest final class ConversationModelTests: XCTestCase { func testConversationModelsCreate() async { let schema = ConversationModelCreateSchema( - _id: "conv-model-1", + id: "conv-model-1", modelName: "test/gpt-3.5-turbo", apiKey: "sk", historyCollection: "conversation_store", diff --git a/Tests/TypesenseTests/MultiSearchTests.swift b/Tests/TypesenseTests/MultiSearchTests.swift index 4ad92cd..9caa2c1 100644 --- a/Tests/TypesenseTests/MultiSearchTests.swift +++ b/Tests/TypesenseTests/MultiSearchTests.swift @@ -155,7 +155,7 @@ final class MultiSearchTests: XCTestCase { ]) let preset = PresetUpsertSchema( - value: .multiSearch(MultiSearchSearchesParameter( + value: .typeMultiSearchSearchesParameter(MultiSearchSearchesParameter( searches:[ MultiSearchCollectionParameters(q: "shoe", filterBy: "price:=[50..120]", collection: "products"), MultiSearchCollectionParameters(q: "Nike", collection: "brands"), diff --git a/Tests/TypesenseTests/OperationTests.swift b/Tests/TypesenseTests/OperationTests.swift index 202d45d..5258330 100644 --- a/Tests/TypesenseTests/OperationTests.swift +++ b/Tests/TypesenseTests/OperationTests.swift @@ -74,7 +74,7 @@ final class OperationTests: XCTestCase { throw DataError.dataNotFound } print(validData) - XCTAssertEqual(1, validData.state) + // XCTAssertEqual(1, validData.state) } catch HTTPError.serverError(let code, let desc) { print(desc) print("The response status code is \(code)") diff --git a/Tests/TypesenseTests/OverrideTests.swift b/Tests/TypesenseTests/OverrideTests.swift index d24dee9..f9d2906 100644 --- a/Tests/TypesenseTests/OverrideTests.swift +++ b/Tests/TypesenseTests/OverrideTests.swift @@ -2,50 +2,50 @@ import XCTest @testable import Typesense final class OverrideTests: XCTestCase { - override func setUp() async throws { - try await createCollection() - try await createAnOverride() - } + // override func setUp() async throws { + // try await createCollection() + // try await createAnOverride() + // } - override func tearDown() async throws { - try await tearDownCollections() - } + // override func tearDown() async throws { + // try await tearDownCollections() + // } - func testOverrideRetrieve() async { - do { - let (result, _) = try await client.collection(name: "companies").override("test-id").retrieve(metadataType: SearchOverrideExclude.self ) - guard let validOverride = result else { - throw DataError.dataNotFound - } - print(validOverride) - XCTAssertEqual("test-id", validOverride._id) - XCTAssertEqual("exclude-id", validOverride.metadata?._id) - } catch HTTPError.serverError(let code, let desc) { - print(desc) - print("The response status code is \(code)") - XCTAssertTrue(false) - } catch (let error) { - print(error) - XCTAssertTrue(false) - } - } + // func testOverrideRetrieve() async { + // do { + // let (result, _) = try await client.collection(name: "companies").override("test-id").retrieve(metadataType: SearchOverrideExclude.self ) + // guard let validOverride = result else { + // throw DataError.dataNotFound + // } + // print(validOverride) + // XCTAssertEqual("test-id", validOverride._id) + // XCTAssertEqual("exclude-id", validOverride.metadata?._id) + // } catch HTTPError.serverError(let code, let desc) { + // print(desc) + // print("The response status code is \(code)") + // XCTAssertTrue(false) + // } catch (let error) { + // print(error) + // XCTAssertTrue(false) + // } + // } - func testOverrideDelete() async { - do { - let (result, _) = try await client.collection(name: "companies").override("test-id").delete() - guard let validOverride = result else { - throw DataError.dataNotFound - } - print(validOverride) - XCTAssertEqual("test-id", validOverride._id) - } catch HTTPError.serverError(let code, let desc) { - print(desc) - print("The response status code is \(code)") - XCTAssertTrue(false) - } catch (let error) { - print(error) - XCTAssertTrue(false) - } - } + // func testOverrideDelete() async { + // do { + // let (result, _) = try await client.collection(name: "companies").override("test-id").delete() + // guard let validOverride = result else { + // throw DataError.dataNotFound + // } + // print(validOverride) + // XCTAssertEqual("test-id", validOverride._id) + // } catch HTTPError.serverError(let code, let desc) { + // print(desc) + // print("The response status code is \(code)") + // XCTAssertTrue(false) + // } catch (let error) { + // print(error) + // XCTAssertTrue(false) + // } + // } } diff --git a/Tests/TypesenseTests/OverridesTests.swift b/Tests/TypesenseTests/OverridesTests.swift index f73018a..2951978 100644 --- a/Tests/TypesenseTests/OverridesTests.swift +++ b/Tests/TypesenseTests/OverridesTests.swift @@ -2,73 +2,73 @@ import XCTest @testable import Typesense final class OverridesTests: XCTestCase { - override func setUp() async throws { - try await createCollection() - } + // override func setUp() async throws { + // try await createCollection() + // } - override func tearDown() async throws { - try await tearDownCollections() - } + // override func tearDown() async throws { + // try await tearDownCollections() + // } - func testOverridesUpsert() async { - let schema = SearchOverrideSchema( - rule: SearchOverrideRule(tags: ["test"], query: "test", match: SearchOverrideRule.Match.exact, filterBy: "employees:=50"), - includes: [SearchOverrideInclude(_id: "include-id", position: 1)], - excludes: [SearchOverrideExclude(_id: "exclude-id")], - filterBy: "test:=true", - removeMatchedTokens: false, - metadata: SearchOverrideExclude(_id: "test-json"), - sortBy: "asc", - replaceQuery: "test", - filterCuratedHits: false, - effectiveFromTs: 123, - effectiveToTs: 456, - stopProcessing: false - ) - do { - let (result, _) = try await client.collection(name: "companies").overrides().upsert(overrideId: "test-id", params: schema) - XCTAssertNotNil(result) - guard let validOverride = result else { - throw DataError.dataNotFound - } - print(validOverride) - XCTAssertEqual("test-id", validOverride._id) - XCTAssertEqual("test", validOverride.rule.query) - XCTAssertEqual("test-json", validOverride.metadata?._id) - XCTAssertEqual("include-id", validOverride.includes?[0]._id) - XCTAssertEqual("exclude-id", validOverride.excludes?[0]._id) - XCTAssertEqual("test:=true", validOverride.filterBy) - XCTAssertEqual(false, validOverride.removeMatchedTokens) - XCTAssertEqual("asc", validOverride.sortBy) - XCTAssertEqual("test", validOverride.replaceQuery) - XCTAssertEqual(false, validOverride.filterCuratedHits) - XCTAssertEqual(123, validOverride.effectiveFromTs) - XCTAssertEqual(456, validOverride.effectiveToTs) - XCTAssertEqual(false, validOverride.stopProcessing) - } catch (let error) { - print(error.localizedDescription) - XCTAssertTrue(false) - } - } + // func testOverridesUpsert() async { + // let schema = SearchOverrideSchema( + // rule: SearchOverrideRule(tags: ["test"], query: "test", match: SearchOverrideRule.Match.exact, filterBy: "employees:=50"), + // includes: [SearchOverrideInclude(_id: "include-id", position: 1)], + // excludes: [SearchOverrideExclude(_id: "exclude-id")], + // filterBy: "test:=true", + // removeMatchedTokens: false, + // metadata: SearchOverrideExclude(_id: "test-json"), + // sortBy: "asc", + // replaceQuery: "test", + // filterCuratedHits: false, + // effectiveFromTs: 123, + // effectiveToTs: 456, + // stopProcessing: false + // ) + // do { + // let (result, _) = try await client.collection(name: "companies").overrides().upsert(overrideId: "test-id", params: schema) + // XCTAssertNotNil(result) + // guard let validOverride = result else { + // throw DataError.dataNotFound + // } + // print(validOverride) + // XCTAssertEqual("test-id", validOverride._id) + // XCTAssertEqual("test", validOverride.rule.query) + // XCTAssertEqual("test-json", validOverride.metadata?._id) + // XCTAssertEqual("include-id", validOverride.includes?[0]._id) + // XCTAssertEqual("exclude-id", validOverride.excludes?[0]._id) + // XCTAssertEqual("test:=true", validOverride.filterBy) + // XCTAssertEqual(false, validOverride.removeMatchedTokens) + // XCTAssertEqual("asc", validOverride.sortBy) + // XCTAssertEqual("test", validOverride.replaceQuery) + // XCTAssertEqual(false, validOverride.filterCuratedHits) + // XCTAssertEqual(123, validOverride.effectiveFromTs) + // XCTAssertEqual(456, validOverride.effectiveToTs) + // XCTAssertEqual(false, validOverride.stopProcessing) + // } catch (let error) { + // print(error.localizedDescription) + // XCTAssertTrue(false) + // } + // } - func testOverridesRetrieve() async { - do { - try await createAnOverride() - let (overrides, _) = try await client.collection(name: "companies").overrides().retrieve(metadataType: SearchOverrideExclude.self ) - guard let validOverrides = overrides else { - throw DataError.dataNotFound - } - print(validOverrides) - XCTAssertEqual(1, validOverrides.overrides.count) - XCTAssertEqual("test-id", validOverrides.overrides[0]._id) - } catch HTTPError.serverError(let code, let desc) { - print(desc) - print("The response status code is \(code)") - XCTAssertTrue(false) - } catch (let error) { - print(error) - XCTAssertTrue(false) - } - } + // func testOverridesRetrieve() async { + // do { + // try await createAnOverride() + // let (overrides, _) = try await client.collection(name: "companies").overrides().retrieve(metadataType: SearchOverrideExclude.self ) + // guard let validOverrides = overrides else { + // throw DataError.dataNotFound + // } + // print(validOverrides) + // XCTAssertEqual(1, validOverrides.overrides.count) + // XCTAssertEqual("test-id", validOverrides.overrides[0]._id) + // } catch HTTPError.serverError(let code, let desc) { + // print(desc) + // print("The response status code is \(code)") + // XCTAssertTrue(false) + // } catch (let error) { + // print(error) + // XCTAssertTrue(false) + // } + // } } diff --git a/Tests/TypesenseTests/PresetTests.swift b/Tests/TypesenseTests/PresetTests.swift index e1bfdea..6648ed4 100644 --- a/Tests/TypesenseTests/PresetTests.swift +++ b/Tests/TypesenseTests/PresetTests.swift @@ -19,7 +19,7 @@ final class PresetTests: XCTestCase { print(validResult) XCTAssertEqual("test-id", validResult.name) switch validResult.value { - case .singleCollectionSearch(let value): + case .typeSearchParameters(let value): XCTAssertEqual("apple", value.q) default: XCTAssertTrue(false) diff --git a/Tests/TypesenseTests/PresetsTests.swift b/Tests/TypesenseTests/PresetsTests.swift index 42445b6..cdcd26a 100644 --- a/Tests/TypesenseTests/PresetsTests.swift +++ b/Tests/TypesenseTests/PresetsTests.swift @@ -8,7 +8,7 @@ final class PresetsTests: XCTestCase { func testPresetsUpsertSearchParameters() async { let schema = PresetUpsertSchema( - value: PresetValue.singleCollectionSearch(SearchParameters(q: "apple")) + value: PresetUpsertSchemaValue.typeSearchParameters(SearchParameters(q: "apple")) ) do { let (result, _) = try await client.presets().upsert(presetName: "test-id", params: schema) @@ -19,7 +19,7 @@ final class PresetsTests: XCTestCase { print(validResult) XCTAssertEqual("test-id", validResult.name) switch validResult.value { - case .singleCollectionSearch(let value): + case .typeSearchParameters(let value): XCTAssertEqual("apple", value.q) default: XCTAssertTrue(false) @@ -32,7 +32,7 @@ final class PresetsTests: XCTestCase { func testPresetsUpsertMultiSearchSearchesParameter() async { let schema = PresetUpsertSchema( - value: PresetValue.multiSearch(MultiSearchSearchesParameter(searches: [MultiSearchCollectionParameters(q: "apple")])) + value: PresetUpsertSchemaValue.typeMultiSearchSearchesParameter(MultiSearchSearchesParameter(searches: [MultiSearchCollectionParameters(q: "apple")])) ) do { let (result, _) = try await client.presets().upsert(presetName: "test-id", params: schema) @@ -43,7 +43,7 @@ final class PresetsTests: XCTestCase { print(validResult) XCTAssertEqual("test-id", validResult.name) switch validResult.value { - case .multiSearch(let value): + case .typeMultiSearchSearchesParameter(let value): XCTAssertEqual("apple", value.searches[0].q) default: XCTAssertTrue(false) @@ -66,10 +66,10 @@ final class PresetsTests: XCTestCase { XCTAssertEqual(2, validResult.presets.count) for preset in validResult.presets{ switch preset.value { - case .singleCollectionSearch(let value): + case .typeSearchParameters(let value): XCTAssertEqual("test-id", preset.name) XCTAssertEqual("apple", value.q) - case .multiSearch(let value): + case .typeMultiSearchSearchesParameter(let value): XCTAssertEqual("test-id-preset-multi-search", preset.name) XCTAssertEqual("banana", value.searches[0].q) } diff --git a/Tests/TypesenseTests/StopwordTests.swift b/Tests/TypesenseTests/StopwordTests.swift index a1540b8..35af54f 100644 --- a/Tests/TypesenseTests/StopwordTests.swift +++ b/Tests/TypesenseTests/StopwordTests.swift @@ -15,7 +15,7 @@ final class StopwordTests: XCTestCase { throw DataError.dataNotFound } print(validResult) - XCTAssertEqual("test-id-stopword-set", validResult._id) + XCTAssertEqual("test-id-stopword-set", validResult.id) XCTAssertEqual(["states","united"], validResult.stopwords) XCTAssertEqual("en", validResult.locale) } catch (let error) { @@ -32,7 +32,7 @@ final class StopwordTests: XCTestCase { throw DataError.dataNotFound } print(validResult) - XCTAssertEqual("test-id-stopword-set", validResult._id) + XCTAssertEqual("test-id-stopword-set", validResult.id) } catch (let error) { print(error) XCTAssertTrue(false) diff --git a/Tests/TypesenseTests/StopwordsTests.swift b/Tests/TypesenseTests/StopwordsTests.swift index 47a881d..22349bb 100644 --- a/Tests/TypesenseTests/StopwordsTests.swift +++ b/Tests/TypesenseTests/StopwordsTests.swift @@ -18,7 +18,7 @@ final class StopwordsTests: XCTestCase { throw DataError.dataNotFound } print(validResult) - XCTAssertEqual("test-id", validResult._id) + XCTAssertEqual("test-id", validResult.id) XCTAssertEqual(["states","united"], validResult.stopwords) XCTAssertEqual("en", validResult.locale) } catch (let error) { @@ -36,7 +36,7 @@ final class StopwordsTests: XCTestCase { } print(validResult) XCTAssertEqual(1, validResult.count) - XCTAssertEqual("test-id-stopword-set", validResult[0]._id) + XCTAssertEqual("test-id-stopword-set", validResult[0].id) } catch (let error) { print(error) XCTAssertTrue(false) diff --git a/Tests/TypesenseTests/SynonymTests.swift b/Tests/TypesenseTests/SynonymTests.swift index 32e8ce5..88351be 100644 --- a/Tests/TypesenseTests/SynonymTests.swift +++ b/Tests/TypesenseTests/SynonymTests.swift @@ -20,7 +20,7 @@ final class SynonymTests: XCTestCase { print(validData) XCTAssertNil(validData.root) XCTAssertEqual(validData.synonyms, ["blazer", "coat", "jacket"]) - XCTAssertEqual(validData._id, "coat-synonyms") + XCTAssertEqual(validData.id, "coat-synonyms") } catch HTTPError.serverError(let code, let desc) { print(desc) print("The response status code is \(code)") @@ -49,7 +49,7 @@ final class SynonymTests: XCTestCase { print(validData) XCTAssertEqual(validData.root, "smart phone") XCTAssertEqual(validData.synonyms, ["iphone", "android"]) - XCTAssertEqual(validData._id, "smart-phone-synonyms") + XCTAssertEqual(validData.id, "smart-phone-synonyms") } catch HTTPError.serverError(let code, let desc) { print(desc) print("The response status code is \(code)") @@ -78,7 +78,7 @@ final class SynonymTests: XCTestCase { print(validData) XCTAssertEqual(validData.root, "") XCTAssertEqual(validData.synonyms, ["blazer", "coat", "jacket"]) - XCTAssertEqual(validData._id, "coat-synonyms") + XCTAssertEqual(validData.id, "coat-synonyms") } catch HTTPError.serverError(let code, let desc) { print(desc) print("The response status code is \(code)") @@ -106,7 +106,7 @@ final class SynonymTests: XCTestCase { } print(validData) XCTAssertEqual(validData.synonyms.count, 1) - XCTAssertEqual(validData.synonyms[0]._id, "coat-synonyms") + XCTAssertEqual(validData.synonyms[0].id, "coat-synonyms") XCTAssertEqual(validData.synonyms[0].synonyms, ["blazer", "coat", "jacket"]) } catch HTTPError.serverError(let code, let desc) { print(desc) diff --git a/Tests/TypesenseTests/TestUtils.swift b/Tests/TypesenseTests/TestUtils.swift index 96c5e40..f0676ff 100644 --- a/Tests/TypesenseTests/TestUtils.swift +++ b/Tests/TypesenseTests/TestUtils.swift @@ -30,17 +30,17 @@ func tearDownStopwords() async throws { throw DataError.dataNotFound } for item in validData { - let _ = try await utilClient.stopword(item._id).delete() + let _ = try await utilClient.stopword(item.id).delete() } } func tearDownAnalyticsRules() async throws { let (data, _) = try await utilClient.analytics().rules().retrieveAll() - guard let validData = data?.rules else { + guard let validData = data else { throw DataError.dataNotFound } for item in validData { - let _ = try await utilClient.analytics().rule(id: item.name).delete() + let _ = try await utilClient.analytics().rule( item.name).delete() } } @@ -50,7 +50,7 @@ func tearDownAPIKeys() async throws { throw DataError.dataNotFound } for item in validData { - let _ = try await utilClient.keys().delete(id: item._id) + let _ = try await utilClient.keys().delete(id: item.id!) } } @@ -79,18 +79,18 @@ func createDocument() async throws { let _ = try await utilClient.collection(name: "companies").documents().create(document: data) } -func createAnOverride() async throws { - let _ = try await utilClient.collection(name: "companies").overrides().upsert( - overrideId: "test-id", - params: SearchOverrideSchema(rule: SearchOverrideRule(filterBy: "test"), filterBy: "test:=true", metadata: SearchOverrideExclude(_id: "exclude-id")) - ) -} +// func createAnOverride() async throws { +// let _ = try await utilClient.collection(name: "companies").overrides().upsert( +// overrideId: "test-id", +// params: SearchOverrideSchema(rule: SearchOverrideRule(filterBy: "test"), filterBy: "test:=true", metadata: SearchOverrideExclude(_id: "exclude-id")) +// ) +// } func createSingleCollectionSearchPreset() async throws { let _ = try await utilClient.presets().upsert( presetName: "test-id", params: PresetUpsertSchema( - value: .singleCollectionSearch(SearchParameters(q: "apple")) + value: PresetUpsertSchemaValue.typeSearchParameters(SearchParameters(q: "apple")) ) ) } @@ -99,7 +99,7 @@ func createMultiSearchPreset() async throws { let _ = try await utilClient.presets().upsert( presetName: "test-id-preset-multi-search", params: PresetUpsertSchema( - value: .multiSearch(MultiSearchSearchesParameter(searches: [MultiSearchCollectionParameters(q: "banana")])) + value: PresetUpsertSchemaValue.typeMultiSearchSearchesParameter(MultiSearchSearchesParameter(searches: [MultiSearchCollectionParameters(q: "banana")])) ) ) } @@ -115,20 +115,22 @@ func createStopwordSet() async throws { } func createAnalyticRule() async throws { - let _ = try await utilClient.analytics().rules().upsert(params: AnalyticsRuleSchema( - name: "product_queries_aggregation", - type: .counter, - params: AnalyticsRuleParameters( - source: AnalyticsRuleParametersSource(collections: ["products"], events: [AnalyticsRuleParametersSourceEvents(type: "click", weight: 1, name: "products_click_event")]), - destination: AnalyticsRuleParametersDestination(collection: "companies", counterField: "num_employees"), - limit: 1000 - ) + let _ = try await utilClient.analytics().rules().create(AnalyticsRuleCreate( + name: "homepage_popular_queries", + type: .popularQueries, + collection: "products", + eventType: "search", + ruleTag: "homepage", + params: AnalyticsRuleCreateParams( + destinationCollection: "product_queries", + limit: 100, + captureSearchRequests: true ) - ) + )) } func createAPIKey() async throws -> ApiKey { - let (data, _) = try await utilClient.keys().create( ApiKeySchema(_description: "Test key with all privileges", actions: ["*"], collections: ["*"])) + let (data, _) = try await utilClient.keys().create( ApiKeySchema(description: "Test key with all privileges", actions: ["*"], collections: ["*"])) return data! } @@ -169,4 +171,4 @@ struct Company: Codable { var num_employees: Int var country: String var metadata: [String: Bool]? -} \ No newline at end of file +} diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml new file mode 100644 index 0000000..b60c68c --- /dev/null +++ b/preprocessed_openapi.yml @@ -0,0 +1,5857 @@ +components: + schemas: + APIStatsResponse: + properties: + delete_latency_ms: + format: double + type: number + delete_requests_per_second: + format: double + type: number + import_latency_ms: + format: double + type: number + import_requests_per_second: + format: double + type: number + latency_ms: + type: object + x-go-type: map[string]float64 + overloaded_requests_per_second: + format: double + type: number + pending_write_batches: + format: double + type: number + requests_per_second: + type: object + x-go-type: map[string]float64 + search_latency_ms: + format: double + type: number + search_requests_per_second: + format: double + type: number + total_requests_per_second: + format: double + type: number + write_latency_ms: + format: double + type: number + write_requests_per_second: + format: double + type: number + type: object + AnalyticsEvent: + properties: + data: + description: Event payload + properties: + analytics_tag: + type: string + doc_id: + type: string + doc_ids: + items: + type: string + type: array + q: + type: string + user_id: + type: string + type: object + event_type: + description: Type of event (e.g., click, conversion, query, visit) + type: string + name: + description: Name of the analytics rule this event corresponds to + type: string + required: + - name + - event_type + - data + type: object + AnalyticsEventCreateResponse: + properties: + ok: + type: boolean + required: + - ok + type: object + AnalyticsEventsResponse: + properties: + events: + items: + properties: + collection: + type: string + doc_id: + type: string + doc_ids: + items: + type: string + type: array + event_type: + type: string + name: + type: string + query: + type: string + timestamp: + format: int64 + type: integer + user_id: + type: string + type: object + type: array + required: + - events + type: object + AnalyticsRule: + allOf: + - $ref: '#/components/schemas/AnalyticsRuleCreate' + - type: object + AnalyticsRuleCreate: + properties: + collection: + type: string + event_type: + type: string + name: + type: string + params: + properties: + capture_search_requests: + type: boolean + counter_field: + type: string + destination_collection: + type: string + expand_query: + type: boolean + limit: + type: integer + meta_fields: + items: + type: string + type: array + weight: + type: integer + type: object + rule_tag: + type: string + type: + enum: + - popular_queries + - nohits_queries + - counter + - log + type: string + required: + - name + - type + - collection + - event_type + type: object + AnalyticsRuleUpdate: + description: Fields allowed to update on an analytics rule + properties: + name: + type: string + params: + properties: + capture_search_requests: + type: boolean + counter_field: + type: string + destination_collection: + type: string + expand_query: + type: boolean + limit: + type: integer + meta_fields: + items: + type: string + type: array + weight: + type: integer + type: object + rule_tag: + type: string + type: object + AnalyticsStatus: + properties: + doc_counter_events: + type: integer + doc_log_events: + type: integer + log_prefix_queries: + type: integer + nohits_prefix_queries: + type: integer + popular_prefix_queries: + type: integer + query_counter_events: + type: integer + query_log_events: + type: integer + type: object + ApiKey: + allOf: + - $ref: '#/components/schemas/ApiKeySchema' + - properties: + id: + format: int64 + readOnly: true + type: integer + value_prefix: + readOnly: true + type: string + type: object + ApiKeyDeleteResponse: + properties: + id: + description: The id of the API key that was deleted + format: int64 + type: integer + required: + - id + type: object + ApiKeySchema: + properties: + actions: + items: + type: string + type: array + collections: + items: + type: string + type: array + description: + type: string + expires_at: + format: int64 + type: integer + value: + type: string + required: + - actions + - collections + - description + type: object + ApiKeysResponse: + properties: + keys: + items: + $ref: '#/components/schemas/ApiKey' + type: array + x-go-type: '[]*ApiKey' + required: + - keys + type: object + ApiResponse: + properties: + message: + type: string + required: + - message + type: object + CollectionAlias: + properties: + collection_name: + description: Name of the collection the alias mapped to + type: string + name: + description: Name of the collection alias + readOnly: true + type: string + required: + - collection_name + - name + type: object + CollectionAliasSchema: + properties: + collection_name: + description: Name of the collection you wish to map the alias to + type: string + required: + - collection_name + type: object + CollectionAliasesResponse: + properties: + aliases: + items: + $ref: '#/components/schemas/CollectionAlias' + type: array + x-go-type: '[]*CollectionAlias' + required: + - aliases + type: object + CollectionResponse: + allOf: + - $ref: '#/components/schemas/CollectionSchema' + - properties: + created_at: + description: Timestamp of when the collection was created (Unix epoch + in seconds) + format: int64 + readOnly: true + type: integer + num_documents: + description: Number of documents in the collection + format: int64 + readOnly: true + type: integer + required: + - num_documents + - created_at + type: object + CollectionSchema: + properties: + default_sorting_field: + default: '' + 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 + type: string + enable_nested_fields: + default: false + 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. + example: true + type: boolean + fields: + description: A list of fields for querying, filtering and faceting + example: + - facet: false + name: num_employees + type: int32 + - facet: false + name: company_name + type: string + - facet: true + name: country + type: string + items: + $ref: '#/components/schemas/Field' + type: array + metadata: + description: 'Optional details about the collection, e.g., when it was created, + who created it etc. + + ' + type: object + name: + description: Name of the collection + example: companies + type: string + symbols_to_index: + default: [] + description: 'List of symbols or special characters to be indexed. + + ' + items: + maxLength: 1 + minLength: 1 + type: string + type: array + synonym_sets: + description: List of synonym set names to associate with this collection + items: + example: synonym_set_1 + type: string + type: array + token_separators: + default: [] + 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: + maxLength: 1 + minLength: 1 + type: string + type: array + voice_query_model: + $ref: '#/components/schemas/VoiceQueryModelCollectionConfig' + required: + - name + - fields + type: object + x-swift-builder: true + CollectionUpdateSchema: + properties: + fields: + description: A list of fields for querying, filtering and faceting + example: + - facet: false + name: company_name + type: string + - facet: false + name: num_employees + type: int32 + - facet: true + name: country + type: string + items: + $ref: '#/components/schemas/Field' + type: array + metadata: + description: 'Optional details about the collection, e.g., when it was created, + who created it etc. + + ' + type: object + synonym_sets: + description: List of synonym set names to associate with this collection + items: + example: synonym_set_1 + type: string + type: array + required: + - fields + type: object + ConversationModelCreateSchema: + allOf: + - $ref: '#/components/schemas/ConversationModelUpdateSchema' + - properties: + history_collection: + description: Typesense collection that stores the historical conversations + 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 + model_name: + description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM + type: string + required: + - model_name + - max_bytes + - history_collection + type: object + required: + - model_name + - max_bytes + ConversationModelSchema: + allOf: + - $ref: '#/components/schemas/ConversationModelCreateSchema' + - properties: + id: + description: An explicit id for the model, otherwise the API will return + a response with an auto-generated conversation model id. + type: string + required: + - id + type: object + ConversationModelUpdateSchema: + properties: + account_id: + description: LLM service's account ID (only applicable for Cloudflare) + type: string + api_key: + description: The LLM service's API Key + type: string + history_collection: + description: Typesense collection that stores the historical conversations + type: string + id: + description: An explicit id for the model, otherwise the API will return + a response with an auto-generated conversation model id. + 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 + model_name: + description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM + type: string + system_prompt: + description: The system prompt that contains special instructions to the + LLM + type: string + ttl: + description: 'Time interval in seconds after which the messages would be + deleted. Default: 86400 (24 hours) + + ' + type: integer + vllm_url: + description: URL of vLLM service + type: string + type: object + CurationExclude: + properties: + id: + description: document id that should be excluded from the search results. + type: string + required: + - id + type: object + CurationInclude: + properties: + id: + description: document id that should be included + type: string + position: + description: position number where document should be included in the search + results + type: integer + required: + - id + - position + type: object + CurationItemCreateSchema: + properties: + effective_from_ts: + description: 'A Unix timestamp that indicates the date/time from which the + curation will be active. You can use this to create rules that start applying + from a future point in time. + + ' + type: integer + effective_to_ts: + description: 'A Unix timestamp that indicates the date/time until which + the curation will be active. You can use this to create rules that stop + applying after a period of time. + + ' + type: integer + excludes: + description: List of document `id`s that should be excluded from the search + results. + items: + $ref: '#/components/schemas/CurationExclude' + type: array + filter_by: + description: 'A filter by clause that is applied to any search query that + matches the curation rule. + + ' + type: string + filter_curated_hits: + description: 'When set to true, the filter conditions of the query is applied + to the curated records as well. Default: false. + + ' + type: boolean + id: + description: ID of the curation item + type: string + includes: + description: List of document `id`s that should be included in the search + results with their corresponding `position`s. + items: + $ref: '#/components/schemas/CurationInclude' + type: array + metadata: + 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. + + ' + type: object + remove_matched_tokens: + description: 'Indicates whether search query tokens that exist in the curation''s + rule should be removed from the search query. + + ' + type: boolean + replace_query: + description: 'Replaces the current search query with this value, when the + search query matches the curation rule. + + ' + type: string + rule: + $ref: '#/components/schemas/CurationRule' + sort_by: + description: 'A sort by clause that is applied to any search query that + matches the curation rule. + + ' + type: string + stop_processing: + description: 'When set to true, curation processing will stop at the first + matching rule. When set to false curation processing will continue and + multiple curation actions will be triggered in sequence. Curations are + processed in the lexical sort order of their id field. + + ' + type: boolean + required: + - rule + type: object + CurationItemDeleteSchema: + properties: + id: + description: ID of the deleted curation item + type: string + required: + - id + type: object + CurationItemSchema: + allOf: + - $ref: '#/components/schemas/CurationItemCreateSchema' + - properties: + id: + type: string + required: + - id + type: object + CurationRule: + properties: + filter_by: + description: 'Indicates that the curation should apply when the filter_by + parameter in a search query exactly matches the string specified here + (including backticks, spaces, brackets, etc). + + ' + type: string + match: + 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 + type: string + query: + description: Indicates what search queries should be curated + type: string + tags: + description: List of tag values to associate with this curation rule. + items: + type: string + type: array + type: object + CurationSetCreateSchema: + properties: + description: + description: Optional description for the curation set + type: string + items: + description: Array of curation items + items: + $ref: '#/components/schemas/CurationItemCreateSchema' + type: array + required: + - items + type: object + CurationSetDeleteSchema: + properties: + name: + description: Name of the deleted curation set + type: string + required: + - name + type: object + CurationSetRetrieveSchema: + $ref: '#/components/schemas/CurationSetCreateSchema' + CurationSetSchema: + allOf: + - $ref: '#/components/schemas/CurationSetCreateSchema' + - properties: + name: + type: string + required: + - name + type: object + DeleteDocumentsParameters: + properties: + 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 + filter_by: + example: 'num_employees:>100 && country: [USA, UK]' + type: string + ignore_not_found: + type: boolean + truncate: + description: When true, removes all documents from the collection while + preserving the collection and its schema. + type: boolean + required: + - filter_by + type: object + DirtyValues: + enum: + - coerce_or_reject + - coerce_or_drop + - drop + - reject + type: string + DropTokensMode: + 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 up to 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 + + ' + enum: + - right_to_left + - left_to_right + - both_sides:3 + type: string + ExportDocumentsParameters: + properties: + exclude_fields: + description: List of fields from the document to exclude in the search result + type: string + 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 + type: object + FacetCounts: + properties: + counts: + items: + properties: + count: + type: integer + highlighted: + type: string + parent: + type: object + value: + type: string + type: object + type: array + field_name: + type: string + stats: + properties: + avg: + format: double + type: number + max: + format: double + type: number + min: + format: double + type: number + sum: + format: double + type: number + total_values: + type: integer + type: object + type: object + Field: + properties: + drop: + example: true + type: boolean + embed: + properties: + from: + items: + type: string + type: array + model_config: + properties: + access_token: + type: string + api_key: + type: string + client_id: + type: string + client_secret: + type: string + indexing_prefix: + type: string + model_name: + type: string + project_id: + type: string + query_prefix: + type: string + refresh_token: + type: string + url: + type: string + required: + - model_name + type: object + required: + - from + - model_config + type: object + facet: + example: false + type: boolean + index: + default: true + example: true + type: boolean + infix: + default: false + example: true + type: boolean + locale: + example: el + type: string + name: + example: company_name + type: string + num_dim: + example: 256 + type: integer + optional: + example: true + type: boolean + range_index: + description: 'Enables an index optimized for range filtering on numerical + fields (e.g. rating:>3.5). Default: false. + + ' + type: boolean + reference: + description: 'Name of a field in another collection that should be linked + to this collection so that it can be joined during query. + + ' + type: string + sort: + example: true + type: boolean + stem: + description: 'Values are stemmed before indexing in-memory. Default: false. + + ' + type: boolean + stem_dictionary: + description: Name of the stemming dictionary to use for this field + example: irregular-plurals + type: string + store: + description: 'When set to false, the field value will not be stored on disk. + Default: true. + + ' + type: boolean + symbols_to_index: + default: [] + description: 'List of symbols or special characters to be indexed. + + ' + items: + maxLength: 1 + minLength: 1 + type: string + type: array + token_separators: + default: [] + 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: + maxLength: 1 + minLength: 1 + type: string + type: array + type: + example: string + type: string + vec_dist: + description: 'The distance metric to be used for vector search. Default: + `cosine`. You can also use `ip` for inner product. + + ' + type: string + required: + - name + - type + type: object + x-swift-builder: true + GetCollectionsParameters: + properties: + exclude_fields: + description: Comma-separated list of fields from the collection to exclude + from the response + type: string + limit: + description: 'Number of collections to fetch. Default: returns all collections. + + ' + type: integer + offset: + description: Identifies the starting point to return collections when paginating. + type: integer + type: object + HealthStatus: + properties: + ok: + type: boolean + required: + - ok + type: object + ImportDocumentsParameters: + properties: + action: + $ref: '#/components/schemas/IndexAction' + batch_size: + type: integer + dirty_values: + $ref: '#/components/schemas/DirtyValues' + remote_embedding_batch_size: + type: integer + return_doc: + type: boolean + return_id: + 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. + type: boolean + type: object + IndexAction: + enum: + - create + - update + - upsert + - emplace + type: string + MultiSearchCollectionParameters: + allOf: + - $ref: '#/components/schemas/MultiSearchParameters' + - properties: + collection: + description: 'The collection to search in. + + ' + type: string + rerank_hybrid_matches: + default: false + 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. + + ' + type: boolean + x-typesense-api-key: + description: A separate search API key for each search within a multi_search + request + type: string + type: object + x-swift-builder: true + MultiSearchParameters: + description: 'Parameters for the multi search API. + + ' + properties: + 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 + conversation: + description: 'Enable conversational search. + + ' + type: boolean + 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 + conversation_model_id: + description: 'The Id of Conversation Model to be used. + + ' + type: string + drop_tokens_mode: + $ref: '#/components/schemas/DropTokensMode' + 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 + enable_analytics: + default: true + description: 'Flag for enabling/disabling analytics aggregation for specific + search queries (for e.g. those originating from a test script). + + ' + type: boolean + enable_overrides: + default: false + 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 + enable_synonyms: + 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 + + ' + type: boolean + enable_typos_for_alpha_numerical_tokens: + description: 'Set this parameter to false to disable typos on alphanumerical + query tokens. Default: true. + + ' + type: boolean + enable_typos_for_numerical_tokens: + default: true + description: 'Make Typesense disable typos for numerical tokens. + + ' + type: boolean + exclude_fields: + description: List of fields from the document to exclude in the search result + type: string + 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 + facet_by: + description: A list of fields that will be used for faceting your results + on. Separate multiple fields with a comma. + type: string + 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 + facet_return_parent: + description: 'Comma separated string of nested facet fields whose parent + object should be returned in facet response. + + ' + type: string + facet_strategy: + description: 'Choose the underlying faceting strategy used. Comma separated + string of allows values: exhaustive, top_values or automatic (default). + + ' + type: string + filter_by: + description: Filter conditions for refining youropen api validator search + results. Separate multiple conditions with &&. + example: 'num_employees:>100 && country: [USA, UK]' + type: string + filter_curated_hits: + 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 + + ' + type: boolean + 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 + 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 + highlight_affix_num_tokens: + description: 'The number of tokens that should surround the highlighted + text on each side. Default: 4 + + ' + type: integer + highlight_end_tag: + description: 'The end tag used for the highlighted snippets. Default: `` + + ' + type: string + highlight_fields: + description: 'A list of custom fields that must be highlighted even if you + don''t query for them + + ' + type: string + highlight_full_fields: + description: List of fields which should be highlighted fully without snippeting + type: string + highlight_start_tag: + description: 'The start tag used for the highlighted snippets. Default: + `` + + ' + type: string + include_fields: + description: List of fields from the document to include in the search result + 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 + limit: + description: 'Number of hits to fetch. Can be used as an alternative to + the per_page parameter. Default: 10. + + ' + type: integer + 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 + max_facet_values: + description: Maximum number of facet values to be returned. + 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 + num_typos: + description: 'The number of typographical errors (1 or 2) that would be + tolerated. Default: 2 + + ' + type: string + 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 + override_tags: + description: Comma separated list of tags to trigger the curations rules + that match the tags. + 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 + 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 + pre_segmented_query: + default: false + 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 + 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 + preset: + description: 'Search using a bunch of search parameters by setting this + parameter to the name of the existing Preset. + + ' + type: string + prioritize_exact_match: + default: true + description: 'Set this parameter to true to ensure that an exact match is + ranked above the others + + ' + type: boolean + prioritize_num_matching_fields: + default: true + description: 'Make Typesense prioritize documents where the query words + appear in more number of fields. + + ' + type: boolean + prioritize_token_position: + default: false + description: 'Make Typesense prioritize documents where the query words + appear earlier in the text. + + ' + type: boolean + 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 + remote_embedding_num_tries: + description: 'Number of times to retry fetching remote embeddings. + + ' + type: integer + remote_embedding_timeout_ms: + description: 'Timeout (in milliseconds) for fetching remote embeddings. + + ' + type: integer + 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 + snippet_threshold: + description: 'Field values under this length will be fully highlighted, + instead of showing a snippet of relevant portion. Default: 30 + + ' + 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 + 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 + synonym_num_typos: + description: 'Allow synonym resolution on typo-corrected words in the query. + Default: 0 + + ' + type: integer + synonym_prefix: + description: 'Allow synonym resolution on word prefixes in the query. Default: + false + + ' + type: boolean + 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 + 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 + use_cache: + description: 'Enable server side caching of search query results. By default, + caching is disabled. + + ' + type: boolean + vector_query: + description: 'Vector query expression for fetching documents "closest" to + a given query/document vector. + + ' + type: string + voice_query: + description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. + + ' + type: string + type: object + x-swift-builder: true + MultiSearchResult: + properties: + conversation: + $ref: '#/components/schemas/SearchResultConversation' + results: + items: + $ref: '#/components/schemas/MultiSearchResultItem' + type: array + x-swift-type: '[MultiSearchResultItem]' + required: + - results + type: object + x-swift-generic-parameter: + MultiSearchResultItem: + allOf: + - $ref: '#/components/schemas/SearchResult' + - properties: + code: + description: HTTP error code + format: int64 + type: integer + error: + description: Error description + type: string + type: object + x-swift-generic-parameter: D + MultiSearchSearchesParameter: + properties: + searches: + items: + $ref: '#/components/schemas/MultiSearchCollectionParameters' + type: array + union: + default: false + description: When true, merges the search results from each search query + into a single ordered set of hits. + type: boolean + required: + - searches + type: object + NLSearchModelBase: + properties: + access_token: + description: Access token for GCP Vertex AI + type: string + account_id: + description: Account ID for Cloudflare-specific models + type: string + api_key: + description: API key for the NL model service + type: string + api_url: + description: Custom API URL for the NL model service + type: string + api_version: + description: API version for the NL model service + type: string + client_id: + description: Client ID for GCP Vertex AI + type: string + client_secret: + description: Client secret for GCP Vertex AI + type: string + max_bytes: + description: Maximum number of bytes to process + type: integer + max_output_tokens: + description: Maximum output tokens for GCP Vertex AI + type: integer + model_name: + description: Name of the NL model to use + type: string + project_id: + description: Project ID for GCP Vertex AI + type: string + refresh_token: + description: Refresh token for GCP Vertex AI + type: string + region: + description: Region for GCP Vertex AI + type: string + stop_sequences: + description: Stop sequences for the NL model (Google-specific) + items: + type: string + type: array + system_prompt: + description: System prompt for the NL model + type: string + temperature: + description: Temperature parameter for the NL model + type: number + top_k: + description: Top-k parameter for the NL model (Google-specific) + type: integer + top_p: + description: Top-p parameter for the NL model (Google-specific) + type: number + type: object + NLSearchModelCreateSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelBase' + - properties: + id: + description: Optional ID for the NL search model + type: string + type: object + NLSearchModelDeleteSchema: + properties: + id: + description: ID of the deleted NL search model + type: string + required: + - id + type: object + NLSearchModelSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelCreateSchema' + - properties: + id: + description: ID of the NL search model + type: string + required: + - id + type: object + NLSearchModelUpdateSchema: + $ref: '#/components/schemas/NLSearchModelCreateSchema' + PresetDeleteSchema: + properties: + name: + type: string + required: + - name + type: object + PresetSchema: + allOf: + - $ref: '#/components/schemas/PresetUpsertSchema' + - properties: + name: + type: string + required: + - name + type: object + PresetUpsertSchema: + properties: + value: + oneOf: + - $ref: '#/components/schemas/SearchParameters' + - $ref: '#/components/schemas/MultiSearchSearchesParameter' + required: + - value + PresetsRetrieveSchema: + properties: + presets: + items: + $ref: '#/components/schemas/PresetSchema' + type: array + x-go-type: '[]*PresetSchema' + required: + - presets + type: object + SchemaChangeStatus: + properties: + altered_docs: + description: Number of documents that have been altered + type: integer + collection: + description: Name of the collection being modified + type: string + validated_docs: + description: Number of documents that have been validated + type: integer + type: object + SearchGroupedHit: + properties: + found: + type: integer + group_key: + items: {} + type: array + hits: + description: The documents that matched the search query + items: + $ref: '#/components/schemas/SearchResultHit' + type: array + x-swift-type: '[SearchResultHit]' + required: + - group_key + - hits + type: object + x-swift-generic-parameter: D + SearchHighlight: + properties: + field: + example: company_name + type: string + indices: + 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 + type: array + matched_tokens: + items: + type: object + x-go-type: interface{} + type: array + snippet: + description: Present only for (non-array) string fields + example: Stark Industries + type: string + snippets: + description: Present only for (array) string[] fields + example: + - Stark Industries + - Stark Corp + items: + type: string + type: array + value: + description: Full field value with highlighting, present only for (non-array) + string fields + example: Stark Industries is a major supplier of space equipment. + type: string + values: + description: Full field value with highlighting, present only for (array) + string[] fields + example: + - Stark Industries + - Stark Corp + items: + type: string + type: array + type: object + SearchParameters: + properties: + 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 + conversation: + description: 'Enable conversational search. + + ' + type: boolean + 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 + conversation_model_id: + description: 'The Id of Conversation Model to be used. + + ' + type: string + drop_tokens_mode: + $ref: '#/components/schemas/DropTokensMode' + 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 + enable_analytics: + default: true + description: 'Flag for enabling/disabling analytics aggregation for specific + search queries (for e.g. those originating from a test script). + + ' + type: boolean + enable_highlight_v1: + default: true + description: 'Flag for enabling/disabling the deprecated, old highlight + structure in the response. Default: true + + ' + type: boolean + enable_overrides: + default: false + 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 + enable_synonyms: + 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 + + ' + type: boolean + enable_typos_for_alpha_numerical_tokens: + description: 'Set this parameter to false to disable typos on alphanumerical + query tokens. Default: true. + + ' + type: boolean + enable_typos_for_numerical_tokens: + default: true + description: 'Make Typesense disable typos for numerical tokens. + + ' + type: boolean + exclude_fields: + description: List of fields from the document to exclude in the search result + type: string + 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 + facet_by: + description: A list of fields that will be used for faceting your results + on. Separate multiple fields with a comma. + type: string + 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 + facet_return_parent: + description: 'Comma separated string of nested facet fields whose parent + object should be returned in facet response. + + ' + type: string + facet_strategy: + description: 'Choose the underlying faceting strategy used. Comma separated + string of allows values: exhaustive, top_values or automatic (default). + + ' + type: string + filter_by: + description: Filter conditions for refining your open api validator search + results. Separate multiple conditions with &&. + example: 'num_employees:>100 && country: [USA, UK]' + type: string + filter_curated_hits: + 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 + + ' + type: boolean + 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 + 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 + highlight_affix_num_tokens: + description: 'The number of tokens that should surround the highlighted + text on each side. Default: 4 + + ' + type: integer + highlight_end_tag: + description: 'The end tag used for the highlighted snippets. Default: `` + + ' + type: string + highlight_fields: + description: 'A list of custom fields that must be highlighted even if you + don''t query for them + + ' + type: string + highlight_full_fields: + description: List of fields which should be highlighted fully without snippeting + type: string + highlight_start_tag: + description: 'The start tag used for the highlighted snippets. Default: + `` + + ' + type: string + include_fields: + description: List of fields from the document to include in the search result + 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 + limit: + description: 'Number of hits to fetch. Can be used as an alternative to + the per_page parameter. Default: 10. + + ' + type: integer + max_candidates: + description: 'Control the number of words that Typesense considers for typo + and prefix searching. + + ' + type: integer + 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 + max_facet_values: + description: Maximum number of facet values to be returned. + type: integer + 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 + 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 + nl_model_id: + description: The ID of the natural language model to use. + type: string + nl_query: + description: Whether to use natural language processing to parse the query. + type: boolean + num_typos: + description: 'The number of typographical errors (1 or 2) that would be + tolerated. Default: 2 + + ' + type: string + 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 + override_tags: + description: Comma separated list of tags to trigger the curations rules + that match the tags. + 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 + 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 + 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 + 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 + preset: + description: 'Search using a bunch of search parameters by setting this + parameter to the name of the existing Preset. + + ' + type: string + prioritize_exact_match: + default: true + description: 'Set this parameter to true to ensure that an exact match is + ranked above the others + + ' + type: boolean + prioritize_num_matching_fields: + default: true + description: 'Make Typesense prioritize documents where the query words + appear in more number of fields. + + ' + type: boolean + prioritize_token_position: + default: false + description: 'Make Typesense prioritize documents where the query words + appear earlier in the text. + + ' + type: boolean + 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 + remote_embedding_num_tries: + description: 'Number of times to retry fetching remote embeddings. + + ' + type: integer + remote_embedding_timeout_ms: + description: 'Timeout (in milliseconds) for fetching remote embeddings. + + ' + type: integer + 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 + snippet_threshold: + description: 'Field values under this length will be fully highlighted, + instead of showing a snippet of relevant portion. Default: 30 + + ' + 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` + example: num_employees:desc + 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 + 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 + synonym_num_typos: + description: 'Allow synonym resolution on typo-corrected words in the query. + Default: 0 + + ' + type: integer + synonym_prefix: + description: 'Allow synonym resolution on word prefixes in the query. Default: + false + + ' + type: boolean + synonym_sets: + description: List of synonym set names to associate with this search query + example: synonym_set_1,synonym_set_2 + 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 + 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 + use_cache: + description: 'Enable server side caching of search query results. By default, + caching is disabled. + + ' + type: boolean + vector_query: + description: 'Vector query expression for fetching documents "closest" to + a given query/document vector. + + ' + type: string + voice_query: + description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. + + ' + type: string + type: object + x-swift-builder: true + SearchRequestParams: + properties: + collection_name: + type: string + per_page: + type: integer + q: + type: string + voice_query: + properties: + transcribed_query: + type: string + type: object + required: + - collection_name + - q + - per_page + type: object + SearchResult: + properties: + conversation: + $ref: '#/components/schemas/SearchResultConversation' + facet_counts: + items: + $ref: '#/components/schemas/FacetCounts' + type: array + found: + description: The number of documents found + type: integer + found_docs: + type: integer + grouped_hits: + items: + $ref: '#/components/schemas/SearchGroupedHit' + type: array + x-swift-type: '[SearchGroupedHit]?' + hits: + description: The documents that matched the search query + items: + $ref: '#/components/schemas/SearchResultHit' + type: array + x-swift-type: '[SearchResultHit]?' + metadata: + additionalProperties: true + description: Custom JSON object that can be returned in the search response + type: object + out_of: + description: The total number of documents in the collection + type: integer + page: + description: The search result page number + type: integer + request_params: + $ref: '#/components/schemas/SearchRequestParams' + search_cutoff: + description: Whether the search was cut off + type: boolean + search_time_ms: + description: The number of milliseconds the search took + type: integer + union_request_params: + description: Returned only for union query response. + items: + $ref: '#/components/schemas/SearchRequestParams' + type: array + type: object + x-swift-generic-parameter: D + SearchResultConversation: + properties: + answer: + type: string + conversation_history: + items: + type: object + type: array + conversation_id: + type: string + query: + type: string + required: + - answer + - conversation_history + - conversation_id + - query + type: object + SearchResultHit: + example: + document: + company_name: Stark Industries + country: USA + id: '124' + num_employees: 5215 + highlights: + company_name: + field: company_name + snippet: Stark Industries + text_match: 1234556 + properties: + document: + additionalProperties: + type: object + description: Can be any key-value pair + type: object + x-swift-type: D? + geo_distance_meters: + additionalProperties: + type: integer + description: Can be any key-value pair + type: object + highlight: + additionalProperties: true + description: Highlighted version of the matching document + type: object + highlights: + description: (Deprecated) Contains highlighted portions of the search fields + items: + $ref: '#/components/schemas/SearchHighlight' + type: array + hybrid_search_info: + description: Information about hybrid search scoring + properties: + rank_fusion_score: + description: Combined score from rank fusion of text and vector search + format: float + type: number + type: object + search_index: + description: Returned only for union query response. Indicates the index + of the query which this document matched to. + type: integer + text_match: + format: int64 + type: integer + text_match_info: + properties: + best_field_score: + type: string + best_field_weight: + type: integer + fields_matched: + type: integer + num_tokens_dropped: + format: int64 + type: integer + x-go-type: uint64 + score: + type: string + tokens_matched: + type: integer + typo_prefix_score: + type: integer + type: object + vector_distance: + description: Distance between the query vector and matching document's vector + value + format: float + type: number + type: object + x-swift-generic-parameter: D + SearchSynonym: + allOf: + - $ref: '#/components/schemas/SearchSynonymSchema' + - properties: + id: + readOnly: true + type: string + required: + - id + type: object + SearchSynonymDeleteResponse: + properties: + id: + description: The id of the synonym that was deleted + type: string + required: + - id + type: object + SearchSynonymSchema: + properties: + locale: + description: Locale for the synonym, leave blank to use the standard tokenizer. + type: string + root: + description: For 1-way synonyms, indicates the root word that words in the + `synonyms` parameter map to. + type: string + symbols_to_index: + 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 + type: array + synonyms: + description: Array of words that should be considered as synonyms. + items: + type: string + type: array + required: + - synonyms + type: object + SearchSynonymsResponse: + properties: + synonyms: + items: + $ref: '#/components/schemas/SearchSynonym' + type: array + x-go-type: '[]*SearchSynonym' + required: + - synonyms + type: object + StemmingDictionary: + properties: + id: + description: Unique identifier for the dictionary + example: irregular-plurals + type: string + words: + description: List of word mappings in the dictionary + items: + properties: + root: + description: The root form of the word + example: person + type: string + word: + description: The word form to be stemmed + example: people + type: string + required: + - word + - root + type: object + type: array + required: + - id + - words + type: object + StopwordsSetRetrieveSchema: + example: '{"stopwords": {"id": "countries", "stopwords": ["Germany", "France", + "Italy"], "locale": "en"}} + + ' + properties: + stopwords: + $ref: '#/components/schemas/StopwordsSetSchema' + required: + - stopwords + type: object + StopwordsSetSchema: + example: '{"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": + "en"} + + ' + properties: + id: + type: string + locale: + type: string + stopwords: + items: + type: string + type: array + required: + - id + - stopwords + type: object + StopwordsSetUpsertSchema: + example: '{"stopwords": ["Germany", "France", "Italy"], "locale": "en"} + + ' + properties: + locale: + type: string + stopwords: + items: + type: string + type: array + required: + - stopwords + type: object + StopwordsSetsRetrieveAllSchema: + example: '{"stopwords": [{"id": "countries", "stopwords": ["Germany", "France", + "Italy"], "locale": "en"}]} + + ' + properties: + stopwords: + items: + $ref: '#/components/schemas/StopwordsSetSchema' + type: array + required: + - stopwords + type: object + SuccessStatus: + properties: + success: + type: boolean + required: + - success + type: object + SynonymItemDeleteSchema: + properties: + id: + description: ID of the deleted synonym item + type: string + required: + - id + type: object + SynonymItemSchema: + properties: + id: + description: Unique identifier for the synonym item + type: string + locale: + description: Locale for the synonym, leave blank to use the standard tokenizer + type: string + root: + description: For 1-way synonyms, indicates the root word that words in the + synonyms parameter map to + type: string + symbols_to_index: + 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 + type: array + synonyms: + description: Array of words that should be considered as synonyms + items: + type: string + type: array + required: + - id + - synonyms + type: object + SynonymSetCreateSchema: + properties: + items: + description: Array of synonym items + items: + $ref: '#/components/schemas/SynonymItemSchema' + type: array + required: + - items + type: object + SynonymSetDeleteSchema: + properties: + name: + description: Name of the deleted synonym set + type: string + required: + - name + type: object + SynonymSetRetrieveSchema: + $ref: '#/components/schemas/SynonymSetCreateSchema' + SynonymSetSchema: + allOf: + - $ref: '#/components/schemas/SynonymSetCreateSchema' + - properties: + name: + description: Name of the synonym set + type: string + required: + - name + type: object + SynonymSetsRetrieveSchema: + properties: + synonym_sets: + description: Array of synonym sets + items: + $ref: '#/components/schemas/SynonymSetSchema' + type: array + required: + - synonym_sets + type: object + UpdateDocumentsParameters: + properties: + filter_by: + example: 'num_employees:>100 && country: [USA, UK]' + type: string + type: object + VoiceQueryModelCollectionConfig: + description: 'Configuration for the voice query model + + ' + properties: + model_name: + example: ts/whisper/base.en + type: string + type: object + securitySchemes: + api_key_header: + in: header + name: X-TYPESENSE-API-KEY + type: apiKey +externalDocs: + description: Find out more about Typsesense + url: https://typesense.org +info: + description: An open source search engine for building delightful search experiences. + license: + name: GPL-3.0 + url: https://opensource.org/licenses/GPL-3.0 + title: Typesense API + version: '30.0' +openapi: 3.0.3 +paths: + /aliases: + get: + description: List all aliases and the corresponding collections that they map + to. + operationId: getAliases + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAliasesResponse' + description: List of all collection aliases + summary: List all aliases + tags: + - collections + /aliases/{aliasName}: + delete: + operationId: deleteAlias + parameters: + - description: The name of the alias to delete + in: path + name: aliasName + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAlias' + description: Collection alias was deleted + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Alias not found + summary: Delete an alias + tags: + - collections + get: + description: Find out which collection an alias points to by fetching it + operationId: getAlias + parameters: + - description: The name of the alias to retrieve + in: path + name: aliasName + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAlias' + description: Collection alias fetched + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: The alias was not found + summary: Retrieve an alias + tags: + - collections + put: + 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: + - description: The name of the alias to create/update + in: path + name: aliasName + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAliasSchema' + description: Collection alias to be created/updated + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAlias' + description: The collection alias was created/updated + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Alias not found + summary: Create or update a collection alias + tags: + - collections + /analytics/events: + get: + description: Retrieve the most recent events for a user and rule. + operationId: getAnalyticsEvents + parameters: + - in: query + name: user_id + required: true + schema: + type: string + - description: Analytics rule name + in: query + name: name + required: true + schema: + type: string + - description: Number of events to return (max 1000) + in: query + name: n + required: true + schema: + type: integer + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventsResponse' + description: Events fetched + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + summary: Retrieve analytics events + tags: + - analytics + post: + description: Submit a single analytics event. The event must correspond to an + existing analytics rule by name. + operationId: createAnalyticsEvent + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEvent' + description: The analytics event to be created + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventCreateResponse' + description: Analytics event successfully created + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + summary: Create an analytics event + tags: + - analytics + /analytics/flush: + post: + description: Triggers a flush of analytics data to persistent storage. + operationId: flushAnalytics + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventCreateResponse' + description: Flush triggered + summary: Flush in-memory analytics to disk + tags: + - analytics + /analytics/rules: + get: + description: Retrieve all analytics rules. Use the optional rule_tag filter + to narrow down results. + operationId: retrieveAnalyticsRules + parameters: + - description: Filter rules by rule_tag + in: query + name: rule_tag + required: false + schema: + type: string + responses: + '200': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/AnalyticsRule' + type: array + description: Analytics rules fetched + summary: Retrieve analytics rules + tags: + - analytics + post: + description: Create one or more analytics rules. You can send a single rule + object or an array of rule objects. + operationId: createAnalyticsRule + requestBody: + content: + application/json: + schema: + oneOf: + - $ref: '#/components/schemas/AnalyticsRuleCreate' + - items: + $ref: '#/components/schemas/AnalyticsRuleCreate' + type: array + description: The analytics rule(s) to be created + required: true + responses: + '200': + content: + application/json: + schema: + oneOf: + - $ref: '#/components/schemas/AnalyticsRule' + - items: + anyOf: + - $ref: '#/components/schemas/AnalyticsRule' + - properties: + error: + type: string + type: object + type: array + description: Analytics rule(s) successfully created + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + summary: Create analytics rule(s) + tags: + - analytics + /analytics/rules/{ruleName}: + delete: + description: Permanently deletes an analytics rule, given it's name + operationId: deleteAnalyticsRule + parameters: + - description: The name of the analytics rule to delete + in: path + name: ruleName + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRule' + description: Analytics rule deleted + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Analytics rule not found + summary: Delete an analytics rule + tags: + - analytics + get: + description: Retrieve the details of an analytics rule, given it's name + operationId: retrieveAnalyticsRule + parameters: + - description: The name of the analytics rule to retrieve + in: path + name: ruleName + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRule' + description: Analytics rule fetched + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Analytics rule not found + summary: Retrieves an analytics rule + tags: + - analytics + put: + description: Upserts an analytics rule with the given name. + operationId: upsertAnalyticsRule + parameters: + - description: The name of the analytics rule to upsert + in: path + name: ruleName + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRuleUpdate' + description: The Analytics rule to be upserted + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRule' + description: Analytics rule successfully upserted + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + summary: Upserts an analytics rule + tags: + - analytics + /analytics/status: + get: + description: Returns sizes of internal analytics buffers and queues. + operationId: getAnalyticsStatus + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsStatus' + description: Status fetched + summary: Get analytics subsystem status + tags: + - analytics + /collections: + get: + 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 + parameters: + - in: query + name: exclude_fields + schema: + description: Comma-separated list of fields from the collection to exclude + from the response + type: string + - in: query + name: offset + schema: + description: Identifies the starting point to return collections when paginating. + type: integer + - in: query + name: limit + schema: + description: 'Number of collections to fetch. Default: returns all collections. + + ' + type: integer + responses: + '200': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/CollectionResponse' + type: array + x-go-type: '[]*CollectionResponse' + description: List of all collections + summary: List all collections + tags: + - collections + post: + 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: + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionSchema' + description: The collection object to be created + required: true + responses: + '201': + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionResponse' + description: Collection successfully created + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + '409': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Collection already exists + summary: Create a new collection + tags: + - collections + /collections/{collectionName}: + delete: + description: Permanently drops a collection. This action cannot be undone. For + large collections, this might have an impact on read latencies. + operationId: deleteCollection + parameters: + - description: The name of the collection to delete + in: path + name: collectionName + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionResponse' + description: Collection deleted + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Collection not found + summary: Delete a collection + tags: + - collections + get: + description: Retrieve the details of a collection, given its name. + operationId: getCollection + parameters: + - description: The name of the collection to retrieve + in: path + name: collectionName + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionResponse' + description: Collection fetched + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Collection not found + summary: Retrieve a single collection + tags: + - collections + patch: + description: Update a collection's schema to modify the fields and their types. + operationId: updateCollection + parameters: + - description: The name of the collection to update + in: path + name: collectionName + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionUpdateSchema' + description: The document object with fields to be updated + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionUpdateSchema' + description: The updated partial collection schema + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: The collection was not found + summary: Update a collection + tags: + - collections + /collections/{collectionName}/documents: + delete: + 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: + - description: The name of the collection to delete documents from + in: path + name: collectionName + required: true + schema: + type: string + - in: query + name: ignore_not_found + schema: + type: boolean + - in: query + name: batch_size + 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 + - in: query + name: truncate + schema: + description: When true, removes all documents from the collection while + preserving the collection and its schema. + type: boolean + - in: query + name: filter_by + schema: + example: 'num_employees:>100 && country: [USA, UK]' + type: string + responses: + '200': + content: + application/json: + schema: + properties: + num_deleted: + type: integer + required: + - num_deleted + type: object + description: Documents successfully deleted + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Collection not found + summary: Delete a bunch of documents + tags: + - documents + patch: + 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: + - description: The name of the collection to update documents in + in: path + name: collectionName + required: true + schema: + type: string + - in: query + name: filter_by + schema: + example: 'num_employees:>100 && country: [USA, UK]' + type: string + requestBody: + content: + application/json: + schema: + description: Can be any key-value pair + type: object + x-go-type: interface{} + description: The document fields to be updated + required: true + responses: + '200': + content: + application/json: + schema: + properties: + num_updated: + description: The number of documents that have been updated + example: 1 + type: integer + required: + - num_updated + type: object + description: The response contains a single field, `num_updated`, indicating + the number of documents affected. + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: The collection was not found + summary: Update documents with conditional query + tags: + - documents + post: + description: A document to be indexed in a given collection must conform to + the schema of the collection. + operationId: indexDocument + parameters: + - description: The name of the collection to add the document to + in: path + name: collectionName + required: true + schema: + type: string + - description: Additional action to perform + in: query + name: action + schema: + $ref: '#/components/schemas/IndexAction' + example: upsert + type: string + - description: Dealing with Dirty Data + in: query + name: dirty_values + schema: + $ref: '#/components/schemas/DirtyValues' + requestBody: + content: + application/json: + schema: + description: Can be any key-value pair + type: object + x-go-type: interface{} + description: The document object to be indexed + required: true + responses: + '201': + content: + application/json: + schema: + description: Can be any key-value pair + type: object + description: Document successfully created/indexed + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Collection not found + summary: Index a document + tags: + - documents + /collections/{collectionName}/documents/export: + get: + description: Export all documents in a collection in JSON lines format. + operationId: exportDocuments + parameters: + - description: The name of the collection + in: path + name: collectionName + required: true + schema: + type: string + - in: query + name: include_fields + schema: + description: List of fields from the document to include in the search result + type: string + - in: query + name: exclude_fields + schema: + description: List of fields from the document to exclude in the search result + type: string + - in: query + name: filter_by + schema: + description: Filter conditions for refining your search results. Separate + multiple conditions with &&. + type: string + responses: + '200': + content: + application/octet-stream: + schema: + 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"} + + ' + type: string + description: Exports all the documents in a given collection. + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: The collection was not found + summary: Export all documents in a collection + tags: + - documents + /collections/{collectionName}/documents/import: + post: + 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: + - description: The name of the collection + in: path + name: collectionName + required: true + schema: + type: string + - in: query + name: return_id + schema: + 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. + type: boolean + - in: query + name: batch_size + schema: + type: integer + - in: query + name: action + schema: + $ref: '#/components/schemas/IndexAction' + - in: query + name: dirty_values + schema: + $ref: '#/components/schemas/DirtyValues' + - in: query + name: return_doc + schema: + type: boolean + - in: query + name: remote_embedding_batch_size + schema: + type: integer + requestBody: + content: + application/octet-stream: + schema: + description: The JSONL file to import + type: string + description: The json array of documents or the JSONL file to import + required: true + responses: + '200': + content: + application/octet-stream: + schema: + example: '{"success": true} + + {"success": false, "error": "Bad JSON.", "document": "[bad doc"} + + ' + type: string + 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. + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: The collection was not found + summary: Import documents into a collection + tags: + - documents + /collections/{collectionName}/documents/search: + get: + description: Search for documents in a collection that match the search criteria. + operationId: searchCollection + parameters: + - description: The name of the collection to search for the document under + in: path + name: collectionName + required: true + schema: + type: string + - in: query + name: group_missing_values + 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 + - in: query + name: min_len_2typo + 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 + - in: query + name: split_join_tokens + 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 + - in: query + name: max_facet_values + schema: + description: Maximum number of facet values to be returned. + type: integer + - in: query + name: synonym_prefix + schema: + description: 'Allow synonym resolution on word prefixes in the query. Default: + false + + ' + type: boolean + - in: query + name: cache_ttl + 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 + - in: query + name: hidden_hits + 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 + - in: query + name: exclude_fields + schema: + description: List of fields from the document to exclude in the search result + type: string + - in: query + name: conversation_id + schema: + description: 'The Id of a previous conversation to continue, this tells + Typesense to include prior context when communicating with the LLM. + + ' + type: string + - in: query + name: exhaustive_search + 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 + - in: query + name: snippet_threshold + schema: + description: 'Field values under this length will be fully highlighted, + instead of showing a snippet of relevant portion. Default: 30 + + ' + type: integer + - in: query + name: query_by + schema: + description: A list of `string` fields that should be queried against. Multiple + fields are separated with a comma. + type: string + - in: query + name: synonym_sets + schema: + description: List of synonym set names to associate with this search query + example: synonym_set_1,synonym_set_2 + type: string + - in: query + name: q + 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 + - in: query + name: page + schema: + description: Results from this specific page number would be fetched. + type: integer + - in: query + name: group_limit + 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 + - in: query + name: limit + schema: + description: 'Number of hits to fetch. Can be used as an alternative to + the per_page parameter. Default: 10. + + ' + type: integer + - in: query + name: pinned_hits + 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 + - in: query + name: synonym_num_typos + schema: + description: 'Allow synonym resolution on typo-corrected words in the query. + Default: 0 + + ' + type: integer + - in: query + name: prefix + 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 + - in: query + name: enable_overrides + schema: + default: false + 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 + - in: query + name: prioritize_num_matching_fields + schema: + default: true + description: 'Make Typesense prioritize documents where the query words + appear in more number of fields. + + ' + type: boolean + - in: query + name: voice_query + schema: + description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. + + ' + type: string + - in: query + name: max_extra_prefix + 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 + - in: query + name: nl_query + schema: + description: Whether to use natural language processing to parse the query. + type: boolean + - in: query + name: num_typos + schema: + description: 'The number of typographical errors (1 or 2) that would be + tolerated. Default: 2 + + ' + type: string + - in: query + name: offset + 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 + - in: query + name: drop_tokens_threshold + 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 + - in: query + name: facet_strategy + schema: + description: 'Choose the underlying faceting strategy used. Comma separated + string of allows values: exhaustive, top_values or automatic (default). + + ' + type: string + - in: query + name: use_cache + schema: + description: 'Enable server side caching of search query results. By default, + caching is disabled. + + ' + type: boolean + - in: query + name: text_match_type + 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 + - in: query + name: query_by_weights + 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 + - in: query + name: per_page + schema: + description: 'Number of results to fetch per page. Default: 10' + type: integer + - in: query + name: facet_by + schema: + description: A list of fields that will be used for faceting your results + on. Separate multiple fields with a comma. + type: string + - in: query + name: conversation_model_id + schema: + description: 'The Id of Conversation Model to be used. + + ' + type: string + - in: query + name: max_extra_suffix + 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 + - in: query + name: group_by + 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 + - in: query + name: min_len_1typo + 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 + - in: query + name: remote_embedding_num_tries + schema: + description: 'Number of times to retry fetching remote embeddings. + + ' + type: integer + - in: query + name: stopwords + 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 + - in: query + name: enable_typos_for_numerical_tokens + schema: + default: true + description: 'Make Typesense disable typos for numerical tokens. + + ' + type: boolean + - in: query + name: max_filter_by_candidates + 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 + - in: query + name: prioritize_exact_match + schema: + default: true + description: 'Set this parameter to true to ensure that an exact match is + ranked above the others + + ' + type: boolean + - in: query + name: search_cutoff_ms + 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 + - in: query + name: highlight_affix_num_tokens + schema: + description: 'The number of tokens that should surround the highlighted + text on each side. Default: 4 + + ' + type: integer + - in: query + name: infix + 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 + - in: query + name: highlight_fields + schema: + description: 'A list of custom fields that must be highlighted even if you + don''t query for them + + ' + type: string + - in: query + name: drop_tokens_mode + schema: + $ref: '#/components/schemas/DropTokensMode' + - in: query + name: filter_by + schema: + description: Filter conditions for refining your open api validator search + results. Separate multiple conditions with &&. + example: 'num_employees:>100 && country: [USA, UK]' + type: string + - in: query + name: remote_embedding_timeout_ms + schema: + description: 'Timeout (in milliseconds) for fetching remote embeddings. + + ' + type: integer + - in: query + name: preset + schema: + description: 'Search using a bunch of search parameters by setting this + parameter to the name of the existing Preset. + + ' + type: string + - in: query + name: enable_highlight_v1 + schema: + default: true + description: 'Flag for enabling/disabling the deprecated, old highlight + structure in the response. Default: true + + ' + type: boolean + - in: query + name: nl_model_id + schema: + description: The ID of the natural language model to use. + type: string + - in: query + name: filter_curated_hits + schema: + 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 + + ' + type: boolean + - in: query + name: enable_synonyms + schema: + 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 + + ' + type: boolean + - in: query + name: sort_by + 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` + example: num_employees:desc + type: string + - in: query + name: facet_return_parent + schema: + description: 'Comma separated string of nested facet fields whose parent + object should be returned in facet response. + + ' + type: string + - in: query + name: pre_segmented_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 + - in: query + name: include_fields + schema: + description: List of fields from the document to include in the search result + type: string + - in: query + name: prioritize_token_position + schema: + default: false + description: 'Make Typesense prioritize documents where the query words + appear earlier in the text. + + ' + type: boolean + - in: query + name: enable_typos_for_alpha_numerical_tokens + schema: + description: 'Set this parameter to false to disable typos on alphanumerical + query tokens. Default: true. + + ' + type: boolean + - in: query + name: highlight_start_tag + schema: + description: 'The start tag used for the highlighted snippets. Default: + `` + + ' + type: string + - in: query + name: facet_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 + - in: query + name: vector_query + schema: + description: 'Vector query expression for fetching documents "closest" to + a given query/document vector. + + ' + type: string + - in: query + name: conversation + schema: + description: 'Enable conversational search. + + ' + type: boolean + - in: query + name: highlight_end_tag + schema: + description: 'The end tag used for the highlighted snippets. Default: `` + + ' + type: string + - in: query + name: typo_tokens_threshold + 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 + - in: query + name: override_tags + schema: + description: Comma separated list of tags to trigger the curations rules + that match the tags. + type: string + - in: query + name: max_candidates + schema: + description: 'Control the number of words that Typesense considers for typo + and prefix searching. + + ' + type: integer + - in: query + name: enable_analytics + schema: + default: true + description: 'Flag for enabling/disabling analytics aggregation for specific + search queries (for e.g. those originating from a test script). + + ' + type: boolean + - in: query + name: highlight_full_fields + schema: + description: List of fields which should be highlighted fully without snippeting + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/SearchResult' + description: Search results + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: The collection or field was not found + summary: Search for documents in a collection + tags: + - documents + /collections/{collectionName}/documents/{documentId}: + delete: + description: Delete an individual document from a collection by using its ID. + operationId: deleteDocument + parameters: + - description: The name of the collection to search for the document under + in: path + name: collectionName + required: true + schema: + type: string + - description: The Document ID + in: path + name: documentId + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + description: Can be any key-value pair + type: object + description: The document referenced by the ID was deleted + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: The document or collection was not found + summary: Delete a document + tags: + - documents + get: + description: Fetch an individual document from a collection by using its ID. + operationId: getDocument + parameters: + - description: The name of the collection to search for the document under + in: path + name: collectionName + required: true + schema: + type: string + - description: The Document ID + in: path + name: documentId + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + description: Can be any key-value pair + type: object + description: The document referenced by the ID + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: The document or collection was not found + summary: Retrieve a document + tags: + - documents + patch: + description: Update an individual document from a collection by using its ID. + The update can be partial. + operationId: updateDocument + parameters: + - description: The name of the collection to search for the document under + in: path + name: collectionName + required: true + schema: + type: string + - description: The Document ID + in: path + name: documentId + required: true + schema: + type: string + - description: Dealing with Dirty Data + in: query + name: dirty_values + schema: + $ref: '#/components/schemas/DirtyValues' + requestBody: + content: + application/json: + schema: + description: Can be any key-value pair + type: object + x-go-type: interface{} + description: The document object with fields to be updated + required: true + responses: + '200': + content: + application/json: + schema: + description: Can be any key-value pair + type: object + description: The document referenced by the ID was updated + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: The document or collection was not found + summary: Update a document + tags: + - documents + /config: + post: + description: Enable logging of requests that take over a defined threshold of + time. Default is `-1` which disables slow request logging. Slow requests are + logged to the primary log file, with the prefix SLOW REQUEST. + operationId: toggleSlowRequestLog + requestBody: + content: + application/json: + schema: + example: '{"log-slow-requests-time-ms": 2000} + + ' + properties: + log-slow-requests-time-ms: + type: integer + required: + - log-slow-requests-time-ms + type: object + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + description: Compacting the on-disk database succeeded. + summary: Toggle Slow Request Log + tags: + - operations + /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: + '201': + 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 + summary: Create a conversation model + tags: + - conversations + /conversations/models/{modelId}: + delete: + description: Delete a conversation model + operationId: deleteConversationModel + parameters: + - description: The id of the conversation model to delete + in: path + name: modelId + 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 + get: + description: Retrieve a conversation model + operationId: retrieveConversationModel + parameters: + - description: The id of the conversation model to retrieve + in: path + name: modelId + 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 + parameters: + - description: The id of the conversation model to update + in: path + name: modelId + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelUpdateSchema' + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: The conversation model was successfully updated + summary: Update a conversation model + tags: + - conversations + /curation_sets: + get: + description: Retrieve all curation sets + operationId: retrieveCurationSets + responses: + '200': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/CurationSetSchema' + type: array + description: List of all curation sets + summary: List all curation sets + tags: + - curation_sets + /curation_sets/{curationSetName}: + delete: + description: Delete a specific curation set by its name + operationId: deleteCurationSet + parameters: + - description: The name of the curation set to delete + in: path + name: curationSetName + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CurationSetDeleteSchema' + description: Curation set successfully deleted + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Curation set not found + summary: Delete a curation set + tags: + - curation_sets + get: + description: Retrieve a specific curation set by its name + operationId: retrieveCurationSet + parameters: + - description: The name of the curation set to retrieve + in: path + name: curationSetName + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CurationSetRetrieveSchema' + description: Curation set fetched + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Curation set not found + summary: Retrieve a curation set + tags: + - curation_sets + put: + description: Create or update a curation set with the given name + operationId: upsertCurationSet + parameters: + - description: The name of the curation set to create/update + in: path + name: curationSetName + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CurationSetCreateSchema' + description: The curation set to be created/updated + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CurationSetSchema' + description: Curation set successfully created/updated + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + summary: Create or update a curation set + tags: + - curation_sets + /curation_sets/{curationSetName}/items: + get: + description: Retrieve all curation items in a set + operationId: retrieveCurationSetItems + parameters: + - description: The name of the curation set to retrieve items for + in: path + name: curationSetName + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/CurationItemSchema' + type: array + description: List of curation items + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Curation set not found + summary: List items in a curation set + tags: + - curation_sets + /curation_sets/{curationSetName}/items/{itemId}: + delete: + description: Delete a specific curation item by its id + operationId: deleteCurationSetItem + parameters: + - description: The name of the curation set + in: path + name: curationSetName + required: true + schema: + type: string + - description: The id of the curation item to delete + in: path + name: itemId + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CurationItemDeleteSchema' + description: Curation item successfully deleted + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Curation item not found + summary: Delete a curation set item + tags: + - curation_sets + get: + description: Retrieve a specific curation item by its id + operationId: retrieveCurationSetItem + parameters: + - description: The name of the curation set + in: path + name: curationSetName + required: true + schema: + type: string + - description: The id of the curation item to retrieve + in: path + name: itemId + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CurationItemSchema' + description: Curation item fetched + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Curation item not found + summary: Retrieve a curation set item + tags: + - curation_sets + put: + description: Create or update a curation set item with the given id + operationId: upsertCurationSetItem + parameters: + - description: The name of the curation set + in: path + name: curationSetName + required: true + schema: + type: string + - description: The id of the curation item to upsert + in: path + name: itemId + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CurationItemCreateSchema' + description: The curation item to be created/updated + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/CurationItemSchema' + description: Curation item successfully created/updated + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + summary: Create or update a curation set item + tags: + - curation_sets + /debug: + get: + description: Print debugging information + operationId: debug + responses: + '200': + content: + application/json: + schema: + properties: + version: + type: string + type: object + description: Debugging information + summary: Print debugging information + tags: + - debug + /health: + get: + description: Checks if Typesense server is ready to accept requests. + operationId: health + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/HealthStatus' + description: Search service is ready for requests. + summary: Checks if Typesense server is ready to accept requests. + tags: + - health + /keys: + get: + operationId: getKeys + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeysResponse' + description: List of all keys + summary: Retrieve (metadata about) all keys. + tags: + - keys + post: + 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: + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeySchema' + description: The object that describes API key scope + responses: + '201': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKey' + description: Created API key + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + '409': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: API key generation conflict + summary: Create an API Key + tags: + - keys + /keys/{keyId}: + delete: + operationId: deleteKey + parameters: + - description: The ID of the key to delete + in: path + name: keyId + required: true + schema: + format: int64 + type: integer + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeyDeleteResponse' + description: The key referenced by the ID + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Key not found + summary: Delete an API key given its ID. + tags: + - keys + get: + 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: + - description: The ID of the key to retrieve + in: path + name: keyId + required: true + schema: + format: int64 + type: integer + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKey' + description: The key referenced by the ID + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: The key was not found + summary: Retrieve (metadata about) a key + tags: + - keys + /metrics.json: + get: + description: Retrieve the metrics. + operationId: retrieveMetrics + responses: + '200': + content: + application/json: + schema: + type: object + description: Metrics fetched. + summary: Get current RAM, CPU, Disk & Network usage metrics. + tags: + - operations + /multi_search: + post: + 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. + operationId: multiSearch + parameters: + - in: query + name: group_missing_values + 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 + - in: query + name: min_len_2typo + 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 + - in: query + name: max_facet_values + schema: + description: Maximum number of facet values to be returned. + type: integer + - in: query + name: synonym_prefix + schema: + description: 'Allow synonym resolution on word prefixes in the query. Default: + false + + ' + type: boolean + - in: query + name: conversation_id + schema: + description: 'The Id of a previous conversation to continue, this tells + Typesense to include prior context when communicating with the LLM. + + ' + type: string + - in: query + name: cache_ttl + 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 + - in: query + name: exclude_fields + schema: + description: List of fields from the document to exclude in the search result + type: string + - in: query + name: hidden_hits + 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 + - in: query + name: exhaustive_search + 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 + - in: query + name: snippet_threshold + schema: + description: 'Field values under this length will be fully highlighted, + instead of showing a snippet of relevant portion. Default: 30 + + ' + type: integer + - in: query + name: query_by + schema: + description: A list of `string` fields that should be queried against. Multiple + fields are separated with a comma. + type: string + - in: query + name: page + schema: + description: Results from this specific page number would be fetched. + type: integer + - in: query + name: q + 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 + - in: query + name: group_limit + 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 + - in: query + name: synonym_num_typos + schema: + description: 'Allow synonym resolution on typo-corrected words in the query. + Default: 0 + + ' + type: integer + - in: query + name: limit + schema: + description: 'Number of hits to fetch. Can be used as an alternative to + the per_page parameter. Default: 10. + + ' + type: integer + - in: query + name: pinned_hits + 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 + - in: query + name: prefix + 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 + - in: query + name: enable_overrides + schema: + default: false + 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 + - in: query + name: prioritize_num_matching_fields + schema: + default: true + description: 'Make Typesense prioritize documents where the query words + appear in more number of fields. + + ' + type: boolean + - in: query + name: voice_query + schema: + description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. + + ' + type: string + - in: query + name: max_extra_prefix + 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 + - in: query + name: num_typos + schema: + description: 'The number of typographical errors (1 or 2) that would be + tolerated. Default: 2 + + ' + type: string + - in: query + name: facet_strategy + schema: + description: 'Choose the underlying faceting strategy used. Comma separated + string of allows values: exhaustive, top_values or automatic (default). + + ' + type: string + - in: query + name: offset + 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 + - in: query + name: drop_tokens_threshold + 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 + - in: query + name: use_cache + schema: + description: 'Enable server side caching of search query results. By default, + caching is disabled. + + ' + type: boolean + - in: query + name: per_page + schema: + description: 'Number of results to fetch per page. Default: 10' + type: integer + - in: query + name: text_match_type + 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 + - in: query + name: query_by_weights + 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 + - in: query + name: facet_by + schema: + description: A list of fields that will be used for faceting your results + on. Separate multiple fields with a comma. + type: string + - in: query + name: group_by + 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 + - in: query + name: conversation_model_id + schema: + description: 'The Id of Conversation Model to be used. + + ' + type: string + - in: query + name: min_len_1typo + 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 + - in: query + name: max_extra_suffix + 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 + - in: query + name: stopwords + 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 + - in: query + name: remote_embedding_num_tries + schema: + description: 'Number of times to retry fetching remote embeddings. + + ' + type: integer + - in: query + name: enable_typos_for_numerical_tokens + schema: + default: true + description: 'Make Typesense disable typos for numerical tokens. + + ' + type: boolean + - in: query + name: prioritize_exact_match + schema: + default: true + description: 'Set this parameter to true to ensure that an exact match is + ranked above the others + + ' + type: boolean + - in: query + name: search_cutoff_ms + 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 + - in: query + name: highlight_affix_num_tokens + schema: + description: 'The number of tokens that should surround the highlighted + text on each side. Default: 4 + + ' + type: integer + - in: query + name: infix + 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 + - in: query + name: highlight_fields + schema: + description: 'A list of custom fields that must be highlighted even if you + don''t query for them + + ' + type: string + - in: query + name: filter_by + schema: + description: Filter conditions for refining youropen api validator search + results. Separate multiple conditions with &&. + example: 'num_employees:>100 && country: [USA, UK]' + type: string + - in: query + name: drop_tokens_mode + schema: + $ref: '#/components/schemas/DropTokensMode' + - in: query + name: remote_embedding_timeout_ms + schema: + description: 'Timeout (in milliseconds) for fetching remote embeddings. + + ' + type: integer + - in: query + name: enable_typos_for_alpha_numerical_tokens + schema: + description: 'Set this parameter to false to disable typos on alphanumerical + query tokens. Default: true. + + ' + type: boolean + - in: query + name: preset + schema: + description: 'Search using a bunch of search parameters by setting this + parameter to the name of the existing Preset. + + ' + type: string + - in: query + name: filter_curated_hits + schema: + 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 + + ' + type: boolean + - in: query + name: pre_segmented_query + schema: + default: false + 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 + - in: query + name: include_fields + schema: + description: List of fields from the document to include in the search result + type: string + - in: query + name: sort_by + 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 + - in: query + name: enable_synonyms + schema: + 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 + + ' + type: boolean + - in: query + name: facet_return_parent + schema: + description: 'Comma separated string of nested facet fields whose parent + object should be returned in facet response. + + ' + type: string + - in: query + name: prioritize_token_position + schema: + default: false + description: 'Make Typesense prioritize documents where the query words + appear earlier in the text. + + ' + type: boolean + - in: query + name: highlight_start_tag + schema: + description: 'The start tag used for the highlighted snippets. Default: + `` + + ' + type: string + - in: query + name: facet_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 + - in: query + name: vector_query + schema: + description: 'Vector query expression for fetching documents "closest" to + a given query/document vector. + + ' + type: string + - in: query + name: conversation + schema: + description: 'Enable conversational search. + + ' + type: boolean + - in: query + name: highlight_end_tag + schema: + description: 'The end tag used for the highlighted snippets. Default: `` + + ' + type: string + - in: query + name: typo_tokens_threshold + 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 + - in: query + name: override_tags + schema: + description: Comma separated list of tags to trigger the curations rules + that match the tags. + type: string + - in: query + name: enable_analytics + schema: + default: true + description: 'Flag for enabling/disabling analytics aggregation for specific + search queries (for e.g. those originating from a test script). + + ' + type: boolean + - in: query + name: highlight_full_fields + schema: + description: List of fields which should be highlighted fully without snippeting + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/MultiSearchSearchesParameter' + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/MultiSearchResult' + description: Search results + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + summary: send multiple search requests in a single HTTP request + tags: + - documents + /nl_search_models: + get: + description: Retrieve all NL search models. + operationId: retrieveAllNLSearchModels + responses: + '200': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/NLSearchModelSchema' + type: array + description: List of all NL search models + summary: List all NL search models + tags: + - nl_search_models + post: + description: Create a new NL search model. + operationId: createNLSearchModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelCreateSchema' + description: The NL search model to be created + required: true + responses: + '201': + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + description: NL search model successfully created + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + summary: Create a NL search model + tags: + - nl_search_models + /nl_search_models/{modelId}: + delete: + description: Delete a specific NL search model by its ID. + operationId: deleteNLSearchModel + parameters: + - description: The ID of the NL search model to delete + in: path + name: modelId + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelDeleteSchema' + description: NL search model successfully deleted + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: NL search model not found + summary: Delete a NL search model + tags: + - nl_search_models + get: + description: Retrieve a specific NL search model by its ID. + operationId: retrieveNLSearchModel + parameters: + - description: The ID of the NL search model to retrieve + in: path + name: modelId + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + description: NL search model fetched + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: NL search model not found + summary: Retrieve a NL search model + tags: + - nl_search_models + put: + description: Update an existing NL search model. + operationId: updateNLSearchModel + parameters: + - description: The ID of the NL search model to update + in: path + name: modelId + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelUpdateSchema' + description: The NL search model fields to update + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + description: NL search model successfully updated + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: NL search model not found + summary: Update a NL search model + tags: + - nl_search_models + /operations/cache/clear: + post: + description: Clear the cached responses of search requests that are sent with + `use_cache` parameter in the LRU cache. + operationId: clearCache + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + description: Clear cache succeeded. + summary: Clear the cached responses of search requests in the LRU cache. + tags: + - operations + /operations/db/compact: + post: + description: Typesense uses RocksDB to store your documents on the disk. If + you do frequent writes or updates, you could benefit from running a compaction + of the underlying RocksDB database. This could reduce the size of the database + and decrease read latency. While the database will not block during this operation, + we recommend running it during off-peak hours. + operationId: compactDb + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + description: Compacting the on-disk database succeeded. + summary: Compacting the on-disk database + tags: + - operations + /operations/schema_changes: + get: + 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': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/SchemaChangeStatus' + type: array + description: List of schema changes in progress + summary: Get the status of in-progress schema change operations + tags: + - operations + /operations/snapshot: + post: + 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: + - description: The directory on the server where the snapshot should be saved. + in: query + name: snapshot_path + required: true + schema: + type: string + responses: + '201': + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + description: Snapshot is created. + summary: Creates a point-in-time snapshot of a Typesense node's state and data + in the specified directory. + tags: + - operations + /operations/vote: + post: + 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': + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + description: Re-election is performed. + summary: Triggers a follower node to initiate the raft voting process, which + triggers leader re-election. + tags: + - operations + /presets: + get: + description: Retrieve the details of all presets + operationId: retrieveAllPresets + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/PresetsRetrieveSchema' + description: Presets fetched. + summary: Retrieves all presets. + tags: + - presets + /presets/{presetId}: + delete: + description: Permanently deletes a preset, given it's name. + operationId: deletePreset + parameters: + - description: The ID of the preset to delete. + example: listing_view + in: path + name: presetId + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/PresetDeleteSchema' + description: Preset deleted. + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Preset not found. + summary: Delete a preset. + tags: + - presets + get: + description: Retrieve the details of a preset, given it's name. + operationId: retrievePreset + parameters: + - description: The ID of the preset to retrieve. + example: listing_view + in: path + name: presetId + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/PresetSchema' + description: Preset fetched. + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Preset not found. + summary: Retrieves a preset. + tags: + - presets + put: + description: Create or update an existing preset. + operationId: upsertPreset + parameters: + - description: The name of the preset set to upsert. + example: listing_view + in: path + name: presetId + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PresetUpsertSchema' + description: The stopwords set to upsert. + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/PresetSchema' + description: Preset successfully upserted. + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + summary: Upserts a preset. + tags: + - presets + /stats.json: + get: + description: Retrieve the stats about API endpoints. + operationId: retrieveAPIStats + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/APIStatsResponse' + description: Stats fetched. + summary: Get stats about API endpoints. + tags: + - operations + /stemming/dictionaries: + get: + description: Retrieve a list of all available stemming dictionaries. + operationId: listStemmingDictionaries + responses: + '200': + content: + application/json: + schema: + properties: + dictionaries: + example: + - irregular-plurals + - company-terms + items: + type: string + type: array + type: object + description: List of all dictionaries + summary: List all stemming dictionaries + tags: + - stemming + /stemming/dictionaries/import: + post: + description: Upload a JSONL file containing word mappings to create or update + a stemming dictionary. + operationId: importStemmingDictionary + parameters: + - description: The ID to assign to the dictionary + example: irregular-plurals + in: query + name: id + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + example: '{"word": "people", "root": "person"} + + {"word": "children", "root": "child"} + + ' + type: string + description: The JSONL file containing word mappings + required: true + responses: + '200': + content: + application/octet-stream: + schema: + example: '{"word": "people", "root": "person"} {"word": "children", + "root": "child"} + + ' + type: string + description: Dictionary successfully imported + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + summary: Import a stemming dictionary + tags: + - stemming + /stemming/dictionaries/{dictionaryId}: + get: + description: Fetch details of a specific stemming dictionary. + operationId: getStemmingDictionary + parameters: + - description: The ID of the dictionary to retrieve + example: irregular-plurals + in: path + name: dictionaryId + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/StemmingDictionary' + description: Stemming dictionary details + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Dictionary not found + summary: Retrieve a stemming dictionary + tags: + - stemming + /stopwords: + get: + description: Retrieve the details of all stopwords sets + operationId: retrieveStopwordsSets + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetsRetrieveAllSchema' + description: Stopwords sets fetched. + summary: Retrieves all stopwords sets. + tags: + - stopwords + /stopwords/{setId}: + delete: + description: Permanently deletes a stopwords set, given it's name. + operationId: deleteStopwordsSet + parameters: + - description: The ID of the stopwords set to delete. + example: countries + in: path + name: setId + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + example: '{"id": "countries"} + + ' + properties: + id: + type: string + required: + - id + type: object + description: Stopwords set rule deleted. + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Stopwords set not found. + summary: Delete a stopwords set. + tags: + - stopwords + get: + description: Retrieve the details of a stopwords set, given it's name. + operationId: retrieveStopwordsSet + parameters: + - description: The ID of the stopwords set to retrieve. + example: countries + in: path + name: setId + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetRetrieveSchema' + description: Stopwords set fetched. + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Stopwords set not found. + summary: Retrieves a stopwords set. + tags: + - stopwords + put: + 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: + - description: The ID of the stopwords set to upsert. + example: countries + in: path + name: setId + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetUpsertSchema' + description: The stopwords set to upsert. + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetSchema' + description: Stopwords set successfully upserted. + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details. + summary: Upserts a stopwords set. + tags: + - stopwords + /synonym_sets: + get: + description: Retrieve all synonym sets + operationId: retrieveSynonymSets + responses: + '200': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/SynonymSetSchema' + type: array + description: List of all synonym sets + summary: List all synonym sets + tags: + - synonyms + /synonym_sets/{synonymSetName}: + delete: + description: Delete a specific synonym set by its name + operationId: deleteSynonymSet + parameters: + - description: The name of the synonym set to delete + in: path + name: synonymSetName + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymSetDeleteSchema' + description: Synonym set successfully deleted + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Synonym set not found + summary: Delete a synonym set + tags: + - synonyms + get: + description: Retrieve a specific synonym set by its name + operationId: retrieveSynonymSet + parameters: + - description: The name of the synonym set to retrieve + in: path + name: synonymSetName + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymSetRetrieveSchema' + description: Synonym set fetched + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Synonym set not found + summary: Retrieve a synonym set + tags: + - synonyms + put: + description: Create or update a synonym set with the given name + operationId: upsertSynonymSet + parameters: + - description: The name of the synonym set to create/update + in: path + name: synonymSetName + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymSetCreateSchema' + description: The synonym set to be created/updated + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymSetSchema' + description: Synonym set successfully created/updated + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + summary: Create or update a synonym set + tags: + - synonyms + /synonym_sets/{synonymSetName}/items: + get: + description: Retrieve all synonym items in a set + operationId: retrieveSynonymSetItems + parameters: + - description: The name of the synonym set to retrieve items for + in: path + name: synonymSetName + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/SynonymItemSchema' + type: array + description: List of synonym items + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Synonym set not found + summary: List items in a synonym set + tags: + - synonyms + /synonym_sets/{synonymSetName}/items/{itemId}: + delete: + description: Delete a specific synonym item by its id + operationId: deleteSynonymSetItem + parameters: + - description: The name of the synonym set + in: path + name: synonymSetName + required: true + schema: + type: string + - description: The id of the synonym item to delete + in: path + name: itemId + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymItemDeleteSchema' + description: Synonym item successfully deleted + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Synonym item not found + summary: Delete a synonym set item + tags: + - synonyms + get: + description: Retrieve a specific synonym item by its id + operationId: retrieveSynonymSetItem + parameters: + - description: The name of the synonym set + in: path + name: synonymSetName + required: true + schema: + type: string + - description: The id of the synonym item to retrieve + in: path + name: itemId + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymItemSchema' + description: Synonym item fetched + '404': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Synonym item not found + summary: Retrieve a synonym set item + tags: + - synonyms + put: + description: Create or update a synonym set item with the given id + operationId: upsertSynonymSetItem + parameters: + - description: The name of the synonym set + in: path + name: synonymSetName + required: true + schema: + type: string + - description: The id of the synonym item to upsert + in: path + name: itemId + required: true + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymItemSchema' + description: The synonym item to be created/updated + required: true + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymItemSchema' + description: Synonym item successfully created/updated + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + summary: Create or update a synonym set item + tags: + - synonyms +security: +- api_key_header: [] +servers: +- description: Typesense Server + url: '{protocol}://{hostname}:{port}' + variables: + hostname: + default: localhost + description: The hostname of your Typesense server + port: + default: '8108' + description: The port of your Typesense server + protocol: + default: http + description: The protocol of your Typesense server +tags: +- description: A collection is defined by a schema + externalDocs: + description: Find out more + url: https://typesense.org/api/#create-collection + name: collections +- 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: documents +- 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: analytics +- 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: keys +- description: Debugging information + name: debug +- description: Manage Typesense cluster + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/cluster-operations.html + name: operations +- description: Manage stopwords sets + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stopwords.html + name: stopwords +- description: Store and reference search parameters + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/search.html#presets + name: presets +- description: Conversational Search (RAG) + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/conversational-search-rag.html + name: conversations +- description: Manage synonyms + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/synonyms.html + name: synonyms +- description: Manage curation sets + name: curation_sets +- description: Manage stemming dictionaries + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stemming.html + name: stemming +- description: Manage NL search models + externalDocs: + description: Find out more + url: https://typesense.org/docs/29.0/api/natural-language-search.html + name: nl_search_models From 5501d66b888f0c703e37a45d6f1f267eea528a4c Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Mon, 1 Dec 2025 21:44:14 +0700 Subject: [PATCH 03/21] custom openapi-generator-template --- .../Typesense/Models/MultiSearchResult.swift | 6 +- .../Models/MultiSearchResultItem.swift | 8 +- .../Typesense/Models/SearchGroupedHit.swift | 6 +- Sources/Typesense/Models/SearchResult.swift | 8 +- .../Typesense/Models/SearchResultHit.swift | 6 +- Tasks/AddVendorAttributes.swift | 22 +- Tasks/VendorAttributes.swift | 2 +- Tasks/main.swift | 1 + openapi-generator-template/model.mustache | 33 + .../modelArray.mustache | 1 + openapi-generator-template/modelEnum.mustache | 7 + .../modelInlineEnumDeclaration.mustache | 7 + .../modelObject.mustache | 137 ++ .../modelOneOf.mustache | 43 + preprocessed_openapi.yml | 1259 ++++++++--------- 15 files changed, 885 insertions(+), 661 deletions(-) create mode 100644 openapi-generator-template/model.mustache create mode 100644 openapi-generator-template/modelArray.mustache create mode 100644 openapi-generator-template/modelEnum.mustache create mode 100644 openapi-generator-template/modelInlineEnumDeclaration.mustache create mode 100644 openapi-generator-template/modelObject.mustache create mode 100644 openapi-generator-template/modelOneOf.mustache diff --git a/Sources/Typesense/Models/MultiSearchResult.swift b/Sources/Typesense/Models/MultiSearchResult.swift index 7a30625..f2c9fc1 100644 --- a/Sources/Typesense/Models/MultiSearchResult.swift +++ b/Sources/Typesense/Models/MultiSearchResult.swift @@ -10,12 +10,12 @@ import Foundation import AnyCodable #endif -public struct MultiSearchResult: Codable { +public struct MultiSearchResult: Codable { public var conversation: SearchResultConversation? - public var results: [MultiSearchResultItem] + public var results: [MultiSearchResultItem]? - public init(conversation: SearchResultConversation? = nil, results: [MultiSearchResultItem]) { + public init(conversation: SearchResultConversation? = nil, results: [MultiSearchResultItem]?) { self.conversation = conversation self.results = results } diff --git a/Sources/Typesense/Models/MultiSearchResultItem.swift b/Sources/Typesense/Models/MultiSearchResultItem.swift index af71d04..85d78b4 100644 --- a/Sources/Typesense/Models/MultiSearchResultItem.swift +++ b/Sources/Typesense/Models/MultiSearchResultItem.swift @@ -10,16 +10,16 @@ import Foundation import AnyCodable #endif -public struct MultiSearchResultItem: Codable { +public struct MultiSearchResultItem: Codable { public var conversation: SearchResultConversation? public var facetCounts: [FacetCounts]? /** The number of documents found */ public var found: Int? public var foundDocs: Int? - public var groupedHits: [SearchGroupedHit]? + public var groupedHits: [SearchGroupedHit]? /** The documents that matched the search query */ - public var hits: [SearchResultHit]? + public var hits: [SearchResultHit]? /** Custom JSON object that can be returned in the search response */ public var metadata: [String: AnyCodable]? /** The total number of documents in the collection */ @@ -38,7 +38,7 @@ public struct MultiSearchResultItem: Codable { /** Error description */ public var error: String? - public init(conversation: SearchResultConversation? = nil, facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, metadata: [String: AnyCodable]? = nil, outOf: Int? = nil, page: Int? = nil, requestParams: SearchRequestParams? = nil, searchCutoff: Bool? = nil, searchTimeMs: Int? = nil, unionRequestParams: [SearchRequestParams]? = nil, code: Int64? = nil, error: String? = nil) { + public init(conversation: SearchResultConversation? = nil, facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, metadata: [String: AnyCodable]? = nil, outOf: Int? = nil, page: Int? = nil, requestParams: SearchRequestParams? = nil, searchCutoff: Bool? = nil, searchTimeMs: Int? = nil, unionRequestParams: [SearchRequestParams]? = nil, code: Int64? = nil, error: String? = nil) { self.conversation = conversation self.facetCounts = facetCounts self.found = found diff --git a/Sources/Typesense/Models/SearchGroupedHit.swift b/Sources/Typesense/Models/SearchGroupedHit.swift index 20f2a1b..ac2ec9e 100644 --- a/Sources/Typesense/Models/SearchGroupedHit.swift +++ b/Sources/Typesense/Models/SearchGroupedHit.swift @@ -10,14 +10,14 @@ import Foundation import AnyCodable #endif -public struct SearchGroupedHit: Codable { +public struct SearchGroupedHit: Codable { public var found: Int? public var groupKey: [AnyCodable] /** The documents that matched the search query */ - public var hits: [SearchResultHit] + public var hits: [SearchResultHit]? - public init(found: Int? = nil, groupKey: [AnyCodable], hits: [SearchResultHit]) { + public init(found: Int? = nil, groupKey: [AnyCodable], hits: [SearchResultHit]?) { self.found = found self.groupKey = groupKey self.hits = hits diff --git a/Sources/Typesense/Models/SearchResult.swift b/Sources/Typesense/Models/SearchResult.swift index bcb00ab..7711510 100644 --- a/Sources/Typesense/Models/SearchResult.swift +++ b/Sources/Typesense/Models/SearchResult.swift @@ -10,16 +10,16 @@ import Foundation import AnyCodable #endif -public struct SearchResult: Codable { +public struct SearchResult: Codable { public var conversation: SearchResultConversation? public var facetCounts: [FacetCounts]? /** The number of documents found */ public var found: Int? public var foundDocs: Int? - public var groupedHits: [SearchGroupedHit]? + public var groupedHits: [SearchGroupedHit]? /** The documents that matched the search query */ - public var hits: [SearchResultHit]? + public var hits: [SearchResultHit]? /** Custom JSON object that can be returned in the search response */ public var metadata: [String: AnyCodable]? /** The total number of documents in the collection */ @@ -34,7 +34,7 @@ public struct SearchResult: Codable { /** Returned only for union query response. */ public var unionRequestParams: [SearchRequestParams]? - public init(conversation: SearchResultConversation? = nil, facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, metadata: [String: AnyCodable]? = nil, outOf: Int? = nil, page: Int? = nil, requestParams: SearchRequestParams? = nil, searchCutoff: Bool? = nil, searchTimeMs: Int? = nil, unionRequestParams: [SearchRequestParams]? = nil) { + public init(conversation: SearchResultConversation? = nil, facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, metadata: [String: AnyCodable]? = nil, outOf: Int? = nil, page: Int? = nil, requestParams: SearchRequestParams? = nil, searchCutoff: Bool? = nil, searchTimeMs: Int? = nil, unionRequestParams: [SearchRequestParams]? = nil) { self.conversation = conversation self.facetCounts = facetCounts self.found = found diff --git a/Sources/Typesense/Models/SearchResultHit.swift b/Sources/Typesense/Models/SearchResultHit.swift index 4ac7486..6db2e34 100644 --- a/Sources/Typesense/Models/SearchResultHit.swift +++ b/Sources/Typesense/Models/SearchResultHit.swift @@ -10,10 +10,10 @@ import Foundation import AnyCodable #endif -public struct SearchResultHit: Codable { +public struct SearchResultHit: Codable { /** Can be any key-value pair */ - public var document: [String: AnyCodable]? + public var document: T? /** Can be any key-value pair */ public var geoDistanceMeters: [String: Int]? /** Highlighted version of the matching document */ @@ -28,7 +28,7 @@ public struct SearchResultHit: Codable { /** Distance between the query vector and matching document's vector value */ public var vectorDistance: Float? - public init(document: [String: AnyCodable]? = nil, geoDistanceMeters: [String: Int]? = nil, highlight: [String: AnyCodable]? = nil, highlights: [SearchHighlight]? = nil, hybridSearchInfo: SearchResultHitHybridSearchInfo? = nil, searchIndex: Int? = nil, textMatch: Int64? = nil, textMatchInfo: SearchResultHitTextMatchInfo? = nil, vectorDistance: Float? = nil) { + public init(document: T? = nil, geoDistanceMeters: [String: Int]? = nil, highlight: [String: AnyCodable]? = nil, highlights: [SearchHighlight]? = nil, hybridSearchInfo: SearchResultHitHybridSearchInfo? = nil, searchIndex: Int? = nil, textMatch: Int64? = nil, textMatchInfo: SearchResultHitTextMatchInfo? = nil, vectorDistance: Float? = nil) { self.document = document self.geoDistanceMeters = geoDistanceMeters self.highlight = highlight diff --git a/Tasks/AddVendorAttributes.swift b/Tasks/AddVendorAttributes.swift index 4936798..f948746 100644 --- a/Tasks/AddVendorAttributes.swift +++ b/Tasks/AddVendorAttributes.swift @@ -5,35 +5,35 @@ func addVendorAttributes(_ doc: inout [String: Any]) throws { // Generic Parameters // Setting "x-swift-generic-parameter" try attrs.schemaGenericParameter([ - ("SearchResult", "T"), - ("SearchGroupedHit", "T"), - ("SearchResultHit", "T"), - ("MultiSearchResult", "T"), - ("MultiSearchResultItem", "T"), + ("SearchResult", "T: Codable"), + ("SearchGroupedHit", "T: Codable"), + ("SearchResultHit", "T: Codable"), + ("MultiSearchResult", "T: Codable"), + ("MultiSearchResultItem", "T: Codable"), ]) - // Field Type Overrides + // Field Type Overrides "x-swift-type" try attrs.schemaFieldTypeOverrides( schema: "SearchResult", overrides: [ - ("hits", "[SearchResultHit]"), - ("grouped_hits", "[SearchGroupedHit]"), + ("hits", "[SearchResultHit]?"), + ("grouped_hits", "[SearchGroupedHit]?"), ] ) try attrs.schemaFieldTypeOverrides( schema: "SearchGroupedHit", - overrides: [("hits", "[SearchResultHit]")] + overrides: [("hits", "[SearchResultHit]?")] ) try attrs.schemaFieldTypeOverrides( schema: "SearchResultHit", - overrides: [("document", "T")] + overrides: [("document", "T?")] ) try attrs.schemaFieldTypeOverrides( schema: "MultiSearchResult", - overrides: [("results", "[MultiSearchResultItem]")] + overrides: [("results", "[MultiSearchResultItem]?")] ) // Save changes back to the inout parameter diff --git a/Tasks/VendorAttributes.swift b/Tasks/VendorAttributes.swift index d5bc6ab..df5be9d 100644 --- a/Tasks/VendorAttributes.swift +++ b/Tasks/VendorAttributes.swift @@ -59,7 +59,7 @@ class VendorAttributes { existingProp["x-swift-type"] = swiftType properties[field] = existingProp } else { - // Create new if missing (matches Rust 'None' branch) + // Create new if missing let newProp: [String: Any] = ["x-swift-type": swiftType] properties[field] = newProp } diff --git a/Tasks/main.swift b/Tasks/main.swift index 87d7e34..d585630 100644 --- a/Tasks/main.swift +++ b/Tasks/main.swift @@ -33,6 +33,7 @@ struct CodeGen: ParsableCommand { "-v", volumeMount, "openapitools/openapi-generator-cli", "generate", + "-t", "/local/openapi-generator-template", "-i", "/local/\(outputPreprocessedFile)", "-g", "swift5", "-o", "/local/output", diff --git a/openapi-generator-template/model.mustache b/openapi-generator-template/model.mustache new file mode 100644 index 0000000..4a77dc7 --- /dev/null +++ b/openapi-generator-template/model.mustache @@ -0,0 +1,33 @@ +{{#models}}{{#model}}// +// {{classname}}.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif{{#useVapor}} +import Vapor{{/useVapor}} +{{#swiftUseApiNamespace}} + +@available(*, deprecated, renamed: "{{projectName}}API.{{classname}}") +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} typealias {{classname}} = {{projectName}}API.{{classname}} + +extension {{projectName}}API { +{{/swiftUseApiNamespace}} +{{#description}} + +/** {{.}} */{{/description}}{{#isDeprecated}} +@available(*, deprecated, message: "This schema is deprecated."){{/isDeprecated}}{{#vendorExtensions.x-is-one-of-interface}} +{{> modelOneOf}}{{/vendorExtensions.x-is-one-of-interface}}{{^vendorExtensions.x-is-one-of-interface}}{{#isArray}} +{{> modelArray}}{{/isArray}}{{^isArray}}{{#isEnum}} +{{> modelEnum}}{{/isEnum}}{{^isEnum}} +{{> modelObject}}{{/isEnum}}{{/isArray}}{{/vendorExtensions.x-is-one-of-interface}}{{/model}}{{/models}} +{{#swiftUseApiNamespace}} +} +{{/swiftUseApiNamespace}}{{#models}}{{#model}}{{#vendorExtensions.x-swift-identifiable}} +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension {{#swiftUseApiNamespace}}{{projectName}}API.{{/swiftUseApiNamespace}}{{{classname}}}: Identifiable {} +{{/vendorExtensions.x-swift-identifiable}}{{/model}}{{/models}} \ No newline at end of file diff --git a/openapi-generator-template/modelArray.mustache b/openapi-generator-template/modelArray.mustache new file mode 100644 index 0000000..536c5e9 --- /dev/null +++ b/openapi-generator-template/modelArray.mustache @@ -0,0 +1 @@ +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} typealias {{classname}} = {{parent}} \ No newline at end of file diff --git a/openapi-generator-template/modelEnum.mustache b/openapi-generator-template/modelEnum.mustache new file mode 100644 index 0000000..d9eddc7 --- /dev/null +++ b/openapi-generator-template/modelEnum.mustache @@ -0,0 +1,7 @@ +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{classname}}: {{dataType}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{^isString}}{{^isInteger}}{{^isFloat}}{{^isDouble}}{{/isDouble}}{{/isFloat}}{{/isInteger}}{{/isString}}{{/useVapor}}, CaseIterable{{#enumUnknownDefaultCase}}{{#isInteger}}, CaseIterableDefaultsLast{{/isInteger}}{{#isFloat}}, CaseIterableDefaultsLast{{/isFloat}}{{#isDouble}}, CaseIterableDefaultsLast{{/isDouble}}{{#isString}}, CaseIterableDefaultsLast{{/isString}}{{/enumUnknownDefaultCase}} { +{{#allowableValues}} +{{#enumVars}} + case {{{name}}} = {{{value}}} +{{/enumVars}} +{{/allowableValues}} +} \ No newline at end of file diff --git a/openapi-generator-template/modelInlineEnumDeclaration.mustache b/openapi-generator-template/modelInlineEnumDeclaration.mustache new file mode 100644 index 0000000..16dd7b1 --- /dev/null +++ b/openapi-generator-template/modelInlineEnumDeclaration.mustache @@ -0,0 +1,7 @@ + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{enumName}}: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{^isContainer}}{{^isString}}{{^isInteger}}{{^isFloat}}{{^isDouble}}{{/isDouble}}{{/isFloat}}{{/isInteger}}{{/isString}}{{/isContainer}}{{/useVapor}}, CaseIterable{{#enumUnknownDefaultCase}}{{#isInteger}}, CaseIterableDefaultsLast{{/isInteger}}{{#isFloat}}, CaseIterableDefaultsLast{{/isFloat}}{{#isDouble}}, CaseIterableDefaultsLast{{/isDouble}}{{#isString}}, CaseIterableDefaultsLast{{/isString}}{{#isContainer}}, CaseIterableDefaultsLast{{/isContainer}}{{/enumUnknownDefaultCase}} { + {{#allowableValues}} + {{#enumVars}} + case {{{name}}} = {{{value}}} + {{/enumVars}} + {{/allowableValues}} + } \ No newline at end of file diff --git a/openapi-generator-template/modelObject.mustache b/openapi-generator-template/modelObject.mustache new file mode 100644 index 0000000..f340b87 --- /dev/null +++ b/openapi-generator-template/modelObject.mustache @@ -0,0 +1,137 @@ +{{^objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#useClasses}}final class{{/useClasses}}{{^useClasses}}struct{{/useClasses}} {{{classname}}}{{#vendorExtensions.x-swift-generic-parameter}}<{{.}}>{{/vendorExtensions.x-swift-generic-parameter}}: {{#useVapor}}Content{{/useVapor}}{{^useVapor}}Codable{{/useVapor}}{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}} { +{{/objcCompatible}}{{#objcCompatible}}@objcMembers {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} class {{classname}}: NSObject, Codable { +{{/objcCompatible}} + +{{#allVars}} +{{#isEnum}} +{{> modelInlineEnumDeclaration}} +{{/isEnum}} +{{/allVars}} +{{#allVars}} +{{#validatable}} +{{#hasValidation}} +{{#isString}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static let {{{name}}}Rule = StringRule(minLength: {{#minLength}}{{{.}}}{{/minLength}}{{^minLength}}nil{{/minLength}}, maxLength: {{#maxLength}}{{{.}}}{{/maxLength}}{{^maxLength}}nil{{/maxLength}}, pattern: {{#pattern}}"{{{.}}}"{{/pattern}}{{^pattern}}nil{{/pattern}}) +{{/isString}} +{{#isNumeric}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static let {{{name}}}Rule = NumericRule<{{{dataType}}}>(minimum: {{#minimum}}{{{.}}}{{/minimum}}{{^minimum}}nil{{/minimum}}, exclusiveMinimum: {{#exclusiveMinimum}}true{{/exclusiveMinimum}}{{^exclusiveMinimum}}false{{/exclusiveMinimum}}, maximum: {{#maximum}}{{{.}}}{{/maximum}}{{^maximum}}nil{{/maximum}}, exclusiveMaximum: {{#exclusiveMaximum}}true{{/exclusiveMaximum}}{{^exclusiveMaximum}}false{{/exclusiveMaximum}}, multipleOf: {{#multipleOf}}{{{.}}}{{/multipleOf}}{{^multipleOf}}nil{{/multipleOf}}) +{{/isNumeric}} +{{#isArray}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static let {{{name}}}Rule = ArrayRule(minItems: {{#minItems}}{{{.}}}{{/minItems}}{{^minItems}}nil{{/minItems}}, maxItems: {{#maxItems}}{{{.}}}{{/maxItems}}{{^maxItems}}nil{{/maxItems}}, uniqueItems: {{#uniqueItems}}true{{/uniqueItems}}{{^uniqueItems}}false{{/uniqueItems}}) +{{/isArray}} +{{/hasValidation}} +{{/validatable}} +{{/allVars}} +{{#allVars}} +{{#isEnum}} + {{#description}}/** {{{.}}} */ + {{/description}}{{#deprecated}}@available(*, deprecated, message: "This property is deprecated.") + {{/deprecated}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var {{{name}}}: {{#vendorExtensions.x-swift-type}}{{{.}}}{{/vendorExtensions.x-swift-type}}{{^vendorExtensions.x-swift-type}}{{#vendorExtensions.x-null-encodable}}NullEncodable<{{{datatypeWithEnum}}}>{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{/vendorExtensions.x-null-encodable}}{{/vendorExtensions.x-swift-type}}{{#defaultValue}} = {{#vendorExtensions.x-null-encodable}}{{{vendorExtensions.x-null-encodable-default-value}}}{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{.}}}{{/vendorExtensions.x-null-encodable}}{{/defaultValue}} +{{/isEnum}} +{{^isEnum}} + {{#description}}/** {{{.}}} */ + {{/description}}{{#deprecated}}@available(*, deprecated, message: "This property is deprecated.") + {{/deprecated}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var {{{name}}}: {{#vendorExtensions.x-swift-type}}{{{.}}}{{/vendorExtensions.x-swift-type}}{{^vendorExtensions.x-swift-type}}{{#vendorExtensions.x-null-encodable}}NullEncodable<{{{datatype}}}>{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{datatype}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{/vendorExtensions.x-null-encodable}}{{/vendorExtensions.x-swift-type}}{{#defaultValue}} = {{#vendorExtensions.x-null-encodable}}{{{vendorExtensions.x-null-encodable-default-value}}}{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{.}}}{{/vendorExtensions.x-null-encodable}}{{/defaultValue}} + {{#objcCompatible}} + {{#vendorExtensions.x-swift-optional-scalar}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var {{{name}}}Num: NSNumber? { + get { + {{^vendorExtensions.x-null-encodable}} + return {{{name}}} as NSNumber? + {{/vendorExtensions.x-null-encodable}} + {{#vendorExtensions.x-null-encodable}} + if case .encodeValue(let value) = {{name}} { + return value as NSNumber? + } else { + return nil + } + {{/vendorExtensions.x-null-encodable}} + } + } + {{/vendorExtensions.x-swift-optional-scalar}} + {{/objcCompatible}} +{{/isEnum}} +{{/allVars}} +{{#hasVars}} + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init({{#allVars}}{{{name}}}: {{#vendorExtensions.x-swift-type}}{{{.}}}{{/vendorExtensions.x-swift-type}}{{^vendorExtensions.x-swift-type}}{{#vendorExtensions.x-null-encodable}}NullEncodable<{{{datatypeWithEnum}}}>{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{/vendorExtensions.x-null-encodable}}{{/vendorExtensions.x-swift-type}}{{#defaultValue}} = {{#vendorExtensions.x-null-encodable}}{{{vendorExtensions.x-null-encodable-default-value}}}{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{.}}}{{/vendorExtensions.x-null-encodable}}{{/defaultValue}}{{^defaultValue}}{{^required}} = {{#vendorExtensions.x-null-encodable}}.encodeNull{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}nil{{/vendorExtensions.x-null-encodable}}{{/required}}{{/defaultValue}}{{^-last}}, {{/-last}}{{/allVars}}) { + {{#allVars}} + self.{{{name}}} = {{{name}}} + {{/allVars}} + } +{{/hasVars}} + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum CodingKeys: {{#hasVars}}String, {{/hasVars}}CodingKey, CaseIterable { + {{#allVars}} + case {{{name}}}{{#vendorExtensions.x-codegen-escaped-property-name}} = "{{{baseName}}}"{{/vendorExtensions.x-codegen-escaped-property-name}} + {{/allVars}} + }{{#generateModelAdditionalProperties}}{{#additionalPropertiesType}} + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var additionalProperties: [String: {{{additionalPropertiesType}}}] = [:] + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} subscript(key: String) -> {{{additionalPropertiesType}}}? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + }{{/additionalPropertiesType}}{{/generateModelAdditionalProperties}} + + // Encodable protocol methods + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + {{#allVars}} + {{#vendorExtensions.x-null-encodable}} + switch {{{name}}} { + case .encodeNothing: break + case .encodeNull, .encodeValue: try container.encode({{{name}}}, forKey: .{{{name}}}) + } + {{/vendorExtensions.x-null-encodable}} + {{^vendorExtensions.x-null-encodable}} + try container.encode{{^required}}IfPresent{{/required}}({{{name}}}, forKey: .{{{name}}}) + {{/vendorExtensions.x-null-encodable}} + {{/allVars}} + {{#generateModelAdditionalProperties}} + {{#additionalPropertiesType}} + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + {{/additionalPropertiesType}} + {{/generateModelAdditionalProperties}} + }{{#generateModelAdditionalProperties}}{{#additionalPropertiesType}} + + // Decodable protocol methods + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}}{{#objcCompatible}} required{{/objcCompatible}} init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + {{#allVars}} + {{{name}}} = try container.decode{{#required}}{{#isNullable}}IfPresent{{/isNullable}}{{/required}}{{^required}}IfPresent{{/required}}({{{datatypeWithEnum}}}.self, forKey: .{{{name}}}) + {{/allVars}} + var nonAdditionalPropertyKeys = Set() + {{#allVars}} + nonAdditionalPropertyKeys.insert("{{{baseName}}}") + {{/allVars}} + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap({{{additionalPropertiesType}}}.self, excludedKeys: nonAdditionalPropertyKeys) + }{{/additionalPropertiesType}}{{/generateModelAdditionalProperties}}{{^objcCompatible}}{{#useClasses}}{{#vendorExtensions.x-swift-hashable}} + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func == (lhs: {{classname}}, rhs: {{classname}}) -> Bool { + {{#allVars}} + lhs.{{{name}}} == rhs.{{{name}}}{{^-last}} &&{{/-last}} + {{/allVars}} + {{#generateModelAdditionalProperties}}{{#additionalPropertiesType}}{{#hasVars}}&& {{/hasVars}}lhs.additionalProperties == rhs.additionalProperties{{/additionalPropertiesType}}{{/generateModelAdditionalProperties}} + } + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func hash(into hasher: inout Hasher) { + {{#allVars}} + hasher.combine({{{name}}}{{^vendorExtensions.x-null-encodable}}{{^required}}?{{/required}}{{/vendorExtensions.x-null-encodable}}.hashValue) + {{/allVars}} + {{#generateModelAdditionalProperties}}{{#additionalPropertiesType}}hasher.combine(additionalProperties.hashValue){{/additionalPropertiesType}}{{/generateModelAdditionalProperties}} + }{{/vendorExtensions.x-swift-hashable}}{{/useClasses}}{{/objcCompatible}} +} diff --git a/openapi-generator-template/modelOneOf.mustache b/openapi-generator-template/modelOneOf.mustache new file mode 100644 index 0000000..d726876 --- /dev/null +++ b/openapi-generator-template/modelOneOf.mustache @@ -0,0 +1,43 @@ +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{classname}}: {{#useVapor}}Content{{/useVapor}}{{^useVapor}}Codable{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}}{{/useVapor}} { + {{#oneOf}} + case type{{.}}({{.}}) + {{/oneOf}} + {{#oneOfUnknownDefaultCase}} + case unknownDefaultOpenApi + {{/oneOfUnknownDefaultCase}} + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + {{#oneOf}} + case .type{{.}}(let value): + try container.encode(value) + {{/oneOf}} + {{#oneOfUnknownDefaultCase}} + case unknownDefaultOpenApi(let type): + try container.encodeNil() + {{/oneOfUnknownDefaultCase}} + } + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + {{#oneOf}} + {{#-first}} + if let value = try? container.decode({{.}}.self) { + {{/-first}} + {{^-first}} + } else if let value = try? container.decode({{.}}.self) { + {{/-first}} + self = .type{{.}}(value) + {{/oneOf}} + } else { + {{#oneOfUnknownDefaultCase}} + self = .unknownDefaultOpenApi + {{/oneOfUnknownDefaultCase}} + {{^oneOfUnknownDefaultCase}} + throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of {{classname}}")) + {{/oneOfUnknownDefaultCase}} + } + } +} diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml index b60c68c..f37db27 100644 --- a/preprocessed_openapi.yml +++ b/preprocessed_openapi.yml @@ -381,7 +381,6 @@ components: - name - fields type: object - x-swift-builder: true CollectionUpdateSchema: properties: fields: @@ -885,7 +884,6 @@ components: - name - type type: object - x-swift-builder: true GetCollectionsParameters: properties: exclude_fields: @@ -956,7 +954,6 @@ components: request type: string type: object - x-swift-builder: true MultiSearchParameters: description: 'Parameters for the multi search API. @@ -1344,7 +1341,6 @@ components: ' type: string type: object - x-swift-builder: true MultiSearchResult: properties: conversation: @@ -1353,11 +1349,11 @@ components: items: $ref: '#/components/schemas/MultiSearchResultItem' type: array - x-swift-type: '[MultiSearchResultItem]' + x-swift-type: '[MultiSearchResultItem]?' required: - results type: object - x-swift-generic-parameter: + x-swift-generic-parameter: 'T: Codable' MultiSearchResultItem: allOf: - $ref: '#/components/schemas/SearchResult' @@ -1370,7 +1366,7 @@ components: description: Error description type: string type: object - x-swift-generic-parameter: D + x-swift-generic-parameter: 'T: Codable' MultiSearchSearchesParameter: properties: searches: @@ -1530,12 +1526,12 @@ components: items: $ref: '#/components/schemas/SearchResultHit' type: array - x-swift-type: '[SearchResultHit]' + x-swift-type: '[SearchResultHit]?' required: - group_key - hits type: object - x-swift-generic-parameter: D + x-swift-generic-parameter: 'T: Codable' SearchHighlight: properties: field: @@ -2001,7 +1997,6 @@ components: ' type: string type: object - x-swift-builder: true SearchRequestParams: properties: collection_name: @@ -2037,13 +2032,13 @@ components: items: $ref: '#/components/schemas/SearchGroupedHit' type: array - x-swift-type: '[SearchGroupedHit]?' + x-swift-type: '[SearchGroupedHit]?' hits: description: The documents that matched the search query items: $ref: '#/components/schemas/SearchResultHit' type: array - x-swift-type: '[SearchResultHit]?' + x-swift-type: '[SearchResultHit]?' metadata: additionalProperties: true description: Custom JSON object that can be returned in the search response @@ -2068,7 +2063,7 @@ components: $ref: '#/components/schemas/SearchRequestParams' type: array type: object - x-swift-generic-parameter: D + x-swift-generic-parameter: 'T: Codable' SearchResultConversation: properties: answer: @@ -2105,7 +2100,7 @@ components: type: object description: Can be any key-value pair type: object - x-swift-type: D? + x-swift-type: T? geo_distance_meters: additionalProperties: type: integer @@ -2160,7 +2155,7 @@ components: format: float type: number type: object - x-swift-generic-parameter: D + x-swift-generic-parameter: 'T: Codable' SearchSynonym: allOf: - $ref: '#/components/schemas/SearchSynonymSchema' @@ -2770,12 +2765,6 @@ paths: first. operationId: getCollections parameters: - - in: query - name: exclude_fields - schema: - description: Comma-separated list of fields from the collection to exclude - from the response - type: string - in: query name: offset schema: @@ -2788,6 +2777,12 @@ paths: ' type: integer + - in: query + name: exclude_fields + schema: + description: Comma-separated list of fields from the collection to exclude + from the response + type: string responses: '200': content: @@ -2941,10 +2936,6 @@ paths: required: true schema: type: string - - in: query - name: ignore_not_found - schema: - type: boolean - in: query name: batch_size schema: @@ -2952,6 +2943,10 @@ paths: 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 + - in: query + name: ignore_not_found + schema: + type: boolean - in: query name: truncate schema: @@ -3103,14 +3098,14 @@ paths: schema: type: string - in: query - name: include_fields + name: exclude_fields schema: - description: List of fields from the document to include in the search result + description: List of fields from the document to exclude in the search result type: string - in: query - name: exclude_fields + name: include_fields schema: - description: List of fields from the document to exclude in the search result + description: List of fields from the document to include in the search result type: string - in: query name: filter_by @@ -3157,6 +3152,10 @@ paths: required: true schema: type: string + - in: query + name: return_doc + schema: + type: boolean - in: query name: return_id schema: @@ -3164,6 +3163,10 @@ paths: import response to return the ingested document's id in the response, you can use the return_id parameter. type: boolean + - in: query + name: remote_embedding_batch_size + schema: + type: integer - in: query name: batch_size schema: @@ -3176,14 +3179,6 @@ paths: name: dirty_values schema: $ref: '#/components/schemas/DirtyValues' - - in: query - name: return_doc - schema: - type: boolean - - in: query - name: remote_embedding_batch_size - schema: - type: integer requestBody: content: application/octet-stream: @@ -3235,180 +3230,182 @@ paths: schema: type: string - in: query - name: group_missing_values - 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 - - in: query - name: min_len_2typo - 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 - - in: query - name: split_join_tokens + name: conversation_id 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`. + description: 'The Id of a previous conversation to continue, this tells + Typesense to include prior context when communicating with the LLM. ' type: string - in: query - name: max_facet_values + name: exclude_fields schema: - description: Maximum number of facet values to be returned. - type: integer + description: List of fields from the document to exclude in the search result + type: string - in: query - name: synonym_prefix + name: pre_segmented_query schema: - description: 'Allow synonym resolution on word prefixes in the query. Default: - false + 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 - in: query - name: cache_ttl + name: min_len_1typo 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. + 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 - in: query - name: hidden_hits + name: query_by_weights 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`. - - ' + 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 - in: query - name: exclude_fields + name: query_by schema: - description: List of fields from the document to exclude in the search result + description: A list of `string` fields that should be queried against. Multiple + fields are separated with a comma. type: string - in: query - name: conversation_id + name: include_fields schema: - description: 'The Id of a previous conversation to continue, this tells - Typesense to include prior context when communicating with the LLM. - - ' + description: List of fields from the document to include in the search result type: string - in: query - name: exhaustive_search + name: drop_tokens_threshold 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). + 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: boolean + type: integer - in: query - name: snippet_threshold + name: group_limit schema: - description: 'Field values under this length will be fully highlighted, - instead of showing a snippet of relevant portion. Default: 30 + 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 - in: query - name: query_by + name: max_extra_prefix schema: - description: A list of `string` fields that should be queried against. Multiple - fields are separated with a comma. - type: string + 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 - in: query - name: synonym_sets + name: sort_by schema: - description: List of synonym set names to associate with this search query - example: synonym_set_1,synonym_set_2 + 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` + example: num_employees:desc type: string - in: query - name: q + name: offset 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 + description: Identifies the starting point to return hits from a result + set. Can be used as an alternative to the page parameter. + type: integer - in: query name: page schema: description: Results from this specific page number would be fetched. type: integer - in: query - name: group_limit + name: exhaustive_search 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 + 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: integer + type: boolean - in: query - name: limit + name: facet_query schema: - description: 'Number of hits to fetch. Can be used as an alternative to - the per_page parameter. Default: 10. + 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 + - in: query + name: nl_query + schema: + description: Whether to use natural language processing to parse the query. + type: boolean + - in: query + name: search_cutoff_ms + 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 - in: query - name: pinned_hits + name: text_match_type 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`. + 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 + - in: query + name: highlight_end_tag + schema: + description: 'The end tag used for the highlighted snippets. Default: `` ' type: string - in: query - name: synonym_num_typos + name: enable_typos_for_alpha_numerical_tokens schema: - description: 'Allow synonym resolution on typo-corrected words in the query. - Default: 0 + description: 'Set this parameter to false to disable typos on alphanumerical + query tokens. Default: true. ' - type: integer + type: boolean - in: query - name: prefix + name: enable_typos_for_numerical_tokens 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 + default: true + description: 'Make Typesense disable typos for numerical tokens. + + ' + type: boolean - in: query - name: enable_overrides + name: group_missing_values schema: - default: false - 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 + 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 + - in: query + name: synonym_sets + schema: + description: List of synonym set names to associate with this search query + example: synonym_set_1,synonym_set_2 + type: string - in: query name: prioritize_num_matching_fields schema: @@ -3419,55 +3416,97 @@ paths: ' type: boolean - in: query - name: voice_query + name: highlight_full_fields schema: - description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. - + description: List of fields which should be highlighted fully without snippeting + type: string + - in: query + name: hidden_hits + 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 - in: query - name: max_extra_prefix + name: prioritize_token_position 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 + default: false + description: 'Make Typesense prioritize documents where the query words + appear earlier in the text. + + ' + type: boolean - in: query - name: nl_query + name: prioritize_exact_match schema: - description: Whether to use natural language processing to parse the query. + default: true + description: 'Set this parameter to true to ensure that an exact match is + ranked above the others + + ' type: boolean - in: query - name: num_typos + name: limit schema: - description: 'The number of typographical errors (1 or 2) that would be - tolerated. Default: 2 + description: 'Number of hits to fetch. Can be used as an alternative to + the per_page parameter. Default: 10. ' - type: string + type: integer - in: query - name: offset + name: filter_curated_hits schema: - description: Identifies the starting point to return hits from a result - set. Can be used as an alternative to the page parameter. + 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 + + ' + type: boolean + - in: query + name: cache_ttl + 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 - in: query - name: drop_tokens_threshold + name: typo_tokens_threshold 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 + than this number, Typesense will attempt to look for tokens with more + typos until enough results are found. Default: 100 ' type: integer - in: query - name: facet_strategy + name: max_candidates schema: - description: 'Choose the underlying faceting strategy used. Comma separated - string of allows values: exhaustive, top_values or automatic (default). + description: 'Control the number of words that Typesense considers for typo + and prefix searching. + + ' + type: integer + - in: query + name: num_typos + schema: + description: 'The number of typographical errors (1 or 2) that would be + tolerated. Default: 2 + + ' + type: string + - in: query + name: facet_return_parent + schema: + description: 'Comma separated string of nested facet fields whose parent + object should be returned in facet response. ' type: string @@ -3480,23 +3519,27 @@ paths: ' type: boolean - in: query - name: text_match_type + name: prefix 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. + 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 - in: query - name: query_by_weights + name: preset 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. + description: 'Search using a bunch of search parameters by setting this + parameter to the name of the existing Preset. + + ' type: string - in: query - name: per_page + name: highlight_affix_num_tokens schema: - description: 'Number of results to fetch per page. Default: 10' + description: 'The number of tokens that should surround the highlighted + text on each side. Default: 4 + + ' type: integer - in: query name: facet_by @@ -3505,92 +3548,76 @@ paths: on. Separate multiple fields with a comma. type: string - in: query - name: conversation_model_id + name: enable_overrides schema: - description: 'The Id of Conversation Model to be used. + default: false + 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: string - - in: query - name: max_extra_suffix - 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 - - in: query - name: group_by - 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 + type: boolean - in: query - name: min_len_1typo + name: enable_analytics 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. + default: true + description: 'Flag for enabling/disabling analytics aggregation for specific + search queries (for e.g. those originating from a test script). ' - type: integer + type: boolean - in: query - name: remote_embedding_num_tries + name: conversation_model_id schema: - description: 'Number of times to retry fetching remote embeddings. + description: 'The Id of Conversation Model to be used. ' - type: integer + type: string - in: query - name: stopwords + name: facet_strategy 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. + description: 'Choose the underlying faceting strategy used. Comma separated + string of allows values: exhaustive, top_values or automatic (default). ' type: string - in: query - name: enable_typos_for_numerical_tokens + name: pinned_hits schema: - default: true - description: 'Make Typesense disable typos for numerical tokens. + 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`. - ' - type: boolean - - in: query - name: max_filter_by_candidates - 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 - - in: query - name: prioritize_exact_match - schema: - default: true - description: 'Set this parameter to true to ensure that an exact match is - ranked above the others + 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: boolean + type: string - in: query - name: search_cutoff_ms + name: remote_embedding_num_tries 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. + description: 'Number of times to retry fetching remote embeddings. ' type: integer - in: query - name: highlight_affix_num_tokens + name: synonym_prefix schema: - description: 'The number of tokens that should surround the highlighted - text on each side. Default: 4 + description: 'Allow synonym resolution on word prefixes in the query. Default: + false ' - type: integer + type: boolean + - in: query + name: q + 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 - in: query name: infix schema: @@ -3601,6 +3628,20 @@ paths: along with regular search `fallback` infix search is performed if regular search does not produce results type: string + - in: query + name: nl_model_id + schema: + description: The ID of the natural language model to use. + type: string + - in: query + name: max_extra_suffix + 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 - in: query name: highlight_fields schema: @@ -3610,189 +3651,143 @@ paths: ' type: string - in: query - name: drop_tokens_mode + name: conversation schema: - $ref: '#/components/schemas/DropTokensMode' + description: 'Enable conversational search. + + ' + type: boolean - in: query - name: filter_by + name: vector_query schema: - description: Filter conditions for refining your open api validator search - results. Separate multiple conditions with &&. - example: 'num_employees:>100 && country: [USA, UK]' + description: 'Vector query expression for fetching documents "closest" to + a given query/document vector. + + ' type: string - in: query - name: remote_embedding_timeout_ms + name: min_len_2typo schema: - description: 'Timeout (in milliseconds) for fetching remote embeddings. + 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 - in: query - name: preset + name: enable_synonyms schema: - description: 'Search using a bunch of search parameters by setting this - parameter to the name of the existing Preset. + 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 ' - type: string + type: boolean - in: query - name: enable_highlight_v1 + name: remote_embedding_timeout_ms schema: - default: true - description: 'Flag for enabling/disabling the deprecated, old highlight - structure in the response. Default: true - - ' - type: boolean - - in: query - name: nl_model_id - schema: - description: The ID of the natural language model to use. - type: string - - in: query - name: filter_curated_hits - schema: - 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 + description: 'Timeout (in milliseconds) for fetching remote embeddings. ' - type: boolean + type: integer - in: query - name: enable_synonyms + name: stopwords schema: - 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 + 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: boolean - - in: query - name: sort_by - 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` - example: num_employees:desc type: string - in: query - name: facet_return_parent + name: filter_by schema: - description: 'Comma separated string of nested facet fields whose parent - object should be returned in facet response. - - ' + description: Filter conditions for refining your open api validator search + results. Separate multiple conditions with &&. + example: 'num_employees:>100 && country: [USA, UK]' type: string - in: query - name: pre_segmented_query + name: split_join_tokens 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 + 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: boolean - - in: query - name: include_fields - schema: - description: List of fields from the document to include in the search result type: string - in: query - name: prioritize_token_position - schema: - default: false - description: 'Make Typesense prioritize documents where the query words - appear earlier in the text. - - ' - type: boolean - - in: query - name: enable_typos_for_alpha_numerical_tokens + name: enable_highlight_v1 schema: - description: 'Set this parameter to false to disable typos on alphanumerical - query tokens. Default: true. + default: true + description: 'Flag for enabling/disabling the deprecated, old highlight + structure in the response. Default: true ' type: boolean - in: query - name: highlight_start_tag + name: group_by schema: - description: 'The start tag used for the highlighted snippets. Default: - `` - - ' + 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 - in: query - name: facet_query + name: override_tags 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". + description: Comma separated list of tags to trigger the curations rules + that match the tags. type: string - in: query - name: vector_query + name: snippet_threshold schema: - description: 'Vector query expression for fetching documents "closest" to - a given query/document vector. + description: 'Field values under this length will be fully highlighted, + instead of showing a snippet of relevant portion. Default: 30 ' - type: string + type: integer - in: query - name: conversation + name: per_page schema: - description: 'Enable conversational search. - - ' - type: boolean + description: 'Number of results to fetch per page. Default: 10' + type: integer - in: query - name: highlight_end_tag + name: voice_query schema: - description: 'The end tag used for the highlighted snippets. Default: `` + description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. ' type: string - in: query - name: typo_tokens_threshold + name: max_facet_values 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 - - ' + description: Maximum number of facet values to be returned. type: integer - in: query - name: override_tags + name: max_filter_by_candidates schema: - description: Comma separated list of tags to trigger the curations rules - that match the tags. - type: string + 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 - in: query - name: max_candidates + name: highlight_start_tag schema: - description: 'Control the number of words that Typesense considers for typo - and prefix searching. + description: 'The start tag used for the highlighted snippets. Default: + `` ' - type: integer + type: string - in: query - name: enable_analytics + name: drop_tokens_mode schema: - default: true - description: 'Flag for enabling/disabling analytics aggregation for specific - search queries (for e.g. those originating from a test script). - - ' - type: boolean + $ref: '#/components/schemas/DropTokensMode' - in: query - name: highlight_full_fields + name: synonym_num_typos schema: - description: List of fields which should be highlighted fully without snippeting - type: string + description: 'Allow synonym resolution on typo-corrected words in the query. + Default: 0 + + ' + type: integer responses: '200': content: @@ -4465,37 +4460,6 @@ paths: in a single HTTP request. operationId: multiSearch parameters: - - in: query - name: group_missing_values - 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 - - in: query - name: min_len_2typo - 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 - - in: query - name: max_facet_values - schema: - description: Maximum number of facet values to be returned. - type: integer - - in: query - name: synonym_prefix - schema: - description: 'Allow synonym resolution on word prefixes in the query. Default: - false - - ' - type: boolean - in: query name: conversation_id schema: @@ -4504,51 +4468,38 @@ paths: ' type: string - - in: query - name: cache_ttl - 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 - in: query name: exclude_fields schema: description: List of fields from the document to exclude in the search result type: string - in: query - name: hidden_hits + name: pre_segmented_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`. + default: false + 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. - ' - type: string - - in: query - name: exhaustive_search - 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). + Set this parameter to true to do the same ' type: boolean - in: query - name: snippet_threshold + name: min_len_1typo schema: - description: 'Field values under this length will be fully highlighted, - instead of showing a snippet of relevant portion. Default: 30 + 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 + - in: query + name: query_by_weights + 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 - in: query name: query_by schema: @@ -4556,16 +4507,19 @@ paths: fields are separated with a comma. type: string - in: query - name: page + name: drop_tokens_threshold schema: - description: Results from this specific page number would be fetched. + 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 - in: query - name: q + name: include_fields 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. + description: List of fields from the document to include in the search result type: string - in: query name: group_limit @@ -4577,215 +4531,220 @@ paths: ' type: integer - in: query - name: synonym_num_typos + name: max_extra_prefix schema: - description: 'Allow synonym resolution on typo-corrected words in the query. - Default: 0 - - ' + 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 - in: query - name: limit + name: sort_by schema: - description: 'Number of hits to fetch. Can be used as an alternative to - the per_page parameter. Default: 10. - - ' - type: integer + 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 - in: query - name: pinned_hits + name: offset 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 + description: Identifies the starting point to return hits from a result + set. Can be used as an alternative to the page parameter. + type: integer - in: query - name: prefix + name: page 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 + description: Results from this specific page number would be fetched. + type: integer - in: query - name: enable_overrides + name: exhaustive_search schema: - default: false - 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 + 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 - in: query - name: prioritize_num_matching_fields + name: search_cutoff_ms schema: - default: true - description: 'Make Typesense prioritize documents where the query words - appear in more number of fields. + 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: boolean + type: integer - in: query - name: voice_query + name: facet_query schema: - description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. - - ' + 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 - in: query - name: max_extra_prefix + name: text_match_type 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 + 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 - in: query - name: num_typos + name: highlight_end_tag schema: - description: 'The number of typographical errors (1 or 2) that would be - tolerated. Default: 2 + description: 'The end tag used for the highlighted snippets. Default: `` ' type: string - in: query - name: facet_strategy + name: enable_typos_for_alpha_numerical_tokens schema: - description: 'Choose the underlying faceting strategy used. Comma separated - string of allows values: exhaustive, top_values or automatic (default). + description: 'Set this parameter to false to disable typos on alphanumerical + query tokens. Default: true. ' - type: string - - in: query - name: offset - 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 + type: boolean - in: query - name: drop_tokens_threshold + name: enable_typos_for_numerical_tokens 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 + default: true + description: 'Make Typesense disable typos for numerical tokens. ' - type: integer + type: boolean - in: query - name: use_cache + name: group_missing_values schema: - description: 'Enable server side caching of search query results. By default, - caching is disabled. + 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 - in: query - name: per_page + name: prioritize_num_matching_fields schema: - description: 'Number of results to fetch per page. Default: 10' - type: integer + default: true + description: 'Make Typesense prioritize documents where the query words + appear in more number of fields. + + ' + type: boolean - in: query - name: text_match_type + name: highlight_full_fields 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. + description: List of fields which should be highlighted fully without snippeting type: string - in: query - name: query_by_weights + name: hidden_hits 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. + 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 - in: query - name: facet_by + name: prioritize_exact_match schema: - description: A list of fields that will be used for faceting your results - on. Separate multiple fields with a comma. - type: string + default: true + description: 'Set this parameter to true to ensure that an exact match is + ranked above the others + + ' + type: boolean - in: query - name: group_by + name: prioritize_token_position 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 + default: false + description: 'Make Typesense prioritize documents where the query words + appear earlier in the text. + + ' + type: boolean - in: query - name: conversation_model_id + name: limit schema: - description: 'The Id of Conversation Model to be used. + description: 'Number of hits to fetch. Can be used as an alternative to + the per_page parameter. Default: 10. ' - type: string + type: integer - in: query - name: min_len_1typo + name: cache_ttl 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. + 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 - in: query - name: max_extra_suffix + name: typo_tokens_threshold 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. + 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 - in: query - name: stopwords + name: filter_curated_hits + schema: + 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 + + ' + type: boolean + - in: query + name: num_typos 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. + description: 'The number of typographical errors (1 or 2) that would be + tolerated. Default: 2 ' type: string - in: query - name: remote_embedding_num_tries + name: facet_return_parent schema: - description: 'Number of times to retry fetching remote embeddings. + description: 'Comma separated string of nested facet fields whose parent + object should be returned in facet response. ' - type: integer + type: string - in: query - name: enable_typos_for_numerical_tokens + name: prefix schema: - default: true - description: 'Make Typesense disable typos for numerical tokens. - - ' - type: boolean + 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 - in: query - name: prioritize_exact_match + name: use_cache schema: - default: true - description: 'Set this parameter to true to ensure that an exact match is - ranked above the others + description: 'Enable server side caching of search query results. By default, + caching is disabled. ' type: boolean - in: query - name: search_cutoff_ms + name: preset 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. + description: 'Search using a bunch of search parameters by setting this + parameter to the name of the existing Preset. ' - type: integer + type: string - in: query name: highlight_affix_num_tokens schema: @@ -4795,91 +4754,123 @@ paths: ' type: integer - in: query - name: infix + name: facet_by 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 + description: A list of fields that will be used for faceting your results + on. Separate multiple fields with a comma. type: string - in: query - name: highlight_fields + name: enable_overrides schema: - description: 'A list of custom fields that must be highlighted even if you - don''t query for them + default: false + 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: string + type: boolean - in: query - name: filter_by + name: pinned_hits schema: - description: Filter conditions for refining youropen api validator search - results. Separate multiple conditions with &&. - example: 'num_employees:>100 && country: [USA, UK]' + 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 - in: query - name: drop_tokens_mode + name: enable_analytics schema: - $ref: '#/components/schemas/DropTokensMode' + default: true + description: 'Flag for enabling/disabling analytics aggregation for specific + search queries (for e.g. those originating from a test script). + + ' + type: boolean - in: query - name: remote_embedding_timeout_ms + name: facet_strategy schema: - description: 'Timeout (in milliseconds) for fetching remote embeddings. + description: 'Choose the underlying faceting strategy used. Comma separated + string of allows values: exhaustive, top_values or automatic (default). ' - type: integer + type: string - in: query - name: enable_typos_for_alpha_numerical_tokens + name: conversation_model_id schema: - description: 'Set this parameter to false to disable typos on alphanumerical - query tokens. Default: true. + description: 'The Id of Conversation Model to be used. ' - type: boolean + type: string - in: query - name: preset + name: remote_embedding_num_tries schema: - description: 'Search using a bunch of search parameters by setting this - parameter to the name of the existing Preset. + description: 'Number of times to retry fetching remote embeddings. ' + type: integer + - in: query + name: q + 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 - in: query - name: filter_curated_hits + name: synonym_prefix schema: - 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 + description: 'Allow synonym resolution on word prefixes in the query. Default: + false ' type: boolean - in: query - name: pre_segmented_query + name: infix schema: - default: false - 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 + 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 + - in: query + name: conversation + schema: + description: 'Enable conversational search. ' type: boolean - in: query - name: include_fields + name: max_extra_suffix schema: - description: List of fields from the document to include in the search result + 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 + - in: query + name: highlight_fields + schema: + description: 'A list of custom fields that must be highlighted even if you + don''t query for them + + ' type: string - in: query - name: sort_by + name: vector_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` + description: 'Vector query expression for fetching documents "closest" to + a given query/document vector. + + ' type: string - in: query name: enable_synonyms @@ -4891,89 +4882,93 @@ paths: ' type: boolean - in: query - name: facet_return_parent + name: min_len_2typo schema: - description: 'Comma separated string of nested facet fields whose parent - object should be returned in facet response. + 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: string + type: integer - in: query - name: prioritize_token_position + name: remote_embedding_timeout_ms schema: - default: false - description: 'Make Typesense prioritize documents where the query words - appear earlier in the text. + description: 'Timeout (in milliseconds) for fetching remote embeddings. ' - type: boolean + type: integer - in: query - name: highlight_start_tag + name: stopwords schema: - description: 'The start tag used for the highlighted snippets. Default: - `` + 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 - in: query - name: facet_query + name: filter_by 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". + description: Filter conditions for refining youropen api validator search + results. Separate multiple conditions with &&. + example: 'num_employees:>100 && country: [USA, UK]' type: string - in: query - name: vector_query + name: group_by schema: - description: 'Vector query expression for fetching documents "closest" to - a given query/document vector. - - ' + 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 - in: query - name: conversation + name: override_tags schema: - description: 'Enable conversational search. - - ' - type: boolean + description: Comma separated list of tags to trigger the curations rules + that match the tags. + type: string - in: query - name: highlight_end_tag + name: synonym_num_typos schema: - description: 'The end tag used for the highlighted snippets. Default: `` + description: 'Allow synonym resolution on typo-corrected words in the query. + Default: 0 ' - type: string + type: integer - in: query - name: typo_tokens_threshold + name: per_page 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 + description: 'Number of results to fetch per page. Default: 10' + type: integer + - in: query + name: snippet_threshold + schema: + description: 'Field values under this length will be fully highlighted, + instead of showing a snippet of relevant portion. Default: 30 ' type: integer - in: query - name: override_tags + name: max_facet_values schema: - description: Comma separated list of tags to trigger the curations rules - that match the tags. - type: string + description: Maximum number of facet values to be returned. + type: integer - in: query - name: enable_analytics + name: highlight_start_tag schema: - default: true - description: 'Flag for enabling/disabling analytics aggregation for specific - search queries (for e.g. those originating from a test script). + description: 'The start tag used for the highlighted snippets. Default: + `` ' - type: boolean + type: string - in: query - name: highlight_full_fields + name: voice_query schema: - description: List of fields which should be highlighted fully without snippeting + description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. + + ' type: string + - in: query + name: drop_tokens_mode + schema: + $ref: '#/components/schemas/DropTokensMode' requestBody: content: application/json: From b4646bc432451f1697ccdddd91b8663a1deef7e4 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Tue, 2 Dec 2025 11:08:55 +0700 Subject: [PATCH 04/21] sort model fields required before optional --- README.md | 2 +- Sources/Typesense/AnalyticsRules.swift | 4 +- Sources/Typesense/Client.swift | 6 +- .../Typesense/Models/APIStatsResponse.swift | 1 - Sources/Typesense/Models/AnalyticsEvent.swift | 1 - .../Models/AnalyticsEventCreateResponse.swift | 1 - .../Typesense/Models/AnalyticsEventData.swift | 1 - .../Models/AnalyticsEventsResponse.swift | 1 - .../AnalyticsEventsResponseEventsInner.swift | 1 - Sources/Typesense/Models/AnalyticsRule.swift | 3 +- .../Models/AnalyticsRuleCreate.swift | 3 +- .../Models/AnalyticsRuleCreateParams.swift | 1 - .../Models/AnalyticsRuleUpdate.swift | 1 - .../Typesense/Models/AnalyticsStatus.swift | 1 - Sources/Typesense/Models/ApiKey.swift | 1 - .../Models/ApiKeyDeleteResponse.swift | 1 - Sources/Typesense/Models/ApiKeySchema.swift | 1 - .../Typesense/Models/ApiKeysResponse.swift | 1 - Sources/Typesense/Models/ApiResponse.swift | 1 - .../Typesense/Models/CollectionAlias.swift | 1 - .../Models/CollectionAliasSchema.swift | 1 - .../Models/CollectionAliasesResponse.swift | 1 - .../Typesense/Models/CollectionResponse.swift | 3 +- .../Typesense/Models/CollectionSchema.swift | 3 +- .../Models/CollectionUpdateSchema.swift | 1 - .../ConversationModelCreateSchema.swift | 3 +- .../Models/ConversationModelSchema.swift | 3 +- .../ConversationModelUpdateSchema.swift | 1 - ...lyticsRule200ResponseOneOfInnerAnyOf.swift | 1 - .../Typesense/Models/CurationExclude.swift | 1 - .../Typesense/Models/CurationInclude.swift | 1 - .../Models/CurationItemCreateSchema.swift | 3 +- .../Models/CurationItemDeleteSchema.swift | 1 - .../Typesense/Models/CurationItemSchema.swift | 3 +- Sources/Typesense/Models/CurationRule.swift | 1 - .../Models/CurationSetCreateSchema.swift | 3 +- .../Models/CurationSetDeleteSchema.swift | 1 - .../Typesense/Models/CurationSetSchema.swift | 3 +- .../Typesense/Models/Debug200Response.swift | 1 - .../Models/DeleteDocuments200Response.swift | 1 - .../Models/DeleteDocumentsParameters.swift | 3 +- .../DeleteStopwordsSet200Response.swift | 1 - .../Models/ExportDocumentsParameters.swift | 1 - Sources/Typesense/Models/FacetCounts.swift | 1 - .../Models/FacetCountsCountsInner.swift | 1 - .../Typesense/Models/FacetCountsStats.swift | 1 - Sources/Typesense/Models/Field.swift | 3 +- Sources/Typesense/Models/FieldEmbed.swift | 1 - .../Models/FieldEmbedModelConfig.swift | 3 +- .../Models/GetCollectionsParameters.swift | 1 - Sources/Typesense/Models/HealthStatus.swift | 1 - .../Models/ImportDocumentsParameters.swift | 1 - .../ListStemmingDictionaries200Response.swift | 1 - .../MultiSearchCollectionParameters.swift | 1 - .../Models/MultiSearchParameters.swift | 1 - .../Typesense/Models/MultiSearchResult.swift | 5 +- .../Models/MultiSearchResultItem.swift | 1 - .../Models/MultiSearchSearchesParameter.swift | 1 - .../Typesense/Models/NLSearchModelBase.swift | 1 - .../Models/NLSearchModelCreateSchema.swift | 1 - .../Models/NLSearchModelDeleteSchema.swift | 1 - .../Models/NLSearchModelSchema.swift | 3 +- .../Typesense/Models/PresetDeleteSchema.swift | 1 - Sources/Typesense/Models/PresetSchema.swift | 1 - .../Typesense/Models/PresetUpsertSchema.swift | 1 - .../Models/PresetsRetrieveSchema.swift | 1 - .../Typesense/Models/SchemaChangeStatus.swift | 1 - .../Typesense/Models/SearchGroupedHit.swift | 3 +- .../Typesense/Models/SearchHighlight.swift | 1 - .../Typesense/Models/SearchParameters.swift | 1 - .../Models/SearchRequestParams.swift | 1 - .../SearchRequestParamsVoiceQuery.swift | 1 - Sources/Typesense/Models/SearchResult.swift | 1 - .../Models/SearchResultConversation.swift | 1 - .../Typesense/Models/SearchResultHit.swift | 1 - .../SearchResultHitHybridSearchInfo.swift | 1 - .../Models/SearchResultHitTextMatchInfo.swift | 1 - Sources/Typesense/Models/SearchSynonym.swift | 3 +- .../Models/SearchSynonymDeleteResponse.swift | 1 - .../Models/SearchSynonymSchema.swift | 3 +- .../Models/SearchSynonymsResponse.swift | 1 - .../Typesense/Models/StemmingDictionary.swift | 1 - .../Models/StemmingDictionaryWordsInner.swift | 1 - .../Models/StopwordsSetRetrieveSchema.swift | 1 - .../Typesense/Models/StopwordsSetSchema.swift | 3 +- .../Models/StopwordsSetUpsertSchema.swift | 3 +- .../StopwordsSetsRetrieveAllSchema.swift | 1 - Sources/Typesense/Models/SuccessStatus.swift | 1 - .../Models/SynonymItemDeleteSchema.swift | 1 - .../Typesense/Models/SynonymItemSchema.swift | 3 +- .../Models/SynonymSetCreateSchema.swift | 1 - .../Models/SynonymSetDeleteSchema.swift | 1 - .../Typesense/Models/SynonymSetSchema.swift | 1 - .../Models/SynonymSetsRetrieveSchema.swift | 1 - .../Models/ToggleSlowRequestLogRequest.swift | 1 - .../Models/UpdateDocuments200Response.swift | 1 - .../Models/UpdateDocumentsParameters.swift | 1 - .../VoiceQueryModelCollectionConfig.swift | 1 - Tasks/AddVendorAttributes.swift | 2 +- Tests/TypesenseTests/AnalyticsTests.swift | 43 +- Tests/TypesenseTests/ApiKeyTests.swift | 2 +- Tests/TypesenseTests/CollectionTests.swift | 13 +- .../ConversationModelTests.swift | 6 +- Tests/TypesenseTests/DocumentTests.swift | 18 +- Tests/TypesenseTests/MultiSearchTests.swift | 44 +- Tests/TypesenseTests/SynonymTests.swift | 15 +- Tests/TypesenseTests/TestUtils.swift | 32 +- .../modelObject.mustache | 8 +- preprocessed_openapi.yml | 1208 ++++++++--------- 109 files changed, 735 insertions(+), 807 deletions(-) diff --git a/README.md b/README.md index 17b8fcf..e3a0d22 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ You can create a collection by first defining a collection schema: ```swift let myCoolSchema = CollectionSchema(name: "schools", fields: [Field(name: "school_name", type: "string"), Field(name: "num_students", type: "int32"), Field(name: "country", type: "string", facet: true)], defaultSortingField: "num_students") -let (data, response) = try await client.collections.create(schema: myCoolSchema) +let (data, response) = try await client.collections().create(schema: myCoolSchema) ``` Define the structure of your document as per your collection, and index it by inserting/upserting it to the collection: diff --git a/Sources/Typesense/AnalyticsRules.swift b/Sources/Typesense/AnalyticsRules.swift index 19efd90..e03af51 100644 --- a/Sources/Typesense/AnalyticsRules.swift +++ b/Sources/Typesense/AnalyticsRules.swift @@ -25,7 +25,7 @@ public struct AnalyticsRules { public func create(_ params: AnalyticsRuleCreate) async throws -> (AnalyticsRule?, URLResponse?) { let ruleData = try encoder.encode(params) - let (data, response) = try await self.apiCall.put(endPoint: endpointPath(), body: ruleData) + let (data, response) = try await self.apiCall.post(endPoint: endpointPath(), body: ruleData) if let result = data { let ruleResult = try decoder.decode(AnalyticsRule.self, from: result) return (ruleResult, response) @@ -36,7 +36,7 @@ public struct AnalyticsRules { public func createMany(_ params: [AnalyticsRuleCreate]) async throws -> ([AnalyticsRule]?, URLResponse?) { let ruleData = try encoder.encode(params) - let (data, response) = try await self.apiCall.put(endPoint: endpointPath(), body: ruleData) + let (data, response) = try await self.apiCall.post(endPoint: endpointPath(), body: ruleData) if let result = data { let ruleResult = try decoder.decode([AnalyticsRule].self, from: result) return (ruleResult, response) diff --git a/Sources/Typesense/Client.swift b/Sources/Typesense/Client.swift index 93191e7..a7b5ca4 100644 --- a/Sources/Typesense/Client.swift +++ b/Sources/Typesense/Client.swift @@ -4,12 +4,14 @@ public struct Client { var configuration: Configuration var apiCall: ApiCall - public var collections: Collections public init(config: Configuration) { self.configuration = config self.apiCall = ApiCall(config: config) - self.collections = Collections(apiCall: apiCall) + } + + public func collections() -> Collections { + return Collections(apiCall: apiCall) } public func collection(name: String) -> Collection { diff --git a/Sources/Typesense/Models/APIStatsResponse.swift b/Sources/Typesense/Models/APIStatsResponse.swift index 3a718a0..b4d9605 100644 --- a/Sources/Typesense/Models/APIStatsResponse.swift +++ b/Sources/Typesense/Models/APIStatsResponse.swift @@ -77,4 +77,3 @@ public struct APIStatsResponse: Codable { try container.encodeIfPresent(writeRequestsPerSecond, forKey: .writeRequestsPerSecond) } } - diff --git a/Sources/Typesense/Models/AnalyticsEvent.swift b/Sources/Typesense/Models/AnalyticsEvent.swift index a409a8d..2df3e36 100644 --- a/Sources/Typesense/Models/AnalyticsEvent.swift +++ b/Sources/Typesense/Models/AnalyticsEvent.swift @@ -39,4 +39,3 @@ public struct AnalyticsEvent: Codable { try container.encode(name, forKey: .name) } } - diff --git a/Sources/Typesense/Models/AnalyticsEventCreateResponse.swift b/Sources/Typesense/Models/AnalyticsEventCreateResponse.swift index 74ece77..f91d369 100644 --- a/Sources/Typesense/Models/AnalyticsEventCreateResponse.swift +++ b/Sources/Typesense/Models/AnalyticsEventCreateResponse.swift @@ -29,4 +29,3 @@ public struct AnalyticsEventCreateResponse: Codable { try container.encode(ok, forKey: .ok) } } - diff --git a/Sources/Typesense/Models/AnalyticsEventData.swift b/Sources/Typesense/Models/AnalyticsEventData.swift index 095a5c5..e1e78be 100644 --- a/Sources/Typesense/Models/AnalyticsEventData.swift +++ b/Sources/Typesense/Models/AnalyticsEventData.swift @@ -46,4 +46,3 @@ public struct AnalyticsEventData: Codable { try container.encodeIfPresent(userId, forKey: .userId) } } - diff --git a/Sources/Typesense/Models/AnalyticsEventsResponse.swift b/Sources/Typesense/Models/AnalyticsEventsResponse.swift index a25fe97..a8477ed 100644 --- a/Sources/Typesense/Models/AnalyticsEventsResponse.swift +++ b/Sources/Typesense/Models/AnalyticsEventsResponse.swift @@ -29,4 +29,3 @@ public struct AnalyticsEventsResponse: Codable { try container.encode(events, forKey: .events) } } - diff --git a/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift b/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift index 5c1ee44..22d3067 100644 --- a/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift +++ b/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift @@ -57,4 +57,3 @@ public struct AnalyticsEventsResponseEventsInner: Codable { try container.encodeIfPresent(userId, forKey: .userId) } } - diff --git a/Sources/Typesense/Models/AnalyticsRule.swift b/Sources/Typesense/Models/AnalyticsRule.swift index b3a495e..2b15c75 100644 --- a/Sources/Typesense/Models/AnalyticsRule.swift +++ b/Sources/Typesense/Models/AnalyticsRule.swift @@ -25,7 +25,7 @@ public struct AnalyticsRule: Codable { public var ruleTag: String? public var type: ModelType - public init(collection: String, eventType: String, name: String, params: AnalyticsRuleCreateParams? = nil, ruleTag: String? = nil, type: ModelType) { + public init(collection: String, eventType: String, name: String, type: ModelType, params: AnalyticsRuleCreateParams? = nil, ruleTag: String? = nil) { self.collection = collection self.eventType = eventType self.name = name @@ -55,4 +55,3 @@ public struct AnalyticsRule: Codable { try container.encode(type, forKey: .type) } } - diff --git a/Sources/Typesense/Models/AnalyticsRuleCreate.swift b/Sources/Typesense/Models/AnalyticsRuleCreate.swift index ef0ba37..8b77674 100644 --- a/Sources/Typesense/Models/AnalyticsRuleCreate.swift +++ b/Sources/Typesense/Models/AnalyticsRuleCreate.swift @@ -25,7 +25,7 @@ public struct AnalyticsRuleCreate: Codable { public var ruleTag: String? public var type: ModelType - public init(collection: String, eventType: String, name: String, params: AnalyticsRuleCreateParams? = nil, ruleTag: String? = nil, type: ModelType) { + public init(collection: String, eventType: String, name: String, type: ModelType, params: AnalyticsRuleCreateParams? = nil, ruleTag: String? = nil) { self.collection = collection self.eventType = eventType self.name = name @@ -55,4 +55,3 @@ public struct AnalyticsRuleCreate: Codable { try container.encode(type, forKey: .type) } } - diff --git a/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift b/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift index 5b36c74..029256b 100644 --- a/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift +++ b/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift @@ -53,4 +53,3 @@ public struct AnalyticsRuleCreateParams: Codable { try container.encodeIfPresent(weight, forKey: .weight) } } - diff --git a/Sources/Typesense/Models/AnalyticsRuleUpdate.swift b/Sources/Typesense/Models/AnalyticsRuleUpdate.swift index 8cddca1..1bf1f68 100644 --- a/Sources/Typesense/Models/AnalyticsRuleUpdate.swift +++ b/Sources/Typesense/Models/AnalyticsRuleUpdate.swift @@ -38,4 +38,3 @@ public struct AnalyticsRuleUpdate: Codable { try container.encodeIfPresent(ruleTag, forKey: .ruleTag) } } - diff --git a/Sources/Typesense/Models/AnalyticsStatus.swift b/Sources/Typesense/Models/AnalyticsStatus.swift index 34a8905..20cf623 100644 --- a/Sources/Typesense/Models/AnalyticsStatus.swift +++ b/Sources/Typesense/Models/AnalyticsStatus.swift @@ -53,4 +53,3 @@ public struct AnalyticsStatus: Codable { try container.encodeIfPresent(queryLogEvents, forKey: .queryLogEvents) } } - diff --git a/Sources/Typesense/Models/ApiKey.swift b/Sources/Typesense/Models/ApiKey.swift index 3214956..55afb2d 100644 --- a/Sources/Typesense/Models/ApiKey.swift +++ b/Sources/Typesense/Models/ApiKey.swift @@ -53,4 +53,3 @@ public struct ApiKey: Codable { try container.encodeIfPresent(valuePrefix, forKey: .valuePrefix) } } - diff --git a/Sources/Typesense/Models/ApiKeyDeleteResponse.swift b/Sources/Typesense/Models/ApiKeyDeleteResponse.swift index 1be4627..84dbb36 100644 --- a/Sources/Typesense/Models/ApiKeyDeleteResponse.swift +++ b/Sources/Typesense/Models/ApiKeyDeleteResponse.swift @@ -30,4 +30,3 @@ public struct ApiKeyDeleteResponse: Codable { try container.encode(id, forKey: .id) } } - diff --git a/Sources/Typesense/Models/ApiKeySchema.swift b/Sources/Typesense/Models/ApiKeySchema.swift index 82b5723..402246f 100644 --- a/Sources/Typesense/Models/ApiKeySchema.swift +++ b/Sources/Typesense/Models/ApiKeySchema.swift @@ -45,4 +45,3 @@ public struct ApiKeySchema: Codable { try container.encodeIfPresent(value, forKey: .value) } } - diff --git a/Sources/Typesense/Models/ApiKeysResponse.swift b/Sources/Typesense/Models/ApiKeysResponse.swift index 27e2e96..8e5c400 100644 --- a/Sources/Typesense/Models/ApiKeysResponse.swift +++ b/Sources/Typesense/Models/ApiKeysResponse.swift @@ -29,4 +29,3 @@ public struct ApiKeysResponse: Codable { try container.encode(keys, forKey: .keys) } } - diff --git a/Sources/Typesense/Models/ApiResponse.swift b/Sources/Typesense/Models/ApiResponse.swift index 96caa34..e68a60c 100644 --- a/Sources/Typesense/Models/ApiResponse.swift +++ b/Sources/Typesense/Models/ApiResponse.swift @@ -29,4 +29,3 @@ public struct ApiResponse: Codable { try container.encode(message, forKey: .message) } } - diff --git a/Sources/Typesense/Models/CollectionAlias.swift b/Sources/Typesense/Models/CollectionAlias.swift index 1a39ceb..87b6707 100644 --- a/Sources/Typesense/Models/CollectionAlias.swift +++ b/Sources/Typesense/Models/CollectionAlias.swift @@ -35,4 +35,3 @@ public struct CollectionAlias: Codable { try container.encode(name, forKey: .name) } } - diff --git a/Sources/Typesense/Models/CollectionAliasSchema.swift b/Sources/Typesense/Models/CollectionAliasSchema.swift index e51ece9..6a99eff 100644 --- a/Sources/Typesense/Models/CollectionAliasSchema.swift +++ b/Sources/Typesense/Models/CollectionAliasSchema.swift @@ -30,4 +30,3 @@ public struct CollectionAliasSchema: Codable { try container.encode(collectionName, forKey: .collectionName) } } - diff --git a/Sources/Typesense/Models/CollectionAliasesResponse.swift b/Sources/Typesense/Models/CollectionAliasesResponse.swift index d96b299..b8dd182 100644 --- a/Sources/Typesense/Models/CollectionAliasesResponse.swift +++ b/Sources/Typesense/Models/CollectionAliasesResponse.swift @@ -29,4 +29,3 @@ public struct CollectionAliasesResponse: Codable { try container.encode(aliases, forKey: .aliases) } } - diff --git a/Sources/Typesense/Models/CollectionResponse.swift b/Sources/Typesense/Models/CollectionResponse.swift index 56a30da..2978ae7 100644 --- a/Sources/Typesense/Models/CollectionResponse.swift +++ b/Sources/Typesense/Models/CollectionResponse.swift @@ -34,7 +34,7 @@ public struct CollectionResponse: Codable { /** Number of documents in the collection */ public var numDocuments: Int64 - public init(defaultSortingField: String? = "", enableNestedFields: Bool? = false, fields: [Field], metadata: AnyCodable? = nil, name: String, symbolsToIndex: [String]? = nil, synonymSets: [String]? = nil, tokenSeparators: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil, createdAt: Int64, numDocuments: Int64) { + public init(fields: [Field], name: String, createdAt: Int64, numDocuments: Int64, defaultSortingField: String? = "", enableNestedFields: Bool? = false, metadata: AnyCodable? = nil, symbolsToIndex: [String]? = nil, synonymSets: [String]? = nil, tokenSeparators: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil) { self.defaultSortingField = defaultSortingField self.enableNestedFields = enableNestedFields self.fields = fields @@ -79,4 +79,3 @@ public struct CollectionResponse: Codable { try container.encode(numDocuments, forKey: .numDocuments) } } - diff --git a/Sources/Typesense/Models/CollectionSchema.swift b/Sources/Typesense/Models/CollectionSchema.swift index e20ad31..3774d5e 100644 --- a/Sources/Typesense/Models/CollectionSchema.swift +++ b/Sources/Typesense/Models/CollectionSchema.swift @@ -30,7 +30,7 @@ public struct CollectionSchema: Codable { public var tokenSeparators: [String]? public var voiceQueryModel: VoiceQueryModelCollectionConfig? - public init(defaultSortingField: String? = "", enableNestedFields: Bool? = false, fields: [Field], metadata: AnyCodable? = nil, name: String, symbolsToIndex: [String]? = nil, synonymSets: [String]? = nil, tokenSeparators: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil) { + public init(fields: [Field], name: String, defaultSortingField: String? = "", enableNestedFields: Bool? = false, metadata: AnyCodable? = nil, symbolsToIndex: [String]? = nil, synonymSets: [String]? = nil, tokenSeparators: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil) { self.defaultSortingField = defaultSortingField self.enableNestedFields = enableNestedFields self.fields = fields @@ -69,4 +69,3 @@ public struct CollectionSchema: Codable { try container.encodeIfPresent(voiceQueryModel, forKey: .voiceQueryModel) } } - diff --git a/Sources/Typesense/Models/CollectionUpdateSchema.swift b/Sources/Typesense/Models/CollectionUpdateSchema.swift index 77211a2..f697ad3 100644 --- a/Sources/Typesense/Models/CollectionUpdateSchema.swift +++ b/Sources/Typesense/Models/CollectionUpdateSchema.swift @@ -40,4 +40,3 @@ public struct CollectionUpdateSchema: Codable { try container.encodeIfPresent(synonymSets, forKey: .synonymSets) } } - diff --git a/Sources/Typesense/Models/ConversationModelCreateSchema.swift b/Sources/Typesense/Models/ConversationModelCreateSchema.swift index 2082789..d053cb3 100644 --- a/Sources/Typesense/Models/ConversationModelCreateSchema.swift +++ b/Sources/Typesense/Models/ConversationModelCreateSchema.swift @@ -31,7 +31,7 @@ public struct ConversationModelCreateSchema: Codable { /** URL of vLLM service */ public var vllmUrl: String? - public init(accountId: String? = nil, apiKey: String? = nil, historyCollection: String, id: String? = nil, maxBytes: Int, modelName: String, systemPrompt: String? = nil, ttl: Int? = nil, vllmUrl: String? = nil) { + public init(historyCollection: String, maxBytes: Int, modelName: String, accountId: String? = nil, apiKey: String? = nil, id: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, vllmUrl: String? = nil) { self.accountId = accountId self.apiKey = apiKey self.historyCollection = historyCollection @@ -70,4 +70,3 @@ public struct ConversationModelCreateSchema: Codable { try container.encodeIfPresent(vllmUrl, forKey: .vllmUrl) } } - diff --git a/Sources/Typesense/Models/ConversationModelSchema.swift b/Sources/Typesense/Models/ConversationModelSchema.swift index 069e835..bad45af 100644 --- a/Sources/Typesense/Models/ConversationModelSchema.swift +++ b/Sources/Typesense/Models/ConversationModelSchema.swift @@ -31,7 +31,7 @@ public struct ConversationModelSchema: Codable { /** URL of vLLM service */ public var vllmUrl: String? - public init(accountId: String? = nil, apiKey: String? = nil, historyCollection: String, id: String, maxBytes: Int, modelName: String, systemPrompt: String? = nil, ttl: Int? = nil, vllmUrl: String? = nil) { + public init(historyCollection: String, id: String, maxBytes: Int, modelName: String, accountId: String? = nil, apiKey: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, vllmUrl: String? = nil) { self.accountId = accountId self.apiKey = apiKey self.historyCollection = historyCollection @@ -70,4 +70,3 @@ public struct ConversationModelSchema: Codable { try container.encodeIfPresent(vllmUrl, forKey: .vllmUrl) } } - diff --git a/Sources/Typesense/Models/ConversationModelUpdateSchema.swift b/Sources/Typesense/Models/ConversationModelUpdateSchema.swift index 30a0500..3f48c0e 100644 --- a/Sources/Typesense/Models/ConversationModelUpdateSchema.swift +++ b/Sources/Typesense/Models/ConversationModelUpdateSchema.swift @@ -70,4 +70,3 @@ public struct ConversationModelUpdateSchema: Codable { try container.encodeIfPresent(vllmUrl, forKey: .vllmUrl) } } - diff --git a/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift b/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift index 1f63acb..e6be6f9 100644 --- a/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift +++ b/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift @@ -29,4 +29,3 @@ public struct CreateAnalyticsRule200ResponseOneOfInnerAnyOf: Codable { try container.encodeIfPresent(error, forKey: .error) } } - diff --git a/Sources/Typesense/Models/CurationExclude.swift b/Sources/Typesense/Models/CurationExclude.swift index 615783e..24bd770 100644 --- a/Sources/Typesense/Models/CurationExclude.swift +++ b/Sources/Typesense/Models/CurationExclude.swift @@ -30,4 +30,3 @@ public struct CurationExclude: Codable { try container.encode(id, forKey: .id) } } - diff --git a/Sources/Typesense/Models/CurationInclude.swift b/Sources/Typesense/Models/CurationInclude.swift index d9a52d3..03f10a3 100644 --- a/Sources/Typesense/Models/CurationInclude.swift +++ b/Sources/Typesense/Models/CurationInclude.swift @@ -35,4 +35,3 @@ public struct CurationInclude: Codable { try container.encode(position, forKey: .position) } } - diff --git a/Sources/Typesense/Models/CurationItemCreateSchema.swift b/Sources/Typesense/Models/CurationItemCreateSchema.swift index 5f2d6d1..9567a38 100644 --- a/Sources/Typesense/Models/CurationItemCreateSchema.swift +++ b/Sources/Typesense/Models/CurationItemCreateSchema.swift @@ -38,7 +38,7 @@ public struct CurationItemCreateSchema: Codable { /** When set to true, curation processing will stop at the first matching rule. When set to false curation processing will continue and multiple curation actions will be triggered in sequence. Curations are processed in the lexical sort order of their id field. */ public var stopProcessing: Bool? - public init(effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, id: String? = nil, includes: [CurationInclude]? = nil, metadata: AnyCodable? = nil, removeMatchedTokens: Bool? = nil, replaceQuery: String? = nil, rule: CurationRule, sortBy: String? = nil, stopProcessing: Bool? = nil) { + public init(rule: CurationRule, effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, id: String? = nil, includes: [CurationInclude]? = nil, metadata: AnyCodable? = nil, removeMatchedTokens: Bool? = nil, replaceQuery: String? = nil, sortBy: String? = nil, stopProcessing: Bool? = nil) { self.effectiveFromTs = effectiveFromTs self.effectiveToTs = effectiveToTs self.excludes = excludes @@ -89,4 +89,3 @@ public struct CurationItemCreateSchema: Codable { try container.encodeIfPresent(stopProcessing, forKey: .stopProcessing) } } - diff --git a/Sources/Typesense/Models/CurationItemDeleteSchema.swift b/Sources/Typesense/Models/CurationItemDeleteSchema.swift index 3df278b..1bc3fb5 100644 --- a/Sources/Typesense/Models/CurationItemDeleteSchema.swift +++ b/Sources/Typesense/Models/CurationItemDeleteSchema.swift @@ -30,4 +30,3 @@ public struct CurationItemDeleteSchema: Codable { try container.encode(id, forKey: .id) } } - diff --git a/Sources/Typesense/Models/CurationItemSchema.swift b/Sources/Typesense/Models/CurationItemSchema.swift index 63d4a56..b5d0da4 100644 --- a/Sources/Typesense/Models/CurationItemSchema.swift +++ b/Sources/Typesense/Models/CurationItemSchema.swift @@ -37,7 +37,7 @@ public struct CurationItemSchema: Codable { /** When set to true, curation processing will stop at the first matching rule. When set to false curation processing will continue and multiple curation actions will be triggered in sequence. Curations are processed in the lexical sort order of their id field. */ public var stopProcessing: Bool? - public init(effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, id: String, includes: [CurationInclude]? = nil, metadata: AnyCodable? = nil, removeMatchedTokens: Bool? = nil, replaceQuery: String? = nil, rule: CurationRule, sortBy: String? = nil, stopProcessing: Bool? = nil) { + public init(id: String, rule: CurationRule, effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, includes: [CurationInclude]? = nil, metadata: AnyCodable? = nil, removeMatchedTokens: Bool? = nil, replaceQuery: String? = nil, sortBy: String? = nil, stopProcessing: Bool? = nil) { self.effectiveFromTs = effectiveFromTs self.effectiveToTs = effectiveToTs self.excludes = excludes @@ -88,4 +88,3 @@ public struct CurationItemSchema: Codable { try container.encodeIfPresent(stopProcessing, forKey: .stopProcessing) } } - diff --git a/Sources/Typesense/Models/CurationRule.swift b/Sources/Typesense/Models/CurationRule.swift index 16b81bc..b627fe3 100644 --- a/Sources/Typesense/Models/CurationRule.swift +++ b/Sources/Typesense/Models/CurationRule.swift @@ -49,4 +49,3 @@ public struct CurationRule: Codable { try container.encodeIfPresent(tags, forKey: .tags) } } - diff --git a/Sources/Typesense/Models/CurationSetCreateSchema.swift b/Sources/Typesense/Models/CurationSetCreateSchema.swift index bec7cd2..7831154 100644 --- a/Sources/Typesense/Models/CurationSetCreateSchema.swift +++ b/Sources/Typesense/Models/CurationSetCreateSchema.swift @@ -17,7 +17,7 @@ public struct CurationSetCreateSchema: Codable { /** Array of curation items */ public var items: [CurationItemCreateSchema] - public init(description: String? = nil, items: [CurationItemCreateSchema]) { + public init(items: [CurationItemCreateSchema], description: String? = nil) { self.description = description self.items = items } @@ -35,4 +35,3 @@ public struct CurationSetCreateSchema: Codable { try container.encode(items, forKey: .items) } } - diff --git a/Sources/Typesense/Models/CurationSetDeleteSchema.swift b/Sources/Typesense/Models/CurationSetDeleteSchema.swift index df7a073..aca1326 100644 --- a/Sources/Typesense/Models/CurationSetDeleteSchema.swift +++ b/Sources/Typesense/Models/CurationSetDeleteSchema.swift @@ -30,4 +30,3 @@ public struct CurationSetDeleteSchema: Codable { try container.encode(name, forKey: .name) } } - diff --git a/Sources/Typesense/Models/CurationSetSchema.swift b/Sources/Typesense/Models/CurationSetSchema.swift index dcd13d3..a661733 100644 --- a/Sources/Typesense/Models/CurationSetSchema.swift +++ b/Sources/Typesense/Models/CurationSetSchema.swift @@ -18,7 +18,7 @@ public struct CurationSetSchema: Codable { public var items: [CurationItemCreateSchema] public var name: String - public init(description: String? = nil, items: [CurationItemCreateSchema], name: String) { + public init(items: [CurationItemCreateSchema], name: String, description: String? = nil) { self.description = description self.items = items self.name = name @@ -39,4 +39,3 @@ public struct CurationSetSchema: Codable { try container.encode(name, forKey: .name) } } - diff --git a/Sources/Typesense/Models/Debug200Response.swift b/Sources/Typesense/Models/Debug200Response.swift index 8b825fd..d7284b1 100644 --- a/Sources/Typesense/Models/Debug200Response.swift +++ b/Sources/Typesense/Models/Debug200Response.swift @@ -29,4 +29,3 @@ public struct Debug200Response: Codable { try container.encodeIfPresent(version, forKey: .version) } } - diff --git a/Sources/Typesense/Models/DeleteDocuments200Response.swift b/Sources/Typesense/Models/DeleteDocuments200Response.swift index c992b56..00e00a1 100644 --- a/Sources/Typesense/Models/DeleteDocuments200Response.swift +++ b/Sources/Typesense/Models/DeleteDocuments200Response.swift @@ -29,4 +29,3 @@ public struct DeleteDocuments200Response: Codable { try container.encode(numDeleted, forKey: .numDeleted) } } - diff --git a/Sources/Typesense/Models/DeleteDocumentsParameters.swift b/Sources/Typesense/Models/DeleteDocumentsParameters.swift index f277651..6c6ca48 100644 --- a/Sources/Typesense/Models/DeleteDocumentsParameters.swift +++ b/Sources/Typesense/Models/DeleteDocumentsParameters.swift @@ -19,7 +19,7 @@ public struct DeleteDocumentsParameters: Codable { /** When true, removes all documents from the collection while preserving the collection and its schema. */ public var truncate: Bool? - public init(batchSize: Int? = nil, filterBy: String, ignoreNotFound: Bool? = nil, truncate: Bool? = nil) { + public init(filterBy: String, batchSize: Int? = nil, ignoreNotFound: Bool? = nil, truncate: Bool? = nil) { self.batchSize = batchSize self.filterBy = filterBy self.ignoreNotFound = ignoreNotFound @@ -43,4 +43,3 @@ public struct DeleteDocumentsParameters: Codable { try container.encodeIfPresent(truncate, forKey: .truncate) } } - diff --git a/Sources/Typesense/Models/DeleteStopwordsSet200Response.swift b/Sources/Typesense/Models/DeleteStopwordsSet200Response.swift index 4a2a3a5..2cb1c6e 100644 --- a/Sources/Typesense/Models/DeleteStopwordsSet200Response.swift +++ b/Sources/Typesense/Models/DeleteStopwordsSet200Response.swift @@ -29,4 +29,3 @@ public struct DeleteStopwordsSet200Response: Codable { try container.encode(id, forKey: .id) } } - diff --git a/Sources/Typesense/Models/ExportDocumentsParameters.swift b/Sources/Typesense/Models/ExportDocumentsParameters.swift index da5f4ae..35036f1 100644 --- a/Sources/Typesense/Models/ExportDocumentsParameters.swift +++ b/Sources/Typesense/Models/ExportDocumentsParameters.swift @@ -40,4 +40,3 @@ public struct ExportDocumentsParameters: Codable { try container.encodeIfPresent(includeFields, forKey: .includeFields) } } - diff --git a/Sources/Typesense/Models/FacetCounts.swift b/Sources/Typesense/Models/FacetCounts.swift index b2b8500..a754e2a 100644 --- a/Sources/Typesense/Models/FacetCounts.swift +++ b/Sources/Typesense/Models/FacetCounts.swift @@ -37,4 +37,3 @@ public struct FacetCounts: Codable { try container.encodeIfPresent(stats, forKey: .stats) } } - diff --git a/Sources/Typesense/Models/FacetCountsCountsInner.swift b/Sources/Typesense/Models/FacetCountsCountsInner.swift index 31c658e..7eea689 100644 --- a/Sources/Typesense/Models/FacetCountsCountsInner.swift +++ b/Sources/Typesense/Models/FacetCountsCountsInner.swift @@ -41,4 +41,3 @@ public struct FacetCountsCountsInner: Codable { try container.encodeIfPresent(value, forKey: .value) } } - diff --git a/Sources/Typesense/Models/FacetCountsStats.swift b/Sources/Typesense/Models/FacetCountsStats.swift index 56649a8..ab04324 100644 --- a/Sources/Typesense/Models/FacetCountsStats.swift +++ b/Sources/Typesense/Models/FacetCountsStats.swift @@ -45,4 +45,3 @@ public struct FacetCountsStats: Codable { try container.encodeIfPresent(totalValues, forKey: .totalValues) } } - diff --git a/Sources/Typesense/Models/Field.swift b/Sources/Typesense/Models/Field.swift index b2cee30..27eebb0 100644 --- a/Sources/Typesense/Models/Field.swift +++ b/Sources/Typesense/Models/Field.swift @@ -40,7 +40,7 @@ public struct Field: Codable { /** The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. */ public var vecDist: String? - public init(drop: Bool? = nil, embed: FieldEmbed? = nil, facet: Bool? = nil, index: Bool? = true, _infix: Bool? = false, locale: String? = nil, name: String, numDim: Int? = nil, _optional: Bool? = nil, rangeIndex: Bool? = nil, reference: String? = nil, sort: Bool? = nil, stem: Bool? = nil, stemDictionary: String? = nil, store: Bool? = nil, symbolsToIndex: [String]? = nil, tokenSeparators: [String]? = nil, type: String, vecDist: String? = nil) { + public init(name: String, type: String, drop: Bool? = nil, embed: FieldEmbed? = nil, facet: Bool? = nil, index: Bool? = true, _infix: Bool? = false, locale: String? = nil, numDim: Int? = nil, _optional: Bool? = nil, rangeIndex: Bool? = nil, reference: String? = nil, sort: Bool? = nil, stem: Bool? = nil, stemDictionary: String? = nil, store: Bool? = nil, symbolsToIndex: [String]? = nil, tokenSeparators: [String]? = nil, vecDist: String? = nil) { self.drop = drop self.embed = embed self.facet = facet @@ -109,4 +109,3 @@ public struct Field: Codable { try container.encodeIfPresent(vecDist, forKey: .vecDist) } } - diff --git a/Sources/Typesense/Models/FieldEmbed.swift b/Sources/Typesense/Models/FieldEmbed.swift index bf3d00a..93295ab 100644 --- a/Sources/Typesense/Models/FieldEmbed.swift +++ b/Sources/Typesense/Models/FieldEmbed.swift @@ -33,4 +33,3 @@ public struct FieldEmbed: Codable { try container.encode(modelConfig, forKey: .modelConfig) } } - diff --git a/Sources/Typesense/Models/FieldEmbedModelConfig.swift b/Sources/Typesense/Models/FieldEmbedModelConfig.swift index 712392f..16c8b77 100644 --- a/Sources/Typesense/Models/FieldEmbedModelConfig.swift +++ b/Sources/Typesense/Models/FieldEmbedModelConfig.swift @@ -23,7 +23,7 @@ public struct FieldEmbedModelConfig: Codable { public var refreshToken: String? public var url: String? - public init(accessToken: String? = nil, apiKey: String? = nil, clientId: String? = nil, clientSecret: String? = nil, indexingPrefix: String? = nil, modelName: String, projectId: String? = nil, queryPrefix: String? = nil, refreshToken: String? = nil, url: String? = nil) { + public init(modelName: String, accessToken: String? = nil, apiKey: String? = nil, clientId: String? = nil, clientSecret: String? = nil, indexingPrefix: String? = nil, projectId: String? = nil, queryPrefix: String? = nil, refreshToken: String? = nil, url: String? = nil) { self.accessToken = accessToken self.apiKey = apiKey self.clientId = clientId @@ -65,4 +65,3 @@ public struct FieldEmbedModelConfig: Codable { try container.encodeIfPresent(url, forKey: .url) } } - diff --git a/Sources/Typesense/Models/GetCollectionsParameters.swift b/Sources/Typesense/Models/GetCollectionsParameters.swift index 52882cd..5ad74d9 100644 --- a/Sources/Typesense/Models/GetCollectionsParameters.swift +++ b/Sources/Typesense/Models/GetCollectionsParameters.swift @@ -40,4 +40,3 @@ public struct GetCollectionsParameters: Codable { try container.encodeIfPresent(offset, forKey: .offset) } } - diff --git a/Sources/Typesense/Models/HealthStatus.swift b/Sources/Typesense/Models/HealthStatus.swift index 168ea87..171f145 100644 --- a/Sources/Typesense/Models/HealthStatus.swift +++ b/Sources/Typesense/Models/HealthStatus.swift @@ -29,4 +29,3 @@ public struct HealthStatus: Codable { try container.encode(ok, forKey: .ok) } } - diff --git a/Sources/Typesense/Models/ImportDocumentsParameters.swift b/Sources/Typesense/Models/ImportDocumentsParameters.swift index 70b23cc..aa6a49e 100644 --- a/Sources/Typesense/Models/ImportDocumentsParameters.swift +++ b/Sources/Typesense/Models/ImportDocumentsParameters.swift @@ -50,4 +50,3 @@ public struct ImportDocumentsParameters: Codable { try container.encodeIfPresent(returnId, forKey: .returnId) } } - diff --git a/Sources/Typesense/Models/ListStemmingDictionaries200Response.swift b/Sources/Typesense/Models/ListStemmingDictionaries200Response.swift index 296dcd1..08c1cf7 100644 --- a/Sources/Typesense/Models/ListStemmingDictionaries200Response.swift +++ b/Sources/Typesense/Models/ListStemmingDictionaries200Response.swift @@ -29,4 +29,3 @@ public struct ListStemmingDictionaries200Response: Codable { try container.encodeIfPresent(dictionaries, forKey: .dictionaries) } } - diff --git a/Sources/Typesense/Models/MultiSearchCollectionParameters.swift b/Sources/Typesense/Models/MultiSearchCollectionParameters.swift index 74d18ca..0e381c0 100644 --- a/Sources/Typesense/Models/MultiSearchCollectionParameters.swift +++ b/Sources/Typesense/Models/MultiSearchCollectionParameters.swift @@ -359,4 +359,3 @@ public struct MultiSearchCollectionParameters: Codable { try container.encodeIfPresent(xTypesenseApiKey, forKey: .xTypesenseApiKey) } } - diff --git a/Sources/Typesense/Models/MultiSearchParameters.swift b/Sources/Typesense/Models/MultiSearchParameters.swift index 9ccfeea..29b26ae 100644 --- a/Sources/Typesense/Models/MultiSearchParameters.swift +++ b/Sources/Typesense/Models/MultiSearchParameters.swift @@ -345,4 +345,3 @@ public struct MultiSearchParameters: Codable { try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) } } - diff --git a/Sources/Typesense/Models/MultiSearchResult.swift b/Sources/Typesense/Models/MultiSearchResult.swift index f2c9fc1..1d8c445 100644 --- a/Sources/Typesense/Models/MultiSearchResult.swift +++ b/Sources/Typesense/Models/MultiSearchResult.swift @@ -13,9 +13,9 @@ import AnyCodable public struct MultiSearchResult: Codable { public var conversation: SearchResultConversation? - public var results: [MultiSearchResultItem]? + public var results: [MultiSearchResultItem] - public init(conversation: SearchResultConversation? = nil, results: [MultiSearchResultItem]?) { + public init(results: [MultiSearchResultItem], conversation: SearchResultConversation? = nil) { self.conversation = conversation self.results = results } @@ -33,4 +33,3 @@ public struct MultiSearchResult: Codable { try container.encode(results, forKey: .results) } } - diff --git a/Sources/Typesense/Models/MultiSearchResultItem.swift b/Sources/Typesense/Models/MultiSearchResultItem.swift index 85d78b4..e58b13d 100644 --- a/Sources/Typesense/Models/MultiSearchResultItem.swift +++ b/Sources/Typesense/Models/MultiSearchResultItem.swift @@ -95,4 +95,3 @@ public struct MultiSearchResultItem: Codable { try container.encodeIfPresent(error, forKey: .error) } } - diff --git a/Sources/Typesense/Models/MultiSearchSearchesParameter.swift b/Sources/Typesense/Models/MultiSearchSearchesParameter.swift index b21185f..7dca9a3 100644 --- a/Sources/Typesense/Models/MultiSearchSearchesParameter.swift +++ b/Sources/Typesense/Models/MultiSearchSearchesParameter.swift @@ -34,4 +34,3 @@ public struct MultiSearchSearchesParameter: Codable { try container.encodeIfPresent(union, forKey: .union) } } - diff --git a/Sources/Typesense/Models/NLSearchModelBase.swift b/Sources/Typesense/Models/NLSearchModelBase.swift index 5f37a11..6af36c8 100644 --- a/Sources/Typesense/Models/NLSearchModelBase.swift +++ b/Sources/Typesense/Models/NLSearchModelBase.swift @@ -115,4 +115,3 @@ public struct NLSearchModelBase: Codable { try container.encodeIfPresent(topP, forKey: .topP) } } - diff --git a/Sources/Typesense/Models/NLSearchModelCreateSchema.swift b/Sources/Typesense/Models/NLSearchModelCreateSchema.swift index f7bbf95..ddb4db3 100644 --- a/Sources/Typesense/Models/NLSearchModelCreateSchema.swift +++ b/Sources/Typesense/Models/NLSearchModelCreateSchema.swift @@ -120,4 +120,3 @@ public struct NLSearchModelCreateSchema: Codable { try container.encodeIfPresent(id, forKey: .id) } } - diff --git a/Sources/Typesense/Models/NLSearchModelDeleteSchema.swift b/Sources/Typesense/Models/NLSearchModelDeleteSchema.swift index 2439beb..7e10ecd 100644 --- a/Sources/Typesense/Models/NLSearchModelDeleteSchema.swift +++ b/Sources/Typesense/Models/NLSearchModelDeleteSchema.swift @@ -30,4 +30,3 @@ public struct NLSearchModelDeleteSchema: Codable { try container.encode(id, forKey: .id) } } - diff --git a/Sources/Typesense/Models/NLSearchModelSchema.swift b/Sources/Typesense/Models/NLSearchModelSchema.swift index 34f633d..03843f6 100644 --- a/Sources/Typesense/Models/NLSearchModelSchema.swift +++ b/Sources/Typesense/Models/NLSearchModelSchema.swift @@ -51,7 +51,7 @@ public struct NLSearchModelSchema: Codable { /** ID of the NL search model */ public var id: String - public init(accessToken: String? = nil, accountId: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, apiVersion: String? = nil, clientId: String? = nil, clientSecret: String? = nil, maxBytes: Int? = nil, maxOutputTokens: Int? = nil, modelName: String? = nil, projectId: String? = nil, refreshToken: String? = nil, region: String? = nil, stopSequences: [String]? = nil, systemPrompt: String? = nil, temperature: Double? = nil, topK: Int? = nil, topP: Double? = nil, id: String) { + public init(id: String, accessToken: String? = nil, accountId: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, apiVersion: String? = nil, clientId: String? = nil, clientSecret: String? = nil, maxBytes: Int? = nil, maxOutputTokens: Int? = nil, modelName: String? = nil, projectId: String? = nil, refreshToken: String? = nil, region: String? = nil, stopSequences: [String]? = nil, systemPrompt: String? = nil, temperature: Double? = nil, topK: Int? = nil, topP: Double? = nil) { self.accessToken = accessToken self.accountId = accountId self.apiKey = apiKey @@ -120,4 +120,3 @@ public struct NLSearchModelSchema: Codable { try container.encode(id, forKey: .id) } } - diff --git a/Sources/Typesense/Models/PresetDeleteSchema.swift b/Sources/Typesense/Models/PresetDeleteSchema.swift index aa59c84..d09eb27 100644 --- a/Sources/Typesense/Models/PresetDeleteSchema.swift +++ b/Sources/Typesense/Models/PresetDeleteSchema.swift @@ -29,4 +29,3 @@ public struct PresetDeleteSchema: Codable { try container.encode(name, forKey: .name) } } - diff --git a/Sources/Typesense/Models/PresetSchema.swift b/Sources/Typesense/Models/PresetSchema.swift index 8d47174..3048b73 100644 --- a/Sources/Typesense/Models/PresetSchema.swift +++ b/Sources/Typesense/Models/PresetSchema.swift @@ -33,4 +33,3 @@ public struct PresetSchema: Codable { try container.encode(name, forKey: .name) } } - diff --git a/Sources/Typesense/Models/PresetUpsertSchema.swift b/Sources/Typesense/Models/PresetUpsertSchema.swift index 08bdbb1..0c6fd9a 100644 --- a/Sources/Typesense/Models/PresetUpsertSchema.swift +++ b/Sources/Typesense/Models/PresetUpsertSchema.swift @@ -29,4 +29,3 @@ public struct PresetUpsertSchema: Codable { try container.encode(value, forKey: .value) } } - diff --git a/Sources/Typesense/Models/PresetsRetrieveSchema.swift b/Sources/Typesense/Models/PresetsRetrieveSchema.swift index 94c7cf2..9a69023 100644 --- a/Sources/Typesense/Models/PresetsRetrieveSchema.swift +++ b/Sources/Typesense/Models/PresetsRetrieveSchema.swift @@ -29,4 +29,3 @@ public struct PresetsRetrieveSchema: Codable { try container.encode(presets, forKey: .presets) } } - diff --git a/Sources/Typesense/Models/SchemaChangeStatus.swift b/Sources/Typesense/Models/SchemaChangeStatus.swift index da9155b..c57b459 100644 --- a/Sources/Typesense/Models/SchemaChangeStatus.swift +++ b/Sources/Typesense/Models/SchemaChangeStatus.swift @@ -40,4 +40,3 @@ public struct SchemaChangeStatus: Codable { try container.encodeIfPresent(validatedDocs, forKey: .validatedDocs) } } - diff --git a/Sources/Typesense/Models/SearchGroupedHit.swift b/Sources/Typesense/Models/SearchGroupedHit.swift index ac2ec9e..07974a7 100644 --- a/Sources/Typesense/Models/SearchGroupedHit.swift +++ b/Sources/Typesense/Models/SearchGroupedHit.swift @@ -17,7 +17,7 @@ public struct SearchGroupedHit: Codable { /** The documents that matched the search query */ public var hits: [SearchResultHit]? - public init(found: Int? = nil, groupKey: [AnyCodable], hits: [SearchResultHit]?) { + public init(groupKey: [AnyCodable], hits: [SearchResultHit]?, found: Int? = nil) { self.found = found self.groupKey = groupKey self.hits = hits @@ -38,4 +38,3 @@ public struct SearchGroupedHit: Codable { try container.encode(hits, forKey: .hits) } } - diff --git a/Sources/Typesense/Models/SearchHighlight.swift b/Sources/Typesense/Models/SearchHighlight.swift index ae2a072..f02014a 100644 --- a/Sources/Typesense/Models/SearchHighlight.swift +++ b/Sources/Typesense/Models/SearchHighlight.swift @@ -58,4 +58,3 @@ public struct SearchHighlight: Codable { try container.encodeIfPresent(values, forKey: .values) } } - diff --git a/Sources/Typesense/Models/SearchParameters.swift b/Sources/Typesense/Models/SearchParameters.swift index e4dae94..87d1462 100644 --- a/Sources/Typesense/Models/SearchParameters.swift +++ b/Sources/Typesense/Models/SearchParameters.swift @@ -379,4 +379,3 @@ public struct SearchParameters: Codable { try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) } } - diff --git a/Sources/Typesense/Models/SearchRequestParams.swift b/Sources/Typesense/Models/SearchRequestParams.swift index c6c0274..8426050 100644 --- a/Sources/Typesense/Models/SearchRequestParams.swift +++ b/Sources/Typesense/Models/SearchRequestParams.swift @@ -41,4 +41,3 @@ public struct SearchRequestParams: Codable { try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) } } - diff --git a/Sources/Typesense/Models/SearchRequestParamsVoiceQuery.swift b/Sources/Typesense/Models/SearchRequestParamsVoiceQuery.swift index be6044e..b10322b 100644 --- a/Sources/Typesense/Models/SearchRequestParamsVoiceQuery.swift +++ b/Sources/Typesense/Models/SearchRequestParamsVoiceQuery.swift @@ -29,4 +29,3 @@ public struct SearchRequestParamsVoiceQuery: Codable { try container.encodeIfPresent(transcribedQuery, forKey: .transcribedQuery) } } - diff --git a/Sources/Typesense/Models/SearchResult.swift b/Sources/Typesense/Models/SearchResult.swift index 7711510..723e779 100644 --- a/Sources/Typesense/Models/SearchResult.swift +++ b/Sources/Typesense/Models/SearchResult.swift @@ -85,4 +85,3 @@ public struct SearchResult: Codable { try container.encodeIfPresent(unionRequestParams, forKey: .unionRequestParams) } } - diff --git a/Sources/Typesense/Models/SearchResultConversation.swift b/Sources/Typesense/Models/SearchResultConversation.swift index 2e905d9..c96db1a 100644 --- a/Sources/Typesense/Models/SearchResultConversation.swift +++ b/Sources/Typesense/Models/SearchResultConversation.swift @@ -41,4 +41,3 @@ public struct SearchResultConversation: Codable { try container.encode(query, forKey: .query) } } - diff --git a/Sources/Typesense/Models/SearchResultHit.swift b/Sources/Typesense/Models/SearchResultHit.swift index 6db2e34..ca1f1dd 100644 --- a/Sources/Typesense/Models/SearchResultHit.swift +++ b/Sources/Typesense/Models/SearchResultHit.swift @@ -67,4 +67,3 @@ public struct SearchResultHit: Codable { try container.encodeIfPresent(vectorDistance, forKey: .vectorDistance) } } - diff --git a/Sources/Typesense/Models/SearchResultHitHybridSearchInfo.swift b/Sources/Typesense/Models/SearchResultHitHybridSearchInfo.swift index 51d5219..04f8d32 100644 --- a/Sources/Typesense/Models/SearchResultHitHybridSearchInfo.swift +++ b/Sources/Typesense/Models/SearchResultHitHybridSearchInfo.swift @@ -31,4 +31,3 @@ public struct SearchResultHitHybridSearchInfo: Codable { try container.encodeIfPresent(rankFusionScore, forKey: .rankFusionScore) } } - diff --git a/Sources/Typesense/Models/SearchResultHitTextMatchInfo.swift b/Sources/Typesense/Models/SearchResultHitTextMatchInfo.swift index a42121e..9ecf7a3 100644 --- a/Sources/Typesense/Models/SearchResultHitTextMatchInfo.swift +++ b/Sources/Typesense/Models/SearchResultHitTextMatchInfo.swift @@ -53,4 +53,3 @@ public struct SearchResultHitTextMatchInfo: Codable { try container.encodeIfPresent(typoPrefixScore, forKey: .typoPrefixScore) } } - diff --git a/Sources/Typesense/Models/SearchSynonym.swift b/Sources/Typesense/Models/SearchSynonym.swift index 394a4a4..2dfd805 100644 --- a/Sources/Typesense/Models/SearchSynonym.swift +++ b/Sources/Typesense/Models/SearchSynonym.swift @@ -22,7 +22,7 @@ public struct SearchSynonym: Codable { public var synonyms: [String] public var id: String - public init(locale: String? = nil, root: String? = nil, symbolsToIndex: [String]? = nil, synonyms: [String], id: String) { + public init(synonyms: [String], id: String, locale: String? = nil, root: String? = nil, symbolsToIndex: [String]? = nil) { self.locale = locale self.root = root self.symbolsToIndex = symbolsToIndex @@ -49,4 +49,3 @@ public struct SearchSynonym: Codable { try container.encode(id, forKey: .id) } } - diff --git a/Sources/Typesense/Models/SearchSynonymDeleteResponse.swift b/Sources/Typesense/Models/SearchSynonymDeleteResponse.swift index 3dd313a..52a76ee 100644 --- a/Sources/Typesense/Models/SearchSynonymDeleteResponse.swift +++ b/Sources/Typesense/Models/SearchSynonymDeleteResponse.swift @@ -30,4 +30,3 @@ public struct SearchSynonymDeleteResponse: Codable { try container.encode(id, forKey: .id) } } - diff --git a/Sources/Typesense/Models/SearchSynonymSchema.swift b/Sources/Typesense/Models/SearchSynonymSchema.swift index 2db0379..709feee 100644 --- a/Sources/Typesense/Models/SearchSynonymSchema.swift +++ b/Sources/Typesense/Models/SearchSynonymSchema.swift @@ -21,7 +21,7 @@ public struct SearchSynonymSchema: Codable { /** Array of words that should be considered as synonyms. */ public var synonyms: [String] - public init(locale: String? = nil, root: String? = nil, symbolsToIndex: [String]? = nil, synonyms: [String]) { + public init(synonyms: [String], locale: String? = nil, root: String? = nil, symbolsToIndex: [String]? = nil) { self.locale = locale self.root = root self.symbolsToIndex = symbolsToIndex @@ -45,4 +45,3 @@ public struct SearchSynonymSchema: Codable { try container.encode(synonyms, forKey: .synonyms) } } - diff --git a/Sources/Typesense/Models/SearchSynonymsResponse.swift b/Sources/Typesense/Models/SearchSynonymsResponse.swift index e665857..16bc477 100644 --- a/Sources/Typesense/Models/SearchSynonymsResponse.swift +++ b/Sources/Typesense/Models/SearchSynonymsResponse.swift @@ -29,4 +29,3 @@ public struct SearchSynonymsResponse: Codable { try container.encode(synonyms, forKey: .synonyms) } } - diff --git a/Sources/Typesense/Models/StemmingDictionary.swift b/Sources/Typesense/Models/StemmingDictionary.swift index 7902ea8..69a896d 100644 --- a/Sources/Typesense/Models/StemmingDictionary.swift +++ b/Sources/Typesense/Models/StemmingDictionary.swift @@ -35,4 +35,3 @@ public struct StemmingDictionary: Codable { try container.encode(words, forKey: .words) } } - diff --git a/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift b/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift index 1000478..724bc02 100644 --- a/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift +++ b/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift @@ -35,4 +35,3 @@ public struct StemmingDictionaryWordsInner: Codable { try container.encode(word, forKey: .word) } } - diff --git a/Sources/Typesense/Models/StopwordsSetRetrieveSchema.swift b/Sources/Typesense/Models/StopwordsSetRetrieveSchema.swift index c5e2b9a..34c0ed9 100644 --- a/Sources/Typesense/Models/StopwordsSetRetrieveSchema.swift +++ b/Sources/Typesense/Models/StopwordsSetRetrieveSchema.swift @@ -29,4 +29,3 @@ public struct StopwordsSetRetrieveSchema: Codable { try container.encode(stopwords, forKey: .stopwords) } } - diff --git a/Sources/Typesense/Models/StopwordsSetSchema.swift b/Sources/Typesense/Models/StopwordsSetSchema.swift index 19fd21a..b80e390 100644 --- a/Sources/Typesense/Models/StopwordsSetSchema.swift +++ b/Sources/Typesense/Models/StopwordsSetSchema.swift @@ -16,7 +16,7 @@ public struct StopwordsSetSchema: Codable { public var locale: String? public var stopwords: [String] - public init(id: String, locale: String? = nil, stopwords: [String]) { + public init(id: String, stopwords: [String], locale: String? = nil) { self.id = id self.locale = locale self.stopwords = stopwords @@ -37,4 +37,3 @@ public struct StopwordsSetSchema: Codable { try container.encode(stopwords, forKey: .stopwords) } } - diff --git a/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift b/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift index 4c7c4e4..8a99a4c 100644 --- a/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift +++ b/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift @@ -15,7 +15,7 @@ public struct StopwordsSetUpsertSchema: Codable { public var locale: String? public var stopwords: [String] - public init(locale: String? = nil, stopwords: [String]) { + public init(stopwords: [String], locale: String? = nil) { self.locale = locale self.stopwords = stopwords } @@ -33,4 +33,3 @@ public struct StopwordsSetUpsertSchema: Codable { try container.encode(stopwords, forKey: .stopwords) } } - diff --git a/Sources/Typesense/Models/StopwordsSetsRetrieveAllSchema.swift b/Sources/Typesense/Models/StopwordsSetsRetrieveAllSchema.swift index 5c28e17..43d7bc8 100644 --- a/Sources/Typesense/Models/StopwordsSetsRetrieveAllSchema.swift +++ b/Sources/Typesense/Models/StopwordsSetsRetrieveAllSchema.swift @@ -29,4 +29,3 @@ public struct StopwordsSetsRetrieveAllSchema: Codable { try container.encode(stopwords, forKey: .stopwords) } } - diff --git a/Sources/Typesense/Models/SuccessStatus.swift b/Sources/Typesense/Models/SuccessStatus.swift index 832d7ad..15a126f 100644 --- a/Sources/Typesense/Models/SuccessStatus.swift +++ b/Sources/Typesense/Models/SuccessStatus.swift @@ -29,4 +29,3 @@ public struct SuccessStatus: Codable { try container.encode(success, forKey: .success) } } - diff --git a/Sources/Typesense/Models/SynonymItemDeleteSchema.swift b/Sources/Typesense/Models/SynonymItemDeleteSchema.swift index 45323f4..89132d9 100644 --- a/Sources/Typesense/Models/SynonymItemDeleteSchema.swift +++ b/Sources/Typesense/Models/SynonymItemDeleteSchema.swift @@ -30,4 +30,3 @@ public struct SynonymItemDeleteSchema: Codable { try container.encode(id, forKey: .id) } } - diff --git a/Sources/Typesense/Models/SynonymItemSchema.swift b/Sources/Typesense/Models/SynonymItemSchema.swift index 8a50178..4aadd59 100644 --- a/Sources/Typesense/Models/SynonymItemSchema.swift +++ b/Sources/Typesense/Models/SynonymItemSchema.swift @@ -23,7 +23,7 @@ public struct SynonymItemSchema: Codable { /** Array of words that should be considered as synonyms */ public var synonyms: [String] - public init(id: String, locale: String? = nil, root: String? = nil, symbolsToIndex: [String]? = nil, synonyms: [String]) { + public init(id: String, synonyms: [String], locale: String? = nil, root: String? = nil, symbolsToIndex: [String]? = nil) { self.id = id self.locale = locale self.root = root @@ -50,4 +50,3 @@ public struct SynonymItemSchema: Codable { try container.encode(synonyms, forKey: .synonyms) } } - diff --git a/Sources/Typesense/Models/SynonymSetCreateSchema.swift b/Sources/Typesense/Models/SynonymSetCreateSchema.swift index 9656b05..739de82 100644 --- a/Sources/Typesense/Models/SynonymSetCreateSchema.swift +++ b/Sources/Typesense/Models/SynonymSetCreateSchema.swift @@ -30,4 +30,3 @@ public struct SynonymSetCreateSchema: Codable { try container.encode(items, forKey: .items) } } - diff --git a/Sources/Typesense/Models/SynonymSetDeleteSchema.swift b/Sources/Typesense/Models/SynonymSetDeleteSchema.swift index db3b07c..c2c1e89 100644 --- a/Sources/Typesense/Models/SynonymSetDeleteSchema.swift +++ b/Sources/Typesense/Models/SynonymSetDeleteSchema.swift @@ -30,4 +30,3 @@ public struct SynonymSetDeleteSchema: Codable { try container.encode(name, forKey: .name) } } - diff --git a/Sources/Typesense/Models/SynonymSetSchema.swift b/Sources/Typesense/Models/SynonymSetSchema.swift index d295741..82859d3 100644 --- a/Sources/Typesense/Models/SynonymSetSchema.swift +++ b/Sources/Typesense/Models/SynonymSetSchema.swift @@ -35,4 +35,3 @@ public struct SynonymSetSchema: Codable { try container.encode(name, forKey: .name) } } - diff --git a/Sources/Typesense/Models/SynonymSetsRetrieveSchema.swift b/Sources/Typesense/Models/SynonymSetsRetrieveSchema.swift index 2cef89e..20171d7 100644 --- a/Sources/Typesense/Models/SynonymSetsRetrieveSchema.swift +++ b/Sources/Typesense/Models/SynonymSetsRetrieveSchema.swift @@ -30,4 +30,3 @@ public struct SynonymSetsRetrieveSchema: Codable { try container.encode(synonymSets, forKey: .synonymSets) } } - diff --git a/Sources/Typesense/Models/ToggleSlowRequestLogRequest.swift b/Sources/Typesense/Models/ToggleSlowRequestLogRequest.swift index e5a6090..3071831 100644 --- a/Sources/Typesense/Models/ToggleSlowRequestLogRequest.swift +++ b/Sources/Typesense/Models/ToggleSlowRequestLogRequest.swift @@ -29,4 +29,3 @@ public struct ToggleSlowRequestLogRequest: Codable { try container.encode(logSlowRequestsTimeMs, forKey: .logSlowRequestsTimeMs) } } - diff --git a/Sources/Typesense/Models/UpdateDocuments200Response.swift b/Sources/Typesense/Models/UpdateDocuments200Response.swift index f388aed..f451120 100644 --- a/Sources/Typesense/Models/UpdateDocuments200Response.swift +++ b/Sources/Typesense/Models/UpdateDocuments200Response.swift @@ -30,4 +30,3 @@ public struct UpdateDocuments200Response: Codable { try container.encode(numUpdated, forKey: .numUpdated) } } - diff --git a/Sources/Typesense/Models/UpdateDocumentsParameters.swift b/Sources/Typesense/Models/UpdateDocumentsParameters.swift index dd2d4a2..75f8422 100644 --- a/Sources/Typesense/Models/UpdateDocumentsParameters.swift +++ b/Sources/Typesense/Models/UpdateDocumentsParameters.swift @@ -29,4 +29,3 @@ public struct UpdateDocumentsParameters: Codable { try container.encodeIfPresent(filterBy, forKey: .filterBy) } } - diff --git a/Sources/Typesense/Models/VoiceQueryModelCollectionConfig.swift b/Sources/Typesense/Models/VoiceQueryModelCollectionConfig.swift index 963e6d5..a8d6dd9 100644 --- a/Sources/Typesense/Models/VoiceQueryModelCollectionConfig.swift +++ b/Sources/Typesense/Models/VoiceQueryModelCollectionConfig.swift @@ -30,4 +30,3 @@ public struct VoiceQueryModelCollectionConfig: Codable { try container.encodeIfPresent(modelName, forKey: .modelName) } } - diff --git a/Tasks/AddVendorAttributes.swift b/Tasks/AddVendorAttributes.swift index f948746..e31d46b 100644 --- a/Tasks/AddVendorAttributes.swift +++ b/Tasks/AddVendorAttributes.swift @@ -33,7 +33,7 @@ func addVendorAttributes(_ doc: inout [String: Any]) throws { try attrs.schemaFieldTypeOverrides( schema: "MultiSearchResult", - overrides: [("results", "[MultiSearchResultItem]?")] + overrides: [("results", "[MultiSearchResultItem]")] ) // Save changes back to the inout parameter diff --git a/Tests/TypesenseTests/AnalyticsTests.swift b/Tests/TypesenseTests/AnalyticsTests.swift index b2d035c..c6f1e33 100644 --- a/Tests/TypesenseTests/AnalyticsTests.swift +++ b/Tests/TypesenseTests/AnalyticsTests.swift @@ -3,7 +3,14 @@ import XCTest final class AnalyticsTests: XCTestCase { override func setUp() async throws { - try await createCollection() + let _ = try await utilClient.collections().create(schema: CollectionSchema(fields: [ + Field(name:"q", type: "string"), + Field(name:"count", type: "int32") + ], name: "product_queries")) + let _ = try await utilClient.collections().create(schema: CollectionSchema(fields: [ + Field(name:"name", type: "string"), + Field(name:"in_stock", type: "int32") + ], name: "products")) try await createAnalyticRule() } @@ -14,15 +21,15 @@ final class AnalyticsTests: XCTestCase { func testAnalyticsRuleCreate() async { let schema = AnalyticsRuleCreate( - name: "test_rule", - type: .popularQueries, collection: "products", eventType: "search", - ruleTag: "homepage", + name: "test-rule", + type: .popularQueries, params: AnalyticsRuleCreateParams( destinationCollection: "product_queries", limit: 100, - ) + ), + ruleTag: "homepage", ) do { let (rule, _) = try await utilClient.analytics().rules().create(schema) @@ -42,26 +49,26 @@ final class AnalyticsTests: XCTestCase { func testAnalyticsRuleCreateMany() async { let schema1 = AnalyticsRuleCreate( - name: "test_rule_1", - type: .popularQueries, - collection: "products", + collection: "test_rule_1", eventType: "search", - ruleTag: "homepage", + name: "products", + type: .popularQueries, params: AnalyticsRuleCreateParams( destinationCollection: "product_queries", limit: 100, - ) + ), + ruleTag: "homepage" ) let schema2 = AnalyticsRuleCreate( - name: "test_rule_2", - type: .popularQueries, collection: "products", eventType: "any", - ruleTag: "homepage", + name: "test_rule_2", + type: .popularQueries, params: AnalyticsRuleCreateParams( destinationCollection: "product_queries", limit: 100, - ) + ), + ruleTag: "homepage", ) do { @@ -126,12 +133,12 @@ final class AnalyticsTests: XCTestCase { func testAnalyticsEventsCreate() async { do { let (res, _) = try await client.analytics().events().create( AnalyticsEvent( - name: "product_queries_aggregation", - eventType: "popular_queries", data: AnalyticsEventData( - userId: "111112", q: "nike shoes", - ) + userId: "111112", + ), + eventType: "popular_queries", + name: "product_queries_aggregation", )) guard let validRes = res else { throw DataError.dataNotFound diff --git a/Tests/TypesenseTests/ApiKeyTests.swift b/Tests/TypesenseTests/ApiKeyTests.swift index 5a72553..1f0e375 100644 --- a/Tests/TypesenseTests/ApiKeyTests.swift +++ b/Tests/TypesenseTests/ApiKeyTests.swift @@ -8,7 +8,7 @@ final class ApiKeyTests: XCTestCase { func testKeyCreate() async { do { - let adminKey = ApiKeySchema(description: "Test key with all privileges", actions: ["*"], collections: ["*"]) + let adminKey = ApiKeySchema(actions: ["*"], collections: ["*"], description: "Test key with all privileges", ) let (data, _) = try await client.keys().create(adminKey) XCTAssertNotNil(data) guard let validData = data else { diff --git a/Tests/TypesenseTests/CollectionTests.swift b/Tests/TypesenseTests/CollectionTests.swift index 27fbdab..f1791f6 100644 --- a/Tests/TypesenseTests/CollectionTests.swift +++ b/Tests/TypesenseTests/CollectionTests.swift @@ -7,9 +7,16 @@ final class CollectionTests: XCTestCase { } func testCollectionCreate() async { - let schema = CollectionSchema(name: "companies", fields: [Field(name: "company_name", type: "string"), Field(name: "num_employees", type: "int32"), Field(name: "country", type: "string", facet: true)], defaultSortingField: "num_employees") + let schema = CollectionSchema( + fields: [ + Field(name: "company_name", type: "string"), + Field(name: "num_employees", type: "int32"), + Field(name: "country", type: "string", facet: true) + ], + name: "companies", + defaultSortingField: "num_employees") do { - let (collResp, _) = try await client.collections.create(schema: schema) + let (collResp, _) = try await client.collections().create(schema: schema) XCTAssertNotNil(collResp) guard let validData = collResp else { throw DataError.dataNotFound @@ -44,7 +51,7 @@ final class CollectionTests: XCTestCase { func testCollectionRetrieveAll() async { do { try await createCollection() - let (collResp, _) = try await client.collections.retrieveAll() + let (collResp, _) = try await client.collections().retrieveAll() XCTAssertNotNil(collResp) guard let validData = collResp else { throw DataError.dataNotFound diff --git a/Tests/TypesenseTests/ConversationModelTests.swift b/Tests/TypesenseTests/ConversationModelTests.swift index 13fd289..a35bbde 100644 --- a/Tests/TypesenseTests/ConversationModelTests.swift +++ b/Tests/TypesenseTests/ConversationModelTests.swift @@ -4,13 +4,13 @@ import XCTest final class ConversationModelTests: XCTestCase { func testConversationModelsCreate() async { let schema = ConversationModelCreateSchema( - id: "conv-model-1", + historyCollection: "conversation_store", + maxBytes: 16384, modelName: "test/gpt-3.5-turbo", apiKey: "sk", - historyCollection: "conversation_store", + id: "conv-model-1", systemPrompt: "You are an assistant for question-answering.", ttl: 123, - maxBytes: 16384 ) do { try await createConversationCollection() diff --git a/Tests/TypesenseTests/DocumentTests.swift b/Tests/TypesenseTests/DocumentTests.swift index 7c4cf75..c85de91 100644 --- a/Tests/TypesenseTests/DocumentTests.swift +++ b/Tests/TypesenseTests/DocumentTests.swift @@ -85,7 +85,7 @@ final class DocumentTests: XCTestCase { try await createDocument() let (data, _) = try await client.collection(name: "companies").documents().update( document: ["country": "Spain"], - options: UpdateDocumentsByFilterParameters(filterBy: "num_employees:>1000") + options: UpdateDocumentsParameters(filterBy: "num_employees:>1000") ) guard let validData = data else { throw DataError.dataNotFound @@ -172,7 +172,7 @@ final class DocumentTests: XCTestCase { } func testDocumentSearch() async { - let searchParams = SearchParameters(q: "*", queryBy: "company_name", page: 0, groupBy: "country", groupLimit: 1) + let searchParams = SearchParameters(groupBy: "country", groupLimit: 1, page: 0, q: "*", queryBy: "company_name") do { try await createDocument() @@ -197,7 +197,7 @@ final class DocumentTests: XCTestCase { } func testDocumentSearchReturnRawData() async { - let searchParams = SearchParameters(q: "stark", queryBy: "company_name", filterBy: "num_employees:>100", sortBy: "num_employees:desc") + let searchParams = SearchParameters(filterBy: "num_employees:>100", q: "stark", queryBy: "company_name", sortBy: "num_employees:desc") do { try await createDocument() @@ -219,16 +219,16 @@ final class DocumentTests: XCTestCase { } func testDocumentSearchWithPreset() async { - let productSchema = CollectionSchema(name: "products", fields: [ + let productSchema = CollectionSchema(fields: [ Field(name: "name", type: "string"), Field(name: "price", type: "int32"), Field(name: "brand", type: "string"), Field(name: "desc", type: "string"), - ]) + ], name: "products") let preset = PresetUpsertSchema( - value: .singleCollectionSearch( - SearchParameters(q: "Jor", queryBy: "name", filterBy: "price:=[50..120]") + value: .typeSearchParameters( + SearchParameters(filterBy: "price:=[50..120]", q: "Jor", queryBy: "name") ) ) @@ -238,7 +238,7 @@ final class DocumentTests: XCTestCase { do { let _ = try await client.presets().upsert(presetName: "single-collection-search-preset", params: preset) do { - let _ = try await client.collections.create(schema: productSchema) + let _ = try await client.collections().create(schema: productSchema) } catch (let error) { print(error.localizedDescription) XCTAssertTrue(false) @@ -266,7 +266,7 @@ final class DocumentTests: XCTestCase { } func testDocumentGroupSearch() async { - let searchParams = SearchParameters(q: "*", queryBy: "company_name", groupBy: "num_employees,country,metadata") + let searchParams = SearchParameters(groupBy: "num_employees,country,metadata", q: "*", queryBy: "company_name") do { try await createDocument() diff --git a/Tests/TypesenseTests/MultiSearchTests.swift b/Tests/TypesenseTests/MultiSearchTests.swift index 9caa2c1..1fed0f4 100644 --- a/Tests/TypesenseTests/MultiSearchTests.swift +++ b/Tests/TypesenseTests/MultiSearchTests.swift @@ -12,19 +12,19 @@ final class MultiSearchTests: XCTestCase { func testMultiSearch() async { - let productSchema = CollectionSchema(name: "products", fields: [ + let productSchema = CollectionSchema(fields: [ Field(name: "name", type: "string"), Field(name: "price", type: "int32"), Field(name: "brand", type: "string"), Field(name: "desc", type: "string"), - ]) + ], name: "products") - let brandSchema = CollectionSchema(name: "brands", fields: [ + let brandSchema = CollectionSchema(fields: [ Field(name: "name", type: "string"), - ]) + ], name: "brands") let searchRequests = [ - MultiSearchCollectionParameters(q: "shoe", filterBy: "price:=[50..120]", collection: "products"), + MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "shoe", collection: "products"), MultiSearchCollectionParameters(q: "Nike", collection: "brands"), ] @@ -35,14 +35,14 @@ final class MultiSearchTests: XCTestCase { do { do { - let _ = try await client.collections.create(schema: productSchema) + let _ = try await client.collections().create(schema: productSchema) } catch (let error) { print(error.localizedDescription) XCTAssertTrue(false) } do { - let _ = try await client.collections.create(schema: brandSchema) + let _ = try await client.collections().create(schema: brandSchema) } catch (let error) { print(error.localizedDescription) XCTAssertTrue(false) @@ -79,19 +79,19 @@ final class MultiSearchTests: XCTestCase { } func testMultiSearchReturnRawData() async { - let productSchema = CollectionSchema(name: "products", fields: [ + let productSchema = CollectionSchema(fields: [ Field(name: "name", type: "string"), Field(name: "price", type: "int32"), Field(name: "brand", type: "string"), Field(name: "desc", type: "string"), - ]) + ], name: "products") - let brandSchema = CollectionSchema(name: "brands", fields: [ + let brandSchema = CollectionSchema(fields: [ Field(name: "name", type: "string"), - ]) + ], name: "brands") let searchRequests = [ - MultiSearchCollectionParameters(q: "shoe", filterBy: "price:=[50..120]", collection: "products"), + MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "shoe", collection: "products"), MultiSearchCollectionParameters(q: "Nike", collection: "brands"), ] @@ -102,14 +102,14 @@ final class MultiSearchTests: XCTestCase { do { do { - let _ = try await client.collections.create(schema: productSchema) + let _ = try await client.collections().create(schema: productSchema) } catch (let error) { print(error.localizedDescription) XCTAssertTrue(false) } do { - let _ = try await client.collections.create(schema: brandSchema) + let _ = try await client.collections().create(schema: brandSchema) } catch (let error) { print(error.localizedDescription) XCTAssertTrue(false) @@ -143,21 +143,21 @@ final class MultiSearchTests: XCTestCase { } func testMultiSearchWithPreset() async { - let productSchema = CollectionSchema(name: "products", fields: [ + let productSchema = CollectionSchema(fields: [ Field(name: "name", type: "string"), Field(name: "price", type: "int32"), Field(name: "brand", type: "string"), Field(name: "desc", type: "string"), - ]) + ], name: "products") - let brandSchema = CollectionSchema(name: "brands", fields: [ + let brandSchema = CollectionSchema(fields: [ Field(name: "name", type: "string"), - ]) + ], name: "brands") let preset = PresetUpsertSchema( value: .typeMultiSearchSearchesParameter(MultiSearchSearchesParameter( searches:[ - MultiSearchCollectionParameters(q: "shoe", filterBy: "price:=[50..120]", collection: "products"), + MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "shoe", collection: "products"), MultiSearchCollectionParameters(q: "Nike", collection: "brands"), ] )) @@ -167,19 +167,19 @@ final class MultiSearchTests: XCTestCase { let brand1 = Brand(name: "Nike") let product1 = Product(name: "Jordan", price: 70, brand: "Nike", desc: "High quality shoe") - let commonParams = MultiSearchParameters(queryBy: "name", preset: "test-multi-search") + let commonParams = MultiSearchParameters(preset: "test-multi-search", queryBy: "name") do { let _ = try await client.presets().upsert(presetName: "test-multi-search", params: preset) do { - let _ = try await client.collections.create(schema: productSchema) + let _ = try await client.collections().create(schema: productSchema) } catch (let error) { print(error.localizedDescription) XCTAssertTrue(false) } do { - let _ = try await client.collections.create(schema: brandSchema) + let _ = try await client.collections().create(schema: brandSchema) } catch (let error) { print(error.localizedDescription) XCTAssertTrue(false) diff --git a/Tests/TypesenseTests/SynonymTests.swift b/Tests/TypesenseTests/SynonymTests.swift index 88351be..f51dc0e 100644 --- a/Tests/TypesenseTests/SynonymTests.swift +++ b/Tests/TypesenseTests/SynonymTests.swift @@ -9,7 +9,7 @@ final class SynonymTests: XCTestCase { do { let synonymSchema = SearchSynonymSchema(synonyms: ["blazer", "coat", "jacket"]) - let (_, _) = try await myClient.collections.create(schema: CollectionSchema(name: "products", fields: [Field(name: "name", type: "string")])) //Creating test collection - Products + let (_, _) = try await myClient.collections().create(schema: CollectionSchema(fields: [Field(name: "name", type: "string")],name: "products")) //Creating test collection - Products let (data, _) = try await myClient.collection(name: "products").synonyms().upsert(id: "coat-synonyms", synonymSchema) let (_,_) = try await myClient.collection(name: "products").delete() //Deleting test collection @@ -37,8 +37,8 @@ final class SynonymTests: XCTestCase { do { - let synonymSchema = SearchSynonymSchema(root: "smart phone", synonyms: ["iphone", "android"]) - let (_, _) = try await myClient.collections.create(schema: CollectionSchema(name: "products", fields: [Field(name: "name", type: "string")])) //Creating test collection - Products + let synonymSchema = SearchSynonymSchema( synonyms: ["iphone", "android"],root: "smart phone",) + let (_, _) = try await myClient.collections().create(schema: CollectionSchema(fields: [Field(name: "name", type: "string")], name: "products", )) //Creating test collection - Products let (data, _) = try await myClient.collection(name: "products").synonyms().upsert(id: "smart-phone-synonyms", synonymSchema) let (_,_) = try await myClient.collection(name: "products").delete() //Deleting test collection @@ -67,7 +67,7 @@ final class SynonymTests: XCTestCase { do { let synonymSchema = SearchSynonymSchema(synonyms: ["blazer", "coat", "jacket"]) - let (_, _) = try await myClient.collections.create(schema: CollectionSchema(name: "products", fields: [Field(name: "name", type: "string")])) //Creating test collection - Products + let (_, _) = try await myClient.collections().create(schema: CollectionSchema(fields: [Field(name: "name", type: "string")], name: "products",)) //Creating test collection - Products let (_, _) = try await myClient.collection(name: "products").synonyms().upsert(id: "coat-synonyms", synonymSchema) //Feed in the synonym let (data,_) = try await myClient.collection(name: "products").synonyms().retrieve(id: "coat-synonyms") let (_,_) = try await myClient.collection(name: "products").delete() //Deleting test collection @@ -96,7 +96,7 @@ final class SynonymTests: XCTestCase { do { let synonymSchema = SearchSynonymSchema(synonyms: ["blazer", "coat", "jacket"]) - let (_, _) = try await myClient.collections.create(schema: CollectionSchema(name: "products", fields: [Field(name: "name", type: "string")])) //Creating test collection - Products + let (_, _) = try await myClient.collections().create(schema: CollectionSchema(fields: [Field(name: "name", type: "string")], name: "products", )) //Creating test collection - Products let (_, _) = try await myClient.collection(name: "products").synonyms().upsert(id: "coat-synonyms", synonymSchema) //Feed in the synonym let (data,_) = try await myClient.collection(name: "products").synonyms().retrieve() let (_,_) = try await myClient.collection(name: "products").delete() //Deleting test collection @@ -125,7 +125,10 @@ final class SynonymTests: XCTestCase { do { let synonymSchema = SearchSynonymSchema(synonyms: ["blazer", "coat", "jacket"]) - let (_, _) = try await myClient.collections.create(schema: CollectionSchema(name: "products", fields: [Field(name: "name", type: "string")])) //Creating test collection - Products + let (_, _) = try await myClient.collections().create(schema: CollectionSchema( + fields: [Field(name: "name", type: "string")], + name: "products", + )) //Creating test collection - Products let (_, _) = try await myClient.collection(name: "products").synonyms().upsert(id: "coat-synonyms", synonymSchema) //Feed in the synonym let (data,_) = try await myClient.collection(name: "products").synonyms().delete(id: "coat-synonyms") let (_,_) = try await myClient.collection(name: "products").delete() //Deleting test collection diff --git a/Tests/TypesenseTests/TestUtils.swift b/Tests/TypesenseTests/TestUtils.swift index f0676ff..10423be 100644 --- a/Tests/TypesenseTests/TestUtils.swift +++ b/Tests/TypesenseTests/TestUtils.swift @@ -5,7 +5,7 @@ let client = Client(config: CONFIG) let utilClient = Client(config: Configuration(nodes: NODES, apiKey: "xyz")) func tearDownCollections() async throws { - let (collResp, _) = try await utilClient.collections.retrieveAll() + let (collResp, _) = try await utilClient.collections().retrieveAll() guard let validData = collResp else { throw DataError.dataNotFound } @@ -65,13 +65,16 @@ func tearDownAliases() async throws { } func createCollection() async throws { - let schema = CollectionSchema(name: "companies", fields: [ + let schema = CollectionSchema( fields: [ Field(name: "company_name", type: "string"), Field(name: "num_employees", type: "int32", facet: true), Field(name: "country", type: "string", facet: true), - Field(name: "metadata", type: "object", _optional: true, facet: true) - ], defaultSortingField: "num_employees", enableNestedFields: true) - let _ = try await utilClient.collections.create(schema: schema) + Field(name: "metadata", type: "object", facet: true, _optional: true) + ], + name: "companies", + defaultSortingField: "num_employees", + enableNestedFields: true) + let _ = try await utilClient.collections().create(schema: schema) } func createDocument() async throws { @@ -116,21 +119,22 @@ func createStopwordSet() async throws { func createAnalyticRule() async throws { let _ = try await utilClient.analytics().rules().create(AnalyticsRuleCreate( - name: "homepage_popular_queries", - type: .popularQueries, collection: "products", eventType: "search", - ruleTag: "homepage", + name: "homepage_popular_queries", + type: .popularQueries, params: AnalyticsRuleCreateParams( + captureSearchRequests: true, destinationCollection: "product_queries", limit: 100, - captureSearchRequests: true - ) + ), + ruleTag: "homepage", + )) } func createAPIKey() async throws -> ApiKey { - let (data, _) = try await utilClient.keys().create( ApiKeySchema(description: "Test key with all privileges", actions: ["*"], collections: ["*"])) + let (data, _) = try await utilClient.keys().create( ApiKeySchema(actions: ["*"], collections: ["*"], description: "Test key with all privileges")) return data! } @@ -139,14 +143,14 @@ func createAlias() async throws { } func createConversationCollection() async throws { - let schema = CollectionSchema(name: "conversation_store", fields: [ + let schema = CollectionSchema(fields: [ Field(name: "conversation_id", type: "string"), Field(name: "model_id", type: "string"), Field(name: "timestamp", type: "int32"), Field(name: "role", type: "string", index: false), Field(name: "message", type: "string", index: false) - ]) - let _ = try await utilClient.collections.create(schema: schema) + ], name: "conversation_store") + let _ = try await utilClient.collections().create(schema: schema) } struct Product: Codable, Equatable { diff --git a/openapi-generator-template/modelObject.mustache b/openapi-generator-template/modelObject.mustache index f340b87..51664c0 100644 --- a/openapi-generator-template/modelObject.mustache +++ b/openapi-generator-template/modelObject.mustache @@ -1,5 +1,5 @@ -{{^objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#useClasses}}final class{{/useClasses}}{{^useClasses}}struct{{/useClasses}} {{{classname}}}{{#vendorExtensions.x-swift-generic-parameter}}<{{.}}>{{/vendorExtensions.x-swift-generic-parameter}}: {{#useVapor}}Content{{/useVapor}}{{^useVapor}}Codable{{/useVapor}}{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}} { -{{/objcCompatible}}{{#objcCompatible}}@objcMembers {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} class {{classname}}: NSObject, Codable { +{{^objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#useClasses}}final class{{/useClasses}}{{^useClasses}}struct{{/useClasses}} {{{classname}}}{{#vendorExtensions.x-swift-generic-parameter}}<{{.}}>{{/vendorExtensions.x-swift-generic-parameter}}: {{#useVapor}}Content{{/useVapor}}{{^useVapor}}Codable{{#useJsonEncodable}}, JSONEncodable{{/useJsonEncodable}}{{/useVapor}}{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}} { +{{/objcCompatible}}{{#objcCompatible}}@objcMembers {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} class {{classname}}: NSObject, Codable{{#useJsonEncodable}}, JSONEncodable{{/useJsonEncodable}} { {{/objcCompatible}} {{#allVars}} @@ -54,7 +54,7 @@ {{/allVars}} {{#hasVars}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init({{#allVars}}{{{name}}}: {{#vendorExtensions.x-swift-type}}{{{.}}}{{/vendorExtensions.x-swift-type}}{{^vendorExtensions.x-swift-type}}{{#vendorExtensions.x-null-encodable}}NullEncodable<{{{datatypeWithEnum}}}>{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{/vendorExtensions.x-null-encodable}}{{/vendorExtensions.x-swift-type}}{{#defaultValue}} = {{#vendorExtensions.x-null-encodable}}{{{vendorExtensions.x-null-encodable-default-value}}}{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{.}}}{{/vendorExtensions.x-null-encodable}}{{/defaultValue}}{{^defaultValue}}{{^required}} = {{#vendorExtensions.x-null-encodable}}.encodeNull{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}nil{{/vendorExtensions.x-null-encodable}}{{/required}}{{/defaultValue}}{{^-last}}, {{/-last}}{{/allVars}}) { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init({{#requiredVars}}{{{name}}}: {{#vendorExtensions.x-swift-type}}{{{.}}}{{/vendorExtensions.x-swift-type}}{{^vendorExtensions.x-swift-type}}{{#vendorExtensions.x-null-encodable}}NullEncodable<{{{datatypeWithEnum}}}>{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{datatypeWithEnum}}}{{/vendorExtensions.x-null-encodable}}{{/vendorExtensions.x-swift-type}}{{^-last}}, {{/-last}}{{/requiredVars}}{{#hasRequired}}{{#hasOptional}}, {{/hasOptional}}{{/hasRequired}}{{#optionalVars}}{{{name}}}: {{#vendorExtensions.x-swift-type}}{{{.}}}{{/vendorExtensions.x-swift-type}}{{^vendorExtensions.x-swift-type}}{{#vendorExtensions.x-null-encodable}}NullEncodable<{{{datatypeWithEnum}}}>{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{/vendorExtensions.x-null-encodable}}{{/vendorExtensions.x-swift-type}}{{#defaultValue}} = {{#vendorExtensions.x-null-encodable}}{{{vendorExtensions.x-null-encodable-default-value}}}{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{.}}}{{/vendorExtensions.x-null-encodable}}{{/defaultValue}}{{^defaultValue}} = {{#vendorExtensions.x-null-encodable}}.encodeNull{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}nil{{/vendorExtensions.x-null-encodable}}{{/defaultValue}}{{^-last}}, {{/-last}}{{/optionalVars}}) { {{#allVars}} self.{{{name}}} = {{{name}}} {{/allVars}} @@ -134,4 +134,4 @@ {{/allVars}} {{#generateModelAdditionalProperties}}{{#additionalPropertiesType}}hasher.combine(additionalProperties.hashValue){{/additionalPropertiesType}}{{/generateModelAdditionalProperties}} }{{/vendorExtensions.x-swift-hashable}}{{/useClasses}}{{/objcCompatible}} -} +} \ No newline at end of file diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml index f37db27..7c474b8 100644 --- a/preprocessed_openapi.yml +++ b/preprocessed_openapi.yml @@ -1349,7 +1349,7 @@ components: items: $ref: '#/components/schemas/MultiSearchResultItem' type: array - x-swift-type: '[MultiSearchResultItem]?' + x-swift-type: '[MultiSearchResultItem]' required: - results type: object @@ -2765,11 +2765,6 @@ paths: first. operationId: getCollections parameters: - - in: query - name: offset - schema: - description: Identifies the starting point to return collections when paginating. - type: integer - in: query name: limit schema: @@ -2783,6 +2778,11 @@ paths: description: Comma-separated list of fields from the collection to exclude from the response type: string + - in: query + name: offset + schema: + description: Identifies the starting point to return collections when paginating. + type: integer responses: '200': content: @@ -3153,9 +3153,13 @@ paths: schema: type: string - in: query - name: return_doc + name: dirty_values schema: - type: boolean + $ref: '#/components/schemas/DirtyValues' + - in: query + name: action + schema: + $ref: '#/components/schemas/IndexAction' - in: query name: return_id schema: @@ -3168,17 +3172,13 @@ paths: schema: type: integer - in: query - name: batch_size - schema: - type: integer - - in: query - name: action + name: return_doc schema: - $ref: '#/components/schemas/IndexAction' + type: boolean - in: query - name: dirty_values + name: batch_size schema: - $ref: '#/components/schemas/DirtyValues' + type: integer requestBody: content: application/octet-stream: @@ -3230,76 +3230,45 @@ paths: schema: type: string - in: query - name: conversation_id - schema: - description: 'The Id of a previous conversation to continue, this tells - Typesense to include prior context when communicating with the LLM. - - ' - type: string - - in: query - name: exclude_fields - schema: - description: List of fields from the document to exclude in the search result - type: string - - in: query - name: pre_segmented_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 - - in: query - name: min_len_1typo + name: min_len_2typo schema: - description: 'Minimum word length for 1-typo correction to be applied. The + 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 - in: query - name: query_by_weights - 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 - - in: query - name: query_by + name: max_filter_by_candidates schema: - description: A list of `string` fields that should be queried against. Multiple - fields are separated with a comma. - type: string + 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 - in: query - name: include_fields + name: voice_query schema: - description: List of fields from the document to include in the search result + description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. + + ' type: string - in: query - name: drop_tokens_threshold + name: highlight_fields 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 + description: 'A list of custom fields that must be highlighted even if you + don''t query for them ' - type: integer + type: string - in: query - name: group_limit + name: highlight_affix_num_tokens 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 + description: 'The number of tokens that should surround the highlighted + text on each side. Default: 4 ' type: integer - in: query - name: max_extra_prefix + name: max_extra_suffix 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 @@ -3308,14 +3277,11 @@ paths: By default, any number of prefixes/suffixes can be present for a match. type: integer - in: query - name: sort_by + name: group_by 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` - example: num_employees:desc + 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 - in: query name: offset @@ -3324,184 +3290,175 @@ paths: set. Can be used as an alternative to the page parameter. type: integer - in: query - name: page - schema: - description: Results from this specific page number would be fetched. - type: integer - - in: query - name: exhaustive_search + name: use_cache 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). + description: 'Enable server side caching of search query results. By default, + caching is disabled. ' type: boolean - in: query - name: facet_query + name: preset 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". + description: 'Search using a bunch of search parameters by setting this + parameter to the name of the existing Preset. + + ' type: string - in: query - name: nl_query - schema: - description: Whether to use natural language processing to parse the query. - type: boolean - - in: query - name: search_cutoff_ms + name: limit 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. + description: 'Number of hits to fetch. Can be used as an alternative to + the per_page parameter. Default: 10. ' type: integer - in: query - name: text_match_type + name: drop_tokens_mode 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. + $ref: '#/components/schemas/DropTokensMode' + - in: query + name: query_by_weights + 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 - in: query - name: highlight_end_tag + name: infix schema: - description: 'The end tag used for the highlighted snippets. Default: `` - - ' + 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 - in: query - name: enable_typos_for_alpha_numerical_tokens + name: highlight_start_tag schema: - description: 'Set this parameter to false to disable typos on alphanumerical - query tokens. Default: true. + description: 'The start tag used for the highlighted snippets. Default: + `` ' - type: boolean + type: string - in: query - name: enable_typos_for_numerical_tokens + name: query_by schema: - default: true - description: 'Make Typesense disable typos for numerical tokens. - - ' - type: boolean + description: A list of `string` fields that should be queried against. Multiple + fields are separated with a comma. + type: string - in: query - name: group_missing_values + name: max_candidates 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 + description: 'Control the number of words that Typesense considers for typo + and prefix searching. ' - type: boolean - - in: query - name: synonym_sets - schema: - description: List of synonym set names to associate with this search query - example: synonym_set_1,synonym_set_2 - type: string + type: integer - in: query - name: prioritize_num_matching_fields + name: conversation schema: - default: true - description: 'Make Typesense prioritize documents where the query words - appear in more number of fields. + description: 'Enable conversational search. ' type: boolean - in: query - name: highlight_full_fields + name: q schema: - description: List of fields which should be highlighted fully without snippeting + 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 - in: query - name: hidden_hits + name: facet_by 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`. - - ' + description: A list of fields that will be used for faceting your results + on. Separate multiple fields with a comma. type: string - in: query - name: prioritize_token_position + name: drop_tokens_threshold schema: - default: false - description: 'Make Typesense prioritize documents where the query words - appear earlier in the text. + 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: boolean + type: integer - in: query - name: prioritize_exact_match + name: remote_embedding_timeout_ms schema: - default: true - description: 'Set this parameter to true to ensure that an exact match is - ranked above the others + description: 'Timeout (in milliseconds) for fetching remote embeddings. ' - type: boolean + type: integer - in: query - name: limit + name: enable_overrides schema: - description: 'Number of hits to fetch. Can be used as an alternative to - the per_page parameter. Default: 10. + default: false + 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: integer + type: boolean - in: query - name: filter_curated_hits + name: pinned_hits schema: - 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 + 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: boolean + type: string - in: query - name: cache_ttl + name: pre_segmented_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. + 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: integer + type: boolean - in: query - name: typo_tokens_threshold + name: include_fields 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 + description: List of fields from the document to include in the search result + type: string - in: query - name: max_candidates + name: facet_query schema: - description: 'Control the number of words that Typesense considers for typo - and prefix searching. - - ' + 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 + - in: query + name: max_extra_prefix + 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 - in: query - name: num_typos + name: enable_typos_for_alpha_numerical_tokens schema: - description: 'The number of typographical errors (1 or 2) that would be - tolerated. Default: 2 + description: 'Set this parameter to false to disable typos on alphanumerical + query tokens. Default: true. ' - type: string + type: boolean - in: query name: facet_return_parent schema: @@ -3511,65 +3468,40 @@ paths: ' type: string - in: query - name: use_cache + name: prioritize_num_matching_fields schema: - description: 'Enable server side caching of search query results. By default, - caching is disabled. + default: true + description: 'Make Typesense prioritize documents where the query words + appear in more number of fields. ' type: boolean - in: query - name: prefix - 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 - - in: query - name: preset + name: enable_typos_for_numerical_tokens schema: - description: 'Search using a bunch of search parameters by setting this - parameter to the name of the existing Preset. + default: true + description: 'Make Typesense disable typos for numerical tokens. ' - type: string + type: boolean - in: query - name: highlight_affix_num_tokens + name: conversation_model_id schema: - description: 'The number of tokens that should surround the highlighted - text on each side. Default: 4 + description: 'The Id of Conversation Model to be used. ' - type: integer - - in: query - name: facet_by - schema: - description: A list of fields that will be used for faceting your results - on. Separate multiple fields with a comma. type: string - in: query - name: enable_overrides - schema: - default: false - 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 - - in: query - name: enable_analytics + name: override_tags schema: - default: true - description: 'Flag for enabling/disabling analytics aggregation for specific - search queries (for e.g. those originating from a test script). - - ' - type: boolean + description: Comma separated list of tags to trigger the curations rules + that match the tags. + type: string - in: query - name: conversation_model_id + name: stopwords schema: - description: 'The Id of Conversation Model to be used. + 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 @@ -3582,19 +3514,9 @@ paths: ' type: string - in: query - name: pinned_hits + name: nl_model_id 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`. - - ' + description: The ID of the natural language model to use. type: string - in: query name: remote_embedding_num_tries @@ -3604,75 +3526,78 @@ paths: ' type: integer - in: query - name: synonym_prefix + name: filter_curated_hits schema: - description: 'Allow synonym resolution on word prefixes in the query. Default: - false + 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 ' type: boolean - in: query - name: q - 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 - - in: query - name: infix + name: enable_highlight_v1 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 + default: true + description: 'Flag for enabling/disabling the deprecated, old highlight + structure in the response. Default: true + + ' + type: boolean - in: query - name: nl_model_id + name: min_len_1typo schema: - description: The ID of the natural language model to use. - type: string + 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 - in: query - name: max_extra_suffix + name: page 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. + description: Results from this specific page number would be fetched. type: integer - in: query - name: highlight_fields + name: search_cutoff_ms schema: - description: 'A list of custom fields that must be highlighted even if you - don''t query for them + 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 + - in: query + name: exclude_fields + schema: + description: List of fields from the document to exclude in the search result type: string - in: query - name: conversation + name: max_facet_values schema: - description: 'Enable conversational search. - - ' - type: boolean + description: Maximum number of facet values to be returned. + type: integer - in: query - name: vector_query + name: snippet_threshold schema: - description: 'Vector query expression for fetching documents "closest" to - a given query/document vector. + description: 'Field values under this length will be fully highlighted, + instead of showing a snippet of relevant portion. Default: 30 ' - type: string + type: integer - in: query - name: min_len_2typo + name: synonym_prefix 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. + description: 'Allow synonym resolution on word prefixes in the query. Default: + false ' - type: integer + type: boolean + - in: query + name: prefix + 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 - in: query name: enable_synonyms schema: @@ -3683,20 +3608,22 @@ paths: ' type: boolean - in: query - name: remote_embedding_timeout_ms + name: num_typos schema: - description: 'Timeout (in milliseconds) for fetching remote embeddings. + description: 'The number of typographical errors (1 or 2) that would be + tolerated. Default: 2 ' - type: integer + type: string - in: query - name: stopwords + name: prioritize_exact_match 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. + default: true + description: 'Set this parameter to true to ensure that an exact match is + ranked above the others ' - type: string + type: boolean - in: query name: filter_by schema: @@ -3705,81 +3632,154 @@ paths: example: 'num_employees:>100 && country: [USA, UK]' type: string - in: query - name: split_join_tokens + name: hidden_hits 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`. + 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 - in: query - name: enable_highlight_v1 + name: group_missing_values schema: - default: true - description: 'Flag for enabling/disabling the deprecated, old highlight - structure in the response. Default: true + 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 - in: query - name: group_by + name: highlight_full_fields 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. + description: List of fields which should be highlighted fully without snippeting type: string - in: query - name: override_tags + name: group_limit schema: - description: Comma separated list of tags to trigger the curations rules - that match the tags. + 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 + - in: query + name: highlight_end_tag + schema: + description: 'The end tag used for the highlighted snippets. Default: `` + + ' type: string - in: query - name: snippet_threshold + name: split_join_tokens schema: - description: 'Field values under this length will be fully highlighted, - instead of showing a snippet of relevant portion. Default: 30 + 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: integer + type: string - in: query - name: per_page + name: enable_analytics schema: - description: 'Number of results to fetch per page. Default: 10' + default: true + description: 'Flag for enabling/disabling analytics aggregation for specific + search queries (for e.g. those originating from a test script). + + ' + type: boolean + - in: query + name: typo_tokens_threshold + 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 - in: query - name: voice_query + name: prioritize_token_position schema: - description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. + default: false + description: 'Make Typesense prioritize documents where the query words + appear earlier in the text. + + ' + type: boolean + - in: query + name: vector_query + schema: + description: 'Vector query expression for fetching documents "closest" to + a given query/document vector. ' type: string - in: query - name: max_facet_values + name: conversation_id schema: - description: Maximum number of facet values to be returned. - type: integer + description: 'The Id of a previous conversation to continue, this tells + Typesense to include prior context when communicating with the LLM. + + ' + type: string - in: query - name: max_filter_by_candidates + name: synonym_sets 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*. + description: List of synonym set names to associate with this search query + example: synonym_set_1,synonym_set_2 + type: string + - in: query + name: exhaustive_search + 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 + - in: query + name: per_page + schema: + description: 'Number of results to fetch per page. Default: 10' type: integer - in: query - name: highlight_start_tag + name: sort_by schema: - description: 'The start tag used for the highlighted snippets. Default: - `` + 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` + example: num_employees:desc + type: string + - in: query + name: cache_ttl + 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 + - in: query + name: text_match_type + 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 - in: query - name: drop_tokens_mode + name: nl_query schema: - $ref: '#/components/schemas/DropTokensMode' + description: Whether to use natural language processing to parse the query. + type: boolean - in: query name: synonym_num_typos schema: @@ -4461,77 +4461,38 @@ paths: operationId: multiSearch parameters: - in: query - name: conversation_id - schema: - description: 'The Id of a previous conversation to continue, this tells - Typesense to include prior context when communicating with the LLM. - - ' - type: string - - in: query - name: exclude_fields - schema: - description: List of fields from the document to exclude in the search result - type: string - - in: query - name: pre_segmented_query - schema: - default: false - 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 - - in: query - name: min_len_1typo + name: min_len_2typo schema: - description: 'Minimum word length for 1-typo correction to be applied. The + 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 - in: query - name: query_by_weights - 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 - - in: query - name: query_by + name: voice_query schema: - description: A list of `string` fields that should be queried against. Multiple - fields are separated with a comma. + description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. + + ' type: string - in: query - name: drop_tokens_threshold + name: highlight_fields 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 + description: 'A list of custom fields that must be highlighted even if you + don''t query for them ' - type: integer - - in: query - name: include_fields - schema: - description: List of fields from the document to include in the search result type: string - in: query - name: group_limit + name: highlight_affix_num_tokens 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 + description: 'The number of tokens that should surround the highlighted + text on each side. Default: 4 ' type: integer - in: query - name: max_extra_prefix + name: max_extra_suffix 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 @@ -4540,13 +4501,11 @@ paths: By default, any number of prefixes/suffixes can be present for a match. type: integer - in: query - name: sort_by + name: group_by 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` + 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 - in: query name: offset @@ -4555,97 +4514,119 @@ paths: set. Can be used as an alternative to the page parameter. type: integer - in: query - name: page + name: preset schema: - description: Results from this specific page number would be fetched. - type: integer + description: 'Search using a bunch of search parameters by setting this + parameter to the name of the existing Preset. + + ' + type: string - in: query - name: exhaustive_search + name: use_cache 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). + description: 'Enable server side caching of search query results. By default, + caching is disabled. ' type: boolean - in: query - name: search_cutoff_ms + name: limit 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. + description: 'Number of hits to fetch. Can be used as an alternative to + the per_page parameter. Default: 10. ' type: integer - in: query - name: facet_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 - - in: query - name: text_match_type + name: drop_tokens_mode 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 + $ref: '#/components/schemas/DropTokensMode' - in: query - name: highlight_end_tag + name: query_by_weights schema: - description: 'The end tag used for the highlighted snippets. Default: `` - - ' + 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 - in: query - name: enable_typos_for_alpha_numerical_tokens + name: infix schema: - description: 'Set this parameter to false to disable typos on alphanumerical - query tokens. Default: true. + 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 + - in: query + name: highlight_start_tag + schema: + description: 'The start tag used for the highlighted snippets. Default: + `` ' - type: boolean + type: string - in: query - name: enable_typos_for_numerical_tokens + name: query_by schema: - default: true - description: 'Make Typesense disable typos for numerical tokens. + description: A list of `string` fields that should be queried against. Multiple + fields are separated with a comma. + type: string + - in: query + name: conversation + schema: + description: 'Enable conversational search. ' type: boolean - in: query - name: group_missing_values + name: q 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 + 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 + - in: query + name: facet_by + schema: + description: A list of fields that will be used for faceting your results + on. Separate multiple fields with a comma. + type: string + - in: query + name: drop_tokens_threshold + 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: boolean + type: integer - in: query - name: prioritize_num_matching_fields + name: remote_embedding_timeout_ms schema: - default: true - description: 'Make Typesense prioritize documents where the query words - appear in more number of fields. + description: 'Timeout (in milliseconds) for fetching remote embeddings. ' - type: boolean + type: integer - in: query - name: highlight_full_fields + name: enable_overrides schema: - description: List of fields which should be highlighted fully without snippeting - type: string + default: false + 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 - in: query - name: hidden_hits + name: pinned_hits 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`. + 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 @@ -4654,321 +4635,340 @@ paths: ' type: string - in: query - name: prioritize_exact_match + name: facet_query schema: - default: true - description: 'Set this parameter to true to ensure that an exact match is - ranked above the others + 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 + - in: query + name: enable_typos_for_alpha_numerical_tokens + schema: + description: 'Set this parameter to false to disable typos on alphanumerical + query tokens. Default: true. ' type: boolean - in: query - name: prioritize_token_position + name: include_fields + schema: + description: List of fields from the document to include in the search result + type: string + - in: query + name: pre_segmented_query schema: default: false - description: 'Make Typesense prioritize documents where the query words - appear earlier in the text. + 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 - in: query - name: limit + name: max_extra_prefix schema: - description: 'Number of hits to fetch. Can be used as an alternative to - the per_page parameter. Default: 10. + 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 + - in: query + name: facet_return_parent + schema: + description: 'Comma separated string of nested facet fields whose parent + object should be returned in facet response. ' - type: integer + type: string - in: query - name: cache_ttl + name: prioritize_num_matching_fields 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. + default: true + description: 'Make Typesense prioritize documents where the query words + appear in more number of fields. ' - type: integer + type: boolean - in: query - name: typo_tokens_threshold + name: override_tags 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 + description: Comma separated list of tags to trigger the curations rules + that match the tags. + type: string + - in: query + name: conversation_model_id + schema: + description: 'The Id of Conversation Model to be used. ' - type: integer + type: string - in: query - name: filter_curated_hits + name: enable_typos_for_numerical_tokens schema: - 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 + default: true + description: 'Make Typesense disable typos for numerical tokens. ' type: boolean - in: query - name: num_typos + name: stopwords schema: - description: 'The number of typographical errors (1 or 2) that would be - tolerated. Default: 2 + 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 - in: query - name: facet_return_parent + name: facet_strategy schema: - description: 'Comma separated string of nested facet fields whose parent - object should be returned in facet response. + description: 'Choose the underlying faceting strategy used. Comma separated + string of allows values: exhaustive, top_values or automatic (default). ' type: string - in: query - name: prefix + name: remote_embedding_num_tries 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 + description: 'Number of times to retry fetching remote embeddings. + + ' + type: integer - in: query - name: use_cache + name: filter_curated_hits schema: - description: 'Enable server side caching of search query results. By default, - caching is disabled. + 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 ' type: boolean - in: query - name: preset + name: min_len_1typo schema: - description: 'Search using a bunch of search parameters by setting this - parameter to the name of the existing Preset. + 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 + - in: query + name: exclude_fields + schema: + description: List of fields from the document to exclude in the search result type: string - in: query - name: highlight_affix_num_tokens + name: max_facet_values schema: - description: 'The number of tokens that should surround the highlighted - text on each side. Default: 4 - - ' + description: Maximum number of facet values to be returned. type: integer - in: query - name: facet_by + name: page schema: - description: A list of fields that will be used for faceting your results - on. Separate multiple fields with a comma. - type: string + description: Results from this specific page number would be fetched. + type: integer - in: query - name: enable_overrides + name: search_cutoff_ms schema: - default: false - 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 + 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: boolean + type: integer - in: query - name: pinned_hits + name: snippet_threshold 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`. + description: 'Field values under this length will be fully highlighted, + instead of showing a snippet of relevant portion. Default: 30 ' - type: string + type: integer - in: query - name: enable_analytics + name: synonym_prefix schema: - default: true - description: 'Flag for enabling/disabling analytics aggregation for specific - search queries (for e.g. those originating from a test script). + description: 'Allow synonym resolution on word prefixes in the query. Default: + false ' type: boolean - in: query - name: facet_strategy + name: prefix schema: - description: 'Choose the underlying faceting strategy used. Comma separated - string of allows values: exhaustive, top_values or automatic (default). + 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 + - in: query + name: num_typos + schema: + description: 'The number of typographical errors (1 or 2) that would be + tolerated. Default: 2 ' type: string - in: query - name: conversation_model_id + name: enable_synonyms schema: - description: 'The Id of Conversation Model to be used. + 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 ' - type: string + type: boolean - in: query - name: remote_embedding_num_tries + name: prioritize_exact_match schema: - description: 'Number of times to retry fetching remote embeddings. + default: true + description: 'Set this parameter to true to ensure that an exact match is + ranked above the others ' - type: integer + type: boolean - in: query - name: q + name: filter_by 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. + description: Filter conditions for refining youropen api validator search + results. Separate multiple conditions with &&. + example: 'num_employees:>100 && country: [USA, UK]' type: string - in: query - name: synonym_prefix + name: hidden_hits schema: - description: 'Allow synonym resolution on word prefixes in the query. Default: - false + 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: boolean - - in: query - name: infix - 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 - in: query - name: conversation + name: group_missing_values schema: - description: 'Enable conversational search. + 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 - in: query - name: max_extra_suffix + name: highlight_full_fields 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 + description: List of fields which should be highlighted fully without snippeting + type: string - in: query - name: highlight_fields + name: group_limit schema: - description: 'A list of custom fields that must be highlighted even if you - don''t query for them + 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: string + type: integer - in: query - name: vector_query + name: highlight_end_tag schema: - description: 'Vector query expression for fetching documents "closest" to - a given query/document vector. + description: 'The end tag used for the highlighted snippets. Default: `` ' type: string - in: query - name: enable_synonyms + name: enable_analytics schema: - 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 + default: true + description: 'Flag for enabling/disabling analytics aggregation for specific + search queries (for e.g. those originating from a test script). ' type: boolean - in: query - name: min_len_2typo + name: typo_tokens_threshold 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. + 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 - in: query - name: remote_embedding_timeout_ms + name: vector_query schema: - description: 'Timeout (in milliseconds) for fetching remote embeddings. + description: 'Vector query expression for fetching documents "closest" to + a given query/document vector. ' - type: integer + type: string - in: query - name: stopwords + name: conversation_id 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. + description: 'The Id of a previous conversation to continue, this tells + Typesense to include prior context when communicating with the LLM. ' type: string - in: query - name: filter_by - schema: - description: Filter conditions for refining youropen api validator search - results. Separate multiple conditions with &&. - example: 'num_employees:>100 && country: [USA, UK]' - type: string - - in: query - name: group_by - 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 - - in: query - name: override_tags + name: prioritize_token_position schema: - description: Comma separated list of tags to trigger the curations rules - that match the tags. - type: string + default: false + description: 'Make Typesense prioritize documents where the query words + appear earlier in the text. + + ' + type: boolean - in: query - name: synonym_num_typos + name: exhaustive_search schema: - description: 'Allow synonym resolution on typo-corrected words in the query. - Default: 0 + 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: integer + type: boolean - in: query name: per_page schema: description: 'Number of results to fetch per page. Default: 10' type: integer - in: query - name: snippet_threshold + name: sort_by schema: - description: 'Field values under this length will be fully highlighted, - instead of showing a snippet of relevant portion. Default: 30 - - ' - type: integer + 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 - in: query - name: max_facet_values + name: cache_ttl schema: - description: Maximum number of facet values to be returned. + 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 - in: query - name: highlight_start_tag + name: text_match_type schema: - description: 'The start tag used for the highlighted snippets. Default: - `` - - ' + 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 - in: query - name: voice_query + name: synonym_num_typos schema: - description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. + description: 'Allow synonym resolution on typo-corrected words in the query. + Default: 0 ' - type: string - - in: query - name: drop_tokens_mode - schema: - $ref: '#/components/schemas/DropTokensMode' + type: integer requestBody: content: application/json: From 1f62b6564d56cecbebcd67fd70bea42613f00bd3 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Wed, 3 Dec 2025 23:50:33 +0700 Subject: [PATCH 05/21] feat: v30 analytics API --- .gitignore | 2 + Sources/Typesense/Analytics.swift | 2 +- Sources/Typesense/AnalyticsEvents.swift | 12 + Sources/Typesense/AnalyticsRules.swift | 4 +- .../AnalyticsEventsRetrieveParams.swift | 41 + .../AnalyticsRuleCreateManyResponse.swift | 50 + Tasks/PreprocessOpenAPI.swift | 77 ++ Tests/TypesenseTests/AnalyticsTests.swift | 59 +- Tests/TypesenseTests/TestUtils.swift | 16 - compose.yml | 9 + preprocessed_openapi.yml | 1207 +++++++++-------- 11 files changed, 850 insertions(+), 629 deletions(-) create mode 100644 Sources/Typesense/Models/AnalyticsEventsRetrieveParams.swift create mode 100644 Sources/Typesense/Shared/AnalyticsRuleCreateManyResponse.swift create mode 100644 compose.yml diff --git a/.gitignore b/.gitignore index e284f64..10032af 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ xcuserdata/ DerivedData/ .swiftpm + +/typesense-data \ No newline at end of file diff --git a/Sources/Typesense/Analytics.swift b/Sources/Typesense/Analytics.swift index 8c5fcc1..4433464 100644 --- a/Sources/Typesense/Analytics.swift +++ b/Sources/Typesense/Analytics.swift @@ -1,7 +1,7 @@ import Foundation public struct Analytics { - static let resourcePath: String = "/analytics" + static let resourcePath: String = "analytics" private var analyticsRules: AnalyticsRules var apiCall: ApiCall diff --git a/Sources/Typesense/AnalyticsEvents.swift b/Sources/Typesense/AnalyticsEvents.swift index c8f3f7f..0cca3bd 100644 --- a/Sources/Typesense/AnalyticsEvents.swift +++ b/Sources/Typesense/AnalyticsEvents.swift @@ -20,4 +20,16 @@ public struct AnalyticsEventsAPI { } return (nil, response) } + + public func retrieve(_ params: AnalyticsEventsRetrieveParams) async throws -> (AnalyticsEventsResponse?, URLResponse?) { + let queryParams = try createURLQuery(forSchema: params) + + let (data, response) = try await self.apiCall.get(endPoint: AnalyticsEventsAPI.resourcePath, queryParameters: queryParams) + if let result = data { + let validData = try decoder.decode(AnalyticsEventsResponse.self, from: result) + return (validData, response) + } + return (nil, response) + } + } diff --git a/Sources/Typesense/AnalyticsRules.swift b/Sources/Typesense/AnalyticsRules.swift index e03af51..1d42a57 100644 --- a/Sources/Typesense/AnalyticsRules.swift +++ b/Sources/Typesense/AnalyticsRules.swift @@ -34,11 +34,11 @@ public struct AnalyticsRules { return (nil, response) } - public func createMany(_ params: [AnalyticsRuleCreate]) async throws -> ([AnalyticsRule]?, URLResponse?) { + public func createMany(_ params: [AnalyticsRuleCreate]) async throws -> ([AnalyticsRuleCreateManyResponseItem]?, URLResponse?) { let ruleData = try encoder.encode(params) let (data, response) = try await self.apiCall.post(endPoint: endpointPath(), body: ruleData) if let result = data { - let ruleResult = try decoder.decode([AnalyticsRule].self, from: result) + let ruleResult = try decoder.decode([AnalyticsRuleCreateManyResponseItem].self, from: result) return (ruleResult, response) } diff --git a/Sources/Typesense/Models/AnalyticsEventsRetrieveParams.swift b/Sources/Typesense/Models/AnalyticsEventsRetrieveParams.swift new file mode 100644 index 0000000..86aaf67 --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsEventsRetrieveParams.swift @@ -0,0 +1,41 @@ +// +// AnalyticsEventsRetrieveParams.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AnalyticsEventsRetrieveParams: Codable { + + /** Number of events to return (max 1000) */ + public var n: Int + /** Analytics rule name */ + public var name: String + public var userId: String + + public init(n: Int, name: String, userId: String) { + self.n = n + self.name = name + self.userId = userId + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case n + case name + case userId = "user_id" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(n, forKey: .n) + try container.encode(name, forKey: .name) + try container.encode(userId, forKey: .userId) + } +} diff --git a/Sources/Typesense/Shared/AnalyticsRuleCreateManyResponse.swift b/Sources/Typesense/Shared/AnalyticsRuleCreateManyResponse.swift new file mode 100644 index 0000000..056324e --- /dev/null +++ b/Sources/Typesense/Shared/AnalyticsRuleCreateManyResponse.swift @@ -0,0 +1,50 @@ +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum AnalyticsRuleCreateManyResponseItem: Codable { + case success(AnalyticsRule) + case error(CreateAnalyticsRuleError) + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .success(let value): + try container.encode(value) + case .error(let value): + try container.encode(value) + } + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if let value = try? container.decode(AnalyticsRule.self) { + self = .success(value) + } else if let value = try? container.decode(CreateAnalyticsRuleError.self) { + self = .error(value) + } else { + throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of PresetUpsertSchemaValue")) + } + } +} + +public struct CreateAnalyticsRuleError: Codable { + + public var error: String? + + public init(error: String? = nil) { + self.error = error + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case error + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(error, forKey: .error) + } +} diff --git a/Tasks/PreprocessOpenAPI.swift b/Tasks/PreprocessOpenAPI.swift index a627a7e..0b3dc8c 100644 --- a/Tasks/PreprocessOpenAPI.swift +++ b/Tasks/PreprocessOpenAPI.swift @@ -17,6 +17,9 @@ struct PreprocessOpenAPI { print("Preprocessing the spec...") + // Create Models from URL Parameters + try createUrlParamsSchema(&doc, name: "AnalyticsEventsRetrieveParams", path: "/analytics/events", method: "get") + // Add Vendor Attributes try addVendorAttributes(&doc) @@ -159,6 +162,80 @@ struct PreprocessOpenAPI { doc["paths"] = paths } + /// Scans a specific Path/Method, finds all Query parameters, and creates a new Schema Model in Components. + static func createUrlParamsSchema(_ doc: inout Node, name: String, path: String, method: String) throws { + print("- Extracting URL params from \(method.uppercased()) \(path) into schema '\(name)'...") + + // Navigate to Paths -> Path -> Method -> Parameters + guard let paths = doc["paths"] as? Node, + let pathItem = paths[path] as? Node, + let operation = pathItem[method] as? Node, + let parameters = operation["parameters"] as? [Node] else { + print("⚠️ Warning: Path or operation not found: \(method) \(path)") + return + } + + var properties: Node = [:] + var requiredFields: [String] = [] + + // Iterate over parameters + for param in parameters { + // We only care about query parameters + guard let inLoc = param["in"] as? String, inLoc == "query", + let paramName = param["name"] as? String, + let schema = param["schema"] as? Node else { + continue + } + + // Build the property definition + var propertyDef = schema + + // Copy description + if let description = param["description"] as? String { + propertyDef["description"] = description + } + + // Copy custom x-swift-type if it exists on the param level + if let customType = param["x-swift-type"] { + propertyDef["x-swift-type"] = customType + } + + properties[paramName] = propertyDef + + // Handle Required Status + // OpenAPI Params use "required: true", JSON Schema uses a "required" array + if let isRequired = param["required"] as? Bool, isRequired { + requiredFields.append(paramName) + } + } + + if properties.isEmpty { + print("⚠️ No query parameters found for \(name). Skipping.") + return + } + + // Construct the new Schema Object + var newSchema: Node = [ + "type": "object", + "properties": properties + ] + + if !requiredFields.isEmpty { + newSchema["required"] = requiredFields + } + + // Inject into components.schemas + var components = doc["components"] as? Node ?? [:] + var schemas = components["schemas"] as? Node ?? [:] + + schemas[name] = newSchema + + components["schemas"] = schemas + doc["components"] = components + + print(" ✅ Created schema '\(name)' with \(properties.count) properties.") + } + } struct StringError: Error, CustomStringConvertible { diff --git a/Tests/TypesenseTests/AnalyticsTests.swift b/Tests/TypesenseTests/AnalyticsTests.swift index c6f1e33..aeb4f53 100644 --- a/Tests/TypesenseTests/AnalyticsTests.swift +++ b/Tests/TypesenseTests/AnalyticsTests.swift @@ -10,8 +10,20 @@ final class AnalyticsTests: XCTestCase { let _ = try await utilClient.collections().create(schema: CollectionSchema(fields: [ Field(name:"name", type: "string"), Field(name:"in_stock", type: "int32") - ], name: "products")) - try await createAnalyticRule() + ], name: "test-products-analytics")) + let _ = try await utilClient.analytics().rules().create(AnalyticsRuleCreate( + collection: "test-products-analytics", + eventType: "search", + name: "homepage_popular_queries", + type: .popularQueries, + params: AnalyticsRuleCreateParams( + captureSearchRequests: true, + destinationCollection: "product_queries", + limit: 100, + ), + ruleTag: "homepage", + + )) } override func tearDown() async throws { @@ -21,7 +33,7 @@ final class AnalyticsTests: XCTestCase { func testAnalyticsRuleCreate() async { let schema = AnalyticsRuleCreate( - collection: "products", + collection: "test-products-analytics", eventType: "search", name: "test-rule", type: .popularQueries, @@ -46,12 +58,12 @@ final class AnalyticsTests: XCTestCase { XCTAssertTrue(false) } } - + func testAnalyticsRuleCreateMany() async { let schema1 = AnalyticsRuleCreate( - collection: "test_rule_1", + collection: "test-products-analytics", eventType: "search", - name: "products", + name: "test_rule_1", type: .popularQueries, params: AnalyticsRuleCreateParams( destinationCollection: "product_queries", @@ -60,8 +72,8 @@ final class AnalyticsTests: XCTestCase { ruleTag: "homepage" ) let schema2 = AnalyticsRuleCreate( - collection: "products", - eventType: "any", + collection: "test-products-analytics", + eventType: "search", name: "test_rule_2", type: .popularQueries, params: AnalyticsRuleCreateParams( @@ -70,7 +82,6 @@ final class AnalyticsTests: XCTestCase { ), ruleTag: "homepage", ) - do { let (rules, _) = try await utilClient.analytics().rules().createMany([schema1, schema2]) XCTAssertNotNil(rules) @@ -78,10 +89,14 @@ final class AnalyticsTests: XCTestCase { throw DataError.dataNotFound } print(validRule) - XCTAssertEqual(validRule[0].name, schema1.name) - XCTAssertEqual(validRule[1].name, schema2.name) + if case let .success(firstRule) = validRule[0], case let .success(secondRule) = validRule[1] { + XCTAssertEqual(firstRule.name, schema1.name) + XCTAssertEqual(secondRule.name, schema2.name) + } else { + XCTFail("Both rules should be of type AnalyticsRule") + } } catch (let error) { - print(error.localizedDescription) + print(error) XCTAssertTrue(false) } } @@ -138,7 +153,7 @@ final class AnalyticsTests: XCTestCase { userId: "111112", ), eventType: "popular_queries", - name: "product_queries_aggregation", + name: "homepage_popular_queries", )) guard let validRes = res else { throw DataError.dataNotFound @@ -146,8 +161,24 @@ final class AnalyticsTests: XCTestCase { print(validRes) XCTAssertTrue(validRes.ok) } catch (let error) { - print(error.localizedDescription) + print(error) XCTAssertTrue(false) } } + + func testAnalyticsEventsRetrieve() async { + do { + let (res, _) = try await client.analytics().events().retrieve( + AnalyticsEventsRetrieveParams(n:10, name: "homepage_popular_queries", userId: "123")) + guard let validRes = res else { + throw DataError.dataNotFound + } + print(validRes) + XCTAssertEqual(validRes.events.count, 0) + } catch (let error) { + print(error) + XCTAssertTrue(false) + } + } + } diff --git a/Tests/TypesenseTests/TestUtils.swift b/Tests/TypesenseTests/TestUtils.swift index 10423be..d1c492f 100644 --- a/Tests/TypesenseTests/TestUtils.swift +++ b/Tests/TypesenseTests/TestUtils.swift @@ -117,22 +117,6 @@ func createStopwordSet() async throws { ) } -func createAnalyticRule() async throws { - let _ = try await utilClient.analytics().rules().create(AnalyticsRuleCreate( - collection: "products", - eventType: "search", - name: "homepage_popular_queries", - type: .popularQueries, - params: AnalyticsRuleCreateParams( - captureSearchRequests: true, - destinationCollection: "product_queries", - limit: 100, - ), - ruleTag: "homepage", - - )) -} - func createAPIKey() async throws -> ApiKey { let (data, _) = try await utilClient.keys().create( ApiKeySchema(actions: ["*"], collections: ["*"], description: "Test key with all privileges")) return data! diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..f12a436 --- /dev/null +++ b/compose.yml @@ -0,0 +1,9 @@ +services: + typesense: + image: typesense/typesense:30.0.rca33 + restart: on-failure + ports: + - '8108:8108' + volumes: + - ./typesense-data:/data + command: '--data-dir /data --api-key=xyz --enable-cors --enable-search-analytics=true --analytics-dir=/analytics-data' diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml index 7c474b8..6b184c3 100644 --- a/preprocessed_openapi.yml +++ b/preprocessed_openapi.yml @@ -107,6 +107,21 @@ components: required: - events type: object + AnalyticsEventsRetrieveParams: + properties: + n: + description: Number of events to return (max 1000) + type: integer + name: + description: Analytics rule name + type: string + user_id: + type: string + required: + - user_id + - name + - n + type: object AnalyticsRule: allOf: - $ref: '#/components/schemas/AnalyticsRuleCreate' @@ -2766,11 +2781,9 @@ paths: operationId: getCollections parameters: - in: query - name: limit + name: offset schema: - description: 'Number of collections to fetch. Default: returns all collections. - - ' + description: Identifies the starting point to return collections when paginating. type: integer - in: query name: exclude_fields @@ -2779,9 +2792,11 @@ paths: from the response type: string - in: query - name: offset + name: limit schema: - description: Identifies the starting point to return collections when paginating. + description: 'Number of collections to fetch. Default: returns all collections. + + ' type: integer responses: '200': @@ -2936,6 +2951,12 @@ paths: required: true schema: type: string + - in: query + name: truncate + schema: + description: When true, removes all documents from the collection while + preserving the collection and its schema. + type: boolean - in: query name: batch_size schema: @@ -2943,21 +2964,15 @@ paths: 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 - - in: query - name: ignore_not_found - schema: - type: boolean - - in: query - name: truncate - schema: - description: When true, removes all documents from the collection while - preserving the collection and its schema. - type: boolean - in: query name: filter_by schema: example: 'num_employees:>100 && country: [USA, UK]' type: string + - in: query + name: ignore_not_found + schema: + type: boolean responses: '200': content: @@ -3102,17 +3117,17 @@ paths: schema: description: List of fields from the document to exclude in the search result type: string - - in: query - name: include_fields - schema: - description: List of fields from the document to include in the search result - type: string - in: query name: filter_by schema: description: Filter conditions for refining your search results. Separate multiple conditions with &&. type: string + - in: query + name: include_fields + schema: + description: List of fields from the document to include in the search result + type: string responses: '200': content: @@ -3152,14 +3167,22 @@ paths: required: true schema: type: string + - in: query + name: action + schema: + $ref: '#/components/schemas/IndexAction' + - in: query + name: remote_embedding_batch_size + schema: + type: integer - in: query name: dirty_values schema: $ref: '#/components/schemas/DirtyValues' - in: query - name: action + name: return_doc schema: - $ref: '#/components/schemas/IndexAction' + type: boolean - in: query name: return_id schema: @@ -3167,14 +3190,6 @@ paths: import response to return the ingested document's id in the response, you can use the return_id parameter. type: boolean - - in: query - name: remote_embedding_batch_size - schema: - type: integer - - in: query - name: return_doc - schema: - type: boolean - in: query name: batch_size schema: @@ -3230,45 +3245,73 @@ paths: schema: type: string - in: query - name: min_len_2typo + name: synonym_sets 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. + description: List of synonym set names to associate with this search query + example: synonym_set_1,synonym_set_2 + type: string + - in: query + name: filter_curated_hits + schema: + 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 ' - type: integer + type: boolean - in: query - name: max_filter_by_candidates + name: highlight_full_fields 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 + description: List of fields which should be highlighted fully without snippeting + type: string - in: query - name: voice_query + name: include_fields schema: - description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. + description: List of fields from the document to include in the search result + type: string + - in: query + name: synonym_num_typos + schema: + description: 'Allow synonym resolution on typo-corrected words in the query. + Default: 0 ' - type: string + type: integer - in: query - name: highlight_fields + name: pinned_hits schema: - description: 'A list of custom fields that must be highlighted even if you - don''t query for them + 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 - in: query - name: highlight_affix_num_tokens + name: facet_query schema: - description: 'The number of tokens that should surround the highlighted - text on each side. Default: 4 + 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 + - in: query + name: group_missing_values + 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: integer + type: boolean - in: query - name: max_extra_suffix + name: max_extra_prefix 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 @@ -3277,53 +3320,30 @@ paths: By default, any number of prefixes/suffixes can be present for a match. type: integer - in: query - name: group_by - 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 - - in: query - name: offset + name: per_page schema: - description: Identifies the starting point to return hits from a result - set. Can be used as an alternative to the page parameter. + description: 'Number of results to fetch per page. Default: 10' type: integer - in: query - name: use_cache - schema: - description: 'Enable server side caching of search query results. By default, - caching is disabled. - - ' - type: boolean - - in: query - name: preset + name: snippet_threshold schema: - description: 'Search using a bunch of search parameters by setting this - parameter to the name of the existing Preset. + description: 'Field values under this length will be fully highlighted, + instead of showing a snippet of relevant portion. Default: 30 ' - type: string + type: integer - in: query - name: limit + name: conversation schema: - description: 'Number of hits to fetch. Can be used as an alternative to - the per_page parameter. Default: 10. + description: 'Enable conversational search. ' - type: integer - - in: query - name: drop_tokens_mode - schema: - $ref: '#/components/schemas/DropTokensMode' + type: boolean - in: query - name: query_by_weights + name: nl_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 + description: Whether to use natural language processing to parse the query. + type: boolean - in: query name: infix schema: @@ -3335,57 +3355,41 @@ paths: search does not produce results type: string - in: query - name: highlight_start_tag + name: highlight_end_tag schema: - description: 'The start tag used for the highlighted snippets. Default: - `` + description: 'The end tag used for the highlighted snippets. Default: `` ' type: string - in: query - name: query_by - schema: - description: A list of `string` fields that should be queried against. Multiple - fields are separated with a comma. - type: string - - in: query - name: max_candidates + name: highlight_fields schema: - description: 'Control the number of words that Typesense considers for typo - and prefix searching. + description: 'A list of custom fields that must be highlighted even if you + don''t query for them ' - type: integer + type: string - in: query - name: conversation + name: vector_query schema: - description: 'Enable conversational search. + description: 'Vector query expression for fetching documents "closest" to + a given query/document vector. ' - type: boolean - - in: query - name: q - 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 - in: query - name: facet_by - schema: - description: A list of fields that will be used for faceting your results - on. Separate multiple fields with a comma. - type: string - - in: query - name: drop_tokens_threshold + name: hidden_hits 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 + 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: integer + type: string - in: query name: remote_embedding_timeout_ms schema: @@ -3394,62 +3398,52 @@ paths: ' type: integer - in: query - name: enable_overrides + name: query_by schema: - default: false - 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 + description: A list of `string` fields that should be queried against. Multiple + fields are separated with a comma. + type: string + - in: query + name: enable_analytics + schema: + default: true + description: 'Flag for enabling/disabling analytics aggregation for specific + search queries (for e.g. those originating from a test script). ' type: boolean - in: query - name: pinned_hits + name: exhaustive_search 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`. + 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: string + type: boolean - in: query - name: pre_segmented_query + name: enable_synonyms 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 + 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 ' type: boolean - in: query - name: include_fields - schema: - description: List of fields from the document to include in the search result - type: string - - in: query - name: facet_query + name: enable_highlight_v1 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 + default: true + description: 'Flag for enabling/disabling the deprecated, old highlight + structure in the response. Default: true + + ' + type: boolean - in: query - name: max_extra_prefix + name: page 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. + description: Results from this specific page number would be fetched. type: integer - in: query name: enable_typos_for_alpha_numerical_tokens @@ -3460,64 +3454,102 @@ paths: ' type: boolean - in: query - name: facet_return_parent + name: filter_by schema: - description: 'Comma separated string of nested facet fields whose parent - object should be returned in facet response. - - ' + description: Filter conditions for refining your open api validator search + results. Separate multiple conditions with &&. + example: 'num_employees:>100 && country: [USA, UK]' type: string - in: query - name: prioritize_num_matching_fields + name: prioritize_exact_match schema: default: true - description: 'Make Typesense prioritize documents where the query words - appear in more number of fields. + description: 'Set this parameter to true to ensure that an exact match is + ranked above the others ' type: boolean - in: query - name: enable_typos_for_numerical_tokens + name: pre_segmented_query schema: - default: true - description: 'Make Typesense disable typos for numerical tokens. + 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 - in: query - name: conversation_model_id + name: typo_tokens_threshold schema: - description: 'The Id of Conversation Model to be used. + 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 + - in: query + name: prioritize_token_position + schema: + default: false + description: 'Make Typesense prioritize documents where the query words + appear earlier in the text. + + ' + type: boolean + - in: query + name: min_len_2typo + 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 + - in: query + name: group_by + 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 - in: query - name: override_tags + name: max_extra_suffix schema: - description: Comma separated list of tags to trigger the curations rules - that match the tags. + 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 + - in: query + name: q + 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 - in: query - name: stopwords + name: conversation_model_id 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. + description: 'The Id of Conversation Model to be used. ' type: string - in: query - name: facet_strategy + name: group_limit schema: - description: 'Choose the underlying faceting strategy used. Comma separated - string of allows values: exhaustive, top_values or automatic (default). + 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: string + type: integer - in: query - name: nl_model_id + name: max_facet_values schema: - description: The ID of the natural language model to use. - type: string + description: Maximum number of facet values to be returned. + type: integer - in: query name: remote_embedding_num_tries schema: @@ -3526,60 +3558,73 @@ paths: ' type: integer - in: query - name: filter_curated_hits + name: facet_return_parent schema: - 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 + description: 'Comma separated string of nested facet fields whose parent + object should be returned in facet response. ' - type: boolean + type: string - in: query - name: enable_highlight_v1 + name: enable_overrides schema: - default: true - description: 'Flag for enabling/disabling the deprecated, old highlight - structure in the response. Default: true + default: false + 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 - in: query - name: min_len_1typo + name: facet_by 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. + description: A list of fields that will be used for faceting your results + on. Separate multiple fields with a comma. + type: string + - in: query + name: stopwords + 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: integer + type: string - in: query - name: page + name: exclude_fields schema: - description: Results from this specific page number would be fetched. - type: integer + description: List of fields from the document to exclude in the search result + type: string - in: query - name: search_cutoff_ms + name: highlight_start_tag 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. + description: 'The start tag used for the highlighted snippets. Default: + `` ' - type: integer + type: string - in: query - name: exclude_fields + name: sort_by schema: - description: List of fields from the document to exclude in the search result + 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` + example: num_employees:desc type: string - in: query - name: max_facet_values + name: use_cache schema: - description: Maximum number of facet values to be returned. - type: integer + description: 'Enable server side caching of search query results. By default, + caching is disabled. + + ' + type: boolean - in: query - name: snippet_threshold + name: min_len_1typo schema: - description: 'Field values under this length will be fully highlighted, - instead of showing a snippet of relevant portion. Default: 30 + 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 @@ -3592,21 +3637,31 @@ paths: ' type: boolean - in: query - name: prefix + name: highlight_affix_num_tokens 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 + description: 'The number of tokens that should surround the highlighted + text on each side. Default: 4 + + ' + type: integer - in: query - name: enable_synonyms + name: search_cutoff_ms schema: - 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 + 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: boolean + type: integer + - in: query + name: nl_model_id + schema: + description: The ID of the natural language model to use. + type: string + - in: query + name: drop_tokens_mode + schema: + $ref: '#/components/schemas/DropTokensMode' - in: query name: num_typos schema: @@ -3616,65 +3671,37 @@ paths: ' type: string - in: query - name: prioritize_exact_match + name: prioritize_num_matching_fields schema: default: true - description: 'Set this parameter to true to ensure that an exact match is - ranked above the others + description: 'Make Typesense prioritize documents where the query words + appear in more number of fields. ' type: boolean - in: query - name: filter_by + name: voice_query schema: - description: Filter conditions for refining your open api validator search - results. Separate multiple conditions with &&. - example: 'num_employees:>100 && country: [USA, UK]' + description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. + + ' type: string - in: query - name: hidden_hits + name: conversation_id 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 - - in: query - name: group_missing_values - 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 + description: 'The Id of a previous conversation to continue, this tells + Typesense to include prior context when communicating with the LLM. ' - type: boolean - - in: query - name: highlight_full_fields - schema: - description: List of fields which should be highlighted fully without snippeting type: string - in: query - name: group_limit + name: max_candidates 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 + description: 'Control the number of words that Typesense considers for typo + and prefix searching. ' type: integer - - in: query - name: highlight_end_tag - schema: - description: 'The end tag used for the highlighted snippets. Default: `` - - ' - type: string - in: query name: split_join_tokens schema: @@ -3686,79 +3713,87 @@ paths: ' type: string - in: query - name: enable_analytics + name: query_by_weights + 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 + - in: query + name: prefix + 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 + - in: query + name: enable_typos_for_numerical_tokens schema: default: true - description: 'Flag for enabling/disabling analytics aggregation for specific - search queries (for e.g. those originating from a test script). + description: 'Make Typesense disable typos for numerical tokens. ' type: boolean - in: query - name: typo_tokens_threshold + name: limit 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 + description: 'Number of hits to fetch. Can be used as an alternative to + the per_page parameter. Default: 10. ' type: integer - in: query - name: prioritize_token_position + name: drop_tokens_threshold schema: - default: false - description: 'Make Typesense prioritize documents where the query words - appear earlier in the text. + 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: boolean + type: integer - in: query - name: vector_query + name: text_match_type schema: - description: 'Vector query expression for fetching documents "closest" to - a given query/document vector. - - ' + 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 - in: query - name: conversation_id + name: override_tags schema: - description: 'The Id of a previous conversation to continue, this tells - Typesense to include prior context when communicating with the LLM. - - ' + description: Comma separated list of tags to trigger the curations rules + that match the tags. type: string - in: query - name: synonym_sets + name: preset schema: - description: List of synonym set names to associate with this search query - example: synonym_set_1,synonym_set_2 + description: 'Search using a bunch of search parameters by setting this + parameter to the name of the existing Preset. + + ' type: string - in: query - name: exhaustive_search + name: facet_strategy 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). + description: 'Choose the underlying faceting strategy used. Comma separated + string of allows values: exhaustive, top_values or automatic (default). ' - type: boolean + type: string - in: query - name: per_page + name: offset schema: - description: 'Number of results to fetch per page. Default: 10' + description: Identifies the starting point to return hits from a result + set. Can be used as an alternative to the page parameter. type: integer - in: query - name: sort_by + name: max_filter_by_candidates 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` - example: num_employees:desc - type: string + 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 - in: query name: cache_ttl schema: @@ -3766,26 +3801,6 @@ paths: query is cached. This value can be set on a per-query basis. Default: 60. - ' - type: integer - - in: query - name: text_match_type - 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 - - in: query - name: nl_query - schema: - description: Whether to use natural language processing to parse the query. - type: boolean - - in: query - name: synonym_num_typos - schema: - description: 'Allow synonym resolution on typo-corrected words in the query. - Default: 0 - ' type: integer responses: @@ -4461,38 +4476,67 @@ paths: operationId: multiSearch parameters: - in: query - name: min_len_2typo + name: filter_curated_hits 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. + 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 ' - type: integer + type: boolean - in: query - name: voice_query + name: highlight_full_fields schema: - description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. + description: List of fields which should be highlighted fully without snippeting + type: string + - in: query + name: synonym_num_typos + schema: + description: 'Allow synonym resolution on typo-corrected words in the query. + Default: 0 ' + type: integer + - in: query + name: include_fields + schema: + description: List of fields from the document to include in the search result type: string - in: query - name: highlight_fields + name: pinned_hits schema: - description: 'A list of custom fields that must be highlighted even if you - don''t query for them + 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 - in: query - name: highlight_affix_num_tokens + name: facet_query schema: - description: 'The number of tokens that should surround the highlighted - text on each side. Default: 4 + 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 + - in: query + name: group_missing_values + 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: integer + type: boolean - in: query - name: max_extra_suffix + name: max_extra_prefix 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 @@ -4501,71 +4545,78 @@ paths: By default, any number of prefixes/suffixes can be present for a match. type: integer - in: query - name: group_by + name: highlight_fields 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. + description: 'A list of custom fields that must be highlighted even if you + don''t query for them + + ' type: string - in: query - name: offset + name: per_page schema: - description: Identifies the starting point to return hits from a result - set. Can be used as an alternative to the page parameter. + description: 'Number of results to fetch per page. Default: 10' type: integer - in: query - name: preset + name: snippet_threshold schema: - description: 'Search using a bunch of search parameters by setting this - parameter to the name of the existing Preset. + description: 'Field values under this length will be fully highlighted, + instead of showing a snippet of relevant portion. Default: 30 ' + type: integer + - in: query + name: infix + 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 - in: query - name: use_cache + name: conversation schema: - description: 'Enable server side caching of search query results. By default, - caching is disabled. + description: 'Enable conversational search. ' type: boolean - in: query - name: limit + name: highlight_end_tag schema: - description: 'Number of hits to fetch. Can be used as an alternative to - the per_page parameter. Default: 10. + description: 'The end tag used for the highlighted snippets. Default: `` ' - type: integer - - in: query - name: drop_tokens_mode - schema: - $ref: '#/components/schemas/DropTokensMode' + type: string - in: query - name: query_by_weights + name: vector_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. + description: 'Vector query expression for fetching documents "closest" to + a given query/document vector. + + ' type: string - in: query - name: infix + name: hidden_hits 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 + 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 - in: query - name: highlight_start_tag + name: remote_embedding_timeout_ms schema: - description: 'The start tag used for the highlighted snippets. Default: - `` + description: 'Timeout (in milliseconds) for fetching remote embeddings. ' - type: string + type: integer - in: query name: query_by schema: @@ -4573,88 +4624,95 @@ paths: fields are separated with a comma. type: string - in: query - name: conversation + name: enable_analytics schema: - description: 'Enable conversational search. + default: true + description: 'Flag for enabling/disabling analytics aggregation for specific + search queries (for e.g. those originating from a test script). ' type: boolean - in: query - name: q + name: exhaustive_search 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 + 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 - in: query - name: facet_by + name: enable_synonyms schema: - description: A list of fields that will be used for faceting your results - on. Separate multiple fields with a comma. - type: string + 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 + + ' + type: boolean - in: query - name: drop_tokens_threshold + name: page 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 + description: Results from this specific page number would be fetched. + type: integer + - in: query + name: enable_typos_for_alpha_numerical_tokens + schema: + description: 'Set this parameter to false to disable typos on alphanumerical + query tokens. Default: true. ' - type: integer + type: boolean - in: query - name: remote_embedding_timeout_ms + name: filter_by schema: - description: 'Timeout (in milliseconds) for fetching remote embeddings. + description: Filter conditions for refining youropen api validator search + results. Separate multiple conditions with &&. + example: 'num_employees:>100 && country: [USA, UK]' + type: string + - in: query + name: prioritize_exact_match + schema: + default: true + description: 'Set this parameter to true to ensure that an exact match is + ranked above the others ' - type: integer + type: boolean - in: query - name: enable_overrides + name: prioritize_token_position schema: default: false - 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 + description: 'Make Typesense prioritize documents where the query words + appear earlier in the text. ' type: boolean - in: query - name: pinned_hits + name: typo_tokens_threshold 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`. + 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: string + type: integer - in: query - name: facet_query + name: group_by 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". + 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 - in: query - name: enable_typos_for_alpha_numerical_tokens + name: min_len_2typo schema: - description: 'Set this parameter to false to disable typos on alphanumerical - query tokens. Default: true. + 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: boolean - - in: query - name: include_fields - schema: - description: List of fields from the document to include in the search result - type: string + type: integer - in: query name: pre_segmented_query schema: @@ -4667,15 +4725,53 @@ paths: ' type: boolean - - in: query - name: max_extra_prefix - 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 + - in: query + name: max_extra_suffix + 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 + - in: query + name: q + 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 + - in: query + name: conversation_model_id + schema: + description: 'The Id of Conversation Model to be used. + + ' + type: string + - in: query + name: group_limit + 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 + - in: query + name: max_facet_values + schema: + description: Maximum number of facet values to be returned. + type: integer + - in: query + name: enable_overrides + schema: + default: false + 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 - in: query name: facet_return_parent schema: @@ -4685,67 +4781,51 @@ paths: ' type: string - in: query - name: prioritize_num_matching_fields + name: remote_embedding_num_tries schema: - default: true - description: 'Make Typesense prioritize documents where the query words - appear in more number of fields. + description: 'Number of times to retry fetching remote embeddings. ' - type: boolean + type: integer - in: query - name: override_tags + name: facet_by schema: - description: Comma separated list of tags to trigger the curations rules - that match the tags. + description: A list of fields that will be used for faceting your results + on. Separate multiple fields with a comma. type: string - in: query - name: conversation_model_id + name: sort_by schema: - description: 'The Id of Conversation Model to be used. - - ' + 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 - in: query - name: enable_typos_for_numerical_tokens + name: synonym_prefix schema: - default: true - description: 'Make Typesense disable typos for numerical tokens. + description: 'Allow synonym resolution on word prefixes in the query. Default: + false ' type: boolean - in: query - name: stopwords + name: highlight_start_tag 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. + description: 'The start tag used for the highlighted snippets. Default: + `` ' type: string - in: query - name: facet_strategy + name: stopwords schema: - description: 'Choose the underlying faceting strategy used. Comma separated - string of allows values: exhaustive, top_values or automatic (default). + 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 - - in: query - name: remote_embedding_num_tries - schema: - description: 'Number of times to retry fetching remote embeddings. - - ' - type: integer - - in: query - name: filter_curated_hits - schema: - 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 - - ' - type: boolean - in: query name: min_len_1typo schema: @@ -4760,14 +4840,20 @@ paths: description: List of fields from the document to exclude in the search result type: string - in: query - name: max_facet_values + name: use_cache schema: - description: Maximum number of facet values to be returned. - type: integer + description: 'Enable server side caching of search query results. By default, + caching is disabled. + + ' + type: boolean - in: query - name: page + name: highlight_affix_num_tokens schema: - description: Results from this specific page number would be fetched. + description: 'The number of tokens that should surround the highlighted + text on each side. Default: 4 + + ' type: integer - in: query name: search_cutoff_ms @@ -4779,28 +4865,9 @@ paths: ' type: integer - in: query - name: snippet_threshold - schema: - description: 'Field values under this length will be fully highlighted, - instead of showing a snippet of relevant portion. Default: 30 - - ' - type: integer - - in: query - name: synonym_prefix - schema: - description: 'Allow synonym resolution on word prefixes in the query. Default: - false - - ' - type: boolean - - in: query - name: prefix + name: drop_tokens_mode 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 + $ref: '#/components/schemas/DropTokensMode' - in: query name: num_typos schema: @@ -4810,141 +4877,104 @@ paths: ' type: string - in: query - name: enable_synonyms - schema: - 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 - - ' - type: boolean - - in: query - name: prioritize_exact_match + name: prioritize_num_matching_fields schema: default: true - description: 'Set this parameter to true to ensure that an exact match is - ranked above the others + description: 'Make Typesense prioritize documents where the query words + appear in more number of fields. ' type: boolean - in: query - name: filter_by + name: prefix schema: - description: Filter conditions for refining youropen api validator search - results. Separate multiple conditions with &&. - example: 'num_employees:>100 && country: [USA, UK]' + 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 - in: query - name: hidden_hits + name: voice_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`. + description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. ' type: string - in: query - name: group_missing_values + name: conversation_id 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 + description: 'The Id of a previous conversation to continue, this tells + Typesense to include prior context when communicating with the LLM. ' - type: boolean - - in: query - name: highlight_full_fields - schema: - description: List of fields which should be highlighted fully without snippeting type: string - in: query - name: group_limit - 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 - - in: query - name: highlight_end_tag + name: query_by_weights schema: - description: 'The end tag used for the highlighted snippets. Default: `` - - ' + 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 - in: query - name: enable_analytics + name: enable_typos_for_numerical_tokens schema: default: true - description: 'Flag for enabling/disabling analytics aggregation for specific - search queries (for e.g. those originating from a test script). + description: 'Make Typesense disable typos for numerical tokens. ' type: boolean - in: query - name: typo_tokens_threshold + name: limit 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 + description: 'Number of hits to fetch. Can be used as an alternative to + the per_page parameter. Default: 10. ' type: integer - in: query - name: vector_query + name: drop_tokens_threshold schema: - description: 'Vector query expression for fetching documents "closest" to - a given query/document vector. + 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 + - in: query + name: text_match_type + 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 - in: query - name: conversation_id + name: preset schema: - description: 'The Id of a previous conversation to continue, this tells - Typesense to include prior context when communicating with the LLM. + description: 'Search using a bunch of search parameters by setting this + parameter to the name of the existing Preset. ' type: string - in: query - name: prioritize_token_position + name: override_tags schema: - default: false - description: 'Make Typesense prioritize documents where the query words - appear earlier in the text. - - ' - type: boolean + description: Comma separated list of tags to trigger the curations rules + that match the tags. + type: string - in: query - name: exhaustive_search + name: facet_strategy 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). + description: 'Choose the underlying faceting strategy used. Comma separated + string of allows values: exhaustive, top_values or automatic (default). ' - type: boolean + type: string - in: query - name: per_page + name: offset schema: - description: 'Number of results to fetch per page. Default: 10' + description: Identifies the starting point to return hits from a result + set. Can be used as an alternative to the page parameter. type: integer - - in: query - name: sort_by - 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 - in: query name: cache_ttl schema: @@ -4952,21 +4982,6 @@ paths: query is cached. This value can be set on a per-query basis. Default: 60. - ' - type: integer - - in: query - name: text_match_type - 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 - - in: query - name: synonym_num_typos - schema: - description: 'Allow synonym resolution on typo-corrected words in the query. - Default: 0 - ' type: integer requestBody: From 56d904708dd8ef8635d3e0d3c29a0febe2cdee32 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Thu, 4 Dec 2025 23:42:32 +0700 Subject: [PATCH 06/21] feat: union search, multi-search with generic parameter pack --- Sources/Typesense/MultiSearch.swift | 240 +++-------------- .../AnalyticsRuleCreateManyResponse.swift | 2 +- .../Shared/MultiSearchResultPack.swift | 45 ++++ Tests/TypesenseTests/MultiSearchTests.swift | 248 ++++++++++++------ Tests/TypesenseTests/TestUtils.swift | 2 +- 5 files changed, 255 insertions(+), 282 deletions(-) create mode 100644 Sources/Typesense/Shared/MultiSearchResultPack.swift diff --git a/Sources/Typesense/MultiSearch.swift b/Sources/Typesense/MultiSearch.swift index ef95d1e..cead0b0 100644 --- a/Sources/Typesense/MultiSearch.swift +++ b/Sources/Typesense/MultiSearch.swift @@ -11,239 +11,69 @@ public struct MultiSearch { self.apiCall = apiCall } - public func perform(searchRequests: [MultiSearchCollectionParameters], commonParameters: MultiSearchParameters, union: Bool = false) async throws -> (Data?, URLResponse?) { + public func perform(searchRequests: [MultiSearchCollectionParameters], commonParameters: MultiSearchParameters) async throws -> (Data?, URLResponse?) { let queryParams = try createURLQuery(forSchema: commonParameters) let searchesData = try encoder.encode(MultiSearchSearchesParameter(searches: searchRequests)) return try await apiCall.post(endPoint: "\(RESOURCEPATH)", body: searchesData, queryParameters: queryParams) } - public func perform(searchRequests: [MultiSearchCollectionParameters], commonParameters: MultiSearchParameters, for: T.Type) async throws -> (MultiSearchResult?, URLResponse?) { - var searchQueryParams: [URLQueryItem] = [] - - if let query = commonParameters.q { - searchQueryParams.append(URLQueryItem(name: "q", value: query)) - } - - if let queryBy = commonParameters.queryBy { - searchQueryParams.append(URLQueryItem(name: "query_by", value: queryBy)) - } - - if let queryByWeights = commonParameters.queryByWeights { - searchQueryParams.append(URLQueryItem(name: "query_by_weights", value: queryByWeights)) - } - - if let textMatchType = commonParameters.textMatchType { - searchQueryParams.append(URLQueryItem(name: "text_match_type", value: textMatchType)) - } - - if let _prefix = commonParameters._prefix { - searchQueryParams.append(URLQueryItem(name: "prefix", value: _prefix)) - } - - if let _infix = commonParameters._infix { - searchQueryParams.append(URLQueryItem(name: "infix", value: _infix)) - } - - if let maxExtraPrefix = commonParameters.maxExtraPrefix { - searchQueryParams.append(URLQueryItem(name: "max_extra_prefix", value: String(maxExtraPrefix))) - } - - if let maxExtraSuffix = commonParameters.maxExtraSuffix { - searchQueryParams.append(URLQueryItem(name: "max_extra_suffix", value: String(maxExtraSuffix))) - } - - if let filterBy = commonParameters.filterBy { - searchQueryParams.append(URLQueryItem(name: "filter_by", value: filterBy)) - } - - if let sortBy = commonParameters.sortBy { - searchQueryParams.append(URLQueryItem(name: "sort_by", value: sortBy)) - } - - if let facetBy = commonParameters.facetBy { - searchQueryParams.append(URLQueryItem(name: "facet_by", value: facetBy)) - } - - if let maxFacetValues = commonParameters.maxFacetValues { - searchQueryParams.append(URLQueryItem(name: "max_facet_values", value: String(maxFacetValues))) - } - - if let facetQuery = commonParameters.facetQuery { - searchQueryParams.append(URLQueryItem(name: "facet_query", value: facetQuery)) - } - - if let numTypos = commonParameters.numTypos { - searchQueryParams.append(URLQueryItem(name: "num_typos", value: String(numTypos))) - } - - if let page = commonParameters.page { - searchQueryParams.append(URLQueryItem(name: "page", value: String(page))) - } - - if let perPage = commonParameters.perPage { - searchQueryParams.append(URLQueryItem(name: "per_page", value: String(perPage))) - } - - if let limit = commonParameters.limit { - searchQueryParams.append(URLQueryItem(name: "limit", value: String(limit))) - } - - if let offset = commonParameters.offset { - searchQueryParams.append(URLQueryItem(name: "offset", value: String(offset))) - } - - if let groupBy = commonParameters.groupBy { - searchQueryParams.append(URLQueryItem(name: "group_by", value: groupBy)) - } - - if let groupLimit = commonParameters.groupLimit { - searchQueryParams.append(URLQueryItem(name: "group_limit", value: String(groupLimit))) - } - - if let groupMissingValues = commonParameters.groupMissingValues { - searchQueryParams.append(URLQueryItem(name: "group_missing_values", value: String(groupMissingValues))) - } - - if let includeFields = commonParameters.includeFields { - searchQueryParams.append(URLQueryItem(name: "include_fields", value: includeFields)) - } - - if let excludeFields = commonParameters.excludeFields { - searchQueryParams.append(URLQueryItem(name: "exclude_fields", value: excludeFields)) - } - - if let highlightFullFields = commonParameters.highlightFullFields { - searchQueryParams.append(URLQueryItem(name: "highlight_full_fields", value: highlightFullFields)) - } - - if let highlightAffixNumTokens = commonParameters.highlightAffixNumTokens { - searchQueryParams.append(URLQueryItem(name: "highlight_affix_num_tokens", value: String(highlightAffixNumTokens))) - } - - if let highlightStartTag = commonParameters.highlightStartTag { - searchQueryParams.append(URLQueryItem(name: "highlight_start_tag", value: highlightStartTag)) - } - - if let highlightEndTag = commonParameters.highlightEndTag { - searchQueryParams.append(URLQueryItem(name: "highlight_end_tag", value: highlightEndTag)) - } - - if let snippetThreshold = commonParameters.snippetThreshold { - searchQueryParams.append(URLQueryItem(name: "snippet_threshold", value: String(snippetThreshold))) - } - - if let dropTokensThreshold = commonParameters.dropTokensThreshold { - searchQueryParams.append(URLQueryItem(name: "drop_tokens_threshold", value: String(dropTokensThreshold))) - } - - if let typoTokensThreshold = commonParameters.typoTokensThreshold { - searchQueryParams.append(URLQueryItem(name: "typo_tokens_threshold", value: String(typoTokensThreshold))) - } - - if let pinnedHits = commonParameters.pinnedHits { - searchQueryParams.append(URLQueryItem(name: "pinned_hits", value: pinnedHits)) - } - - if let hiddenHits = commonParameters.hiddenHits { - searchQueryParams.append(URLQueryItem(name: "hidden_hits", value: hiddenHits)) - } - - if let overrideTags = commonParameters.overrideTags { - searchQueryParams.append(URLQueryItem(name: "override_tags", value: overrideTags)) - } - - if let highlightFields = commonParameters.highlightFields { - searchQueryParams.append(URLQueryItem(name: "highlight_fields", value: highlightFields)) - } - - if let preSegmentedQuery = commonParameters.preSegmentedQuery { - searchQueryParams.append(URLQueryItem(name: "pre_segmented_query", value: String(preSegmentedQuery))) - } - - if let preset = commonParameters.preset { - searchQueryParams.append(URLQueryItem(name: "preset", value: preset)) - } - - if let enableOverrides = commonParameters.enableOverrides { - searchQueryParams.append(URLQueryItem(name: "enable_overrides", value: String(enableOverrides))) - } - - if let prioritizeExactMatch = commonParameters.prioritizeExactMatch { - searchQueryParams.append(URLQueryItem(name: "prioritize_exact_match", value: String(prioritizeExactMatch))) - } - - if let prioritizeTokenPosition = commonParameters.prioritizeTokenPosition { - searchQueryParams.append(URLQueryItem(name: "prioritize_token_position", value: String(prioritizeTokenPosition))) - } - - if let prioritizeNumMatchingFields = commonParameters.prioritizeNumMatchingFields { - searchQueryParams.append(URLQueryItem(name: "prioritize_num_matching_fields", value: String(prioritizeNumMatchingFields))) - } - - if let enableTyposForNumericalTokens = commonParameters.enableTyposForNumericalTokens { - searchQueryParams.append(URLQueryItem(name: "enable_typos_for_numerical_tokens", value: String(enableTyposForNumericalTokens))) - } - - if let exhaustiveSearch = commonParameters.exhaustiveSearch { - searchQueryParams.append(URLQueryItem(name: "exhaustive_search", value: String(exhaustiveSearch))) - } + public func performUnion(searchRequests: [MultiSearchCollectionParameters], commonParameters: MultiSearchParameters) async throws -> (Data?, URLResponse?) { + let queryParams = try createURLQuery(forSchema: commonParameters) + let searchesData = try encoder.encode(MultiSearchSearchesParameter(searches: searchRequests, union: true)) - if let searchCutoffMs = commonParameters.searchCutoffMs { - searchQueryParams.append(URLQueryItem(name: "search_cutoff_ms", value: String(searchCutoffMs))) - } + return try await apiCall.post(endPoint: "\(RESOURCEPATH)", body: searchesData, queryParameters: queryParams) + } - if let useCache = commonParameters.useCache { - searchQueryParams.append(URLQueryItem(name: "use_cache", value: String(useCache))) - } + public func perform(searchRequests: [MultiSearchCollectionParameters], commonParameters: MultiSearchParameters, for: T.Type) async throws -> (MultiSearchResult?, URLResponse?) { + let queryParams = try createURLQuery(forSchema: commonParameters) + let searches = MultiSearchSearchesParameter(searches: searchRequests) - if let cacheTtl = commonParameters.cacheTtl { - searchQueryParams.append(URLQueryItem(name: "cache_ttl", value: String(cacheTtl))) - } + let searchesData = try encoder.encode(searches) - if let minLen1typo = commonParameters.minLen1typo { - searchQueryParams.append(URLQueryItem(name: "min_len1type", value: String(minLen1typo))) - } + let (data, response) = try await apiCall.post(endPoint: "\(RESOURCEPATH)", body: searchesData, queryParameters: queryParams) - if let minLen2typo = commonParameters.minLen2typo { - searchQueryParams.append(URLQueryItem(name: "min_len2type", value: String(minLen2typo))) + if let validData = data { + let searchRes = try decoder.decode(MultiSearchResult.self, from: validData) + return (searchRes, response) } - if let vectorQuery = commonParameters.vectorQuery { - searchQueryParams.append(URLQueryItem(name: "vector_query", value: vectorQuery)) - } + return (nil, response) + } - if let remoteEmbeddingTimeoutMS = commonParameters.remoteEmbeddingTimeoutMs { - searchQueryParams.append(URLQueryItem(name: "remote_embedding_timeout_ms", value: String(remoteEmbeddingTimeoutMS))) - } + @available(macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, visionOS 1.0, *) + public func perform(searchRequests: [MultiSearchCollectionParameters], commonParameters: MultiSearchParameters, for types: (repeat (each T).Type) +) async throws -> (MultiSearchResultPack?, URLResponse?) { + let queryParams = try createURLQuery(forSchema: commonParameters) + let searches = MultiSearchSearchesParameter(searches: searchRequests) - if let remoteEmbeddingNumTries = commonParameters.remoteEmbeddingNumTries { - searchQueryParams.append(URLQueryItem(name: "remote_embedding_num_tries", value: String(remoteEmbeddingNumTries))) - } + let searchesData = try encoder.encode(searches) - if let facetStrategy = commonParameters.facetStrategy { - searchQueryParams.append(URLQueryItem(name: "facet_strategy", value: facetStrategy)) - } + let (data, response) = try await apiCall.post(endPoint: "\(RESOURCEPATH)", body: searchesData, queryParameters: queryParams) - if let stopwords = commonParameters.stopwords { - searchQueryParams.append(URLQueryItem(name: "stopwords", value: stopwords)) + if let validData = data { + let searchRes = try decoder.decode(MultiSearchResultPack.self, from: validData) + return (searchRes, response) } - if let facetReturnParent = commonParameters.facetReturnParent { - searchQueryParams.append(URLQueryItem(name: "facet_strategy", value: facetReturnParent)) - } + return (nil, response) + } - let searches = MultiSearchSearchesParameter(searches: searchRequests) + public func performUnion(searchRequests: [MultiSearchCollectionParameters], commonParameters: MultiSearchParameters, for: T.Type) async throws -> (SearchResult?, URLResponse?) { + let queryParams = try createURLQuery(forSchema: commonParameters) + let searches = MultiSearchSearchesParameter(searches: searchRequests, union: true) let searchesData = try encoder.encode(searches) - let (data, response) = try await apiCall.post(endPoint: "\(RESOURCEPATH)", body: searchesData, queryParameters: searchQueryParams) + let (data, response) = try await apiCall.post(endPoint: "\(RESOURCEPATH)", body: searchesData, queryParameters: queryParams) if let validData = data { - let searchRes = try decoder.decode(MultiSearchResult.self, from: validData) + let searchRes = try decoder.decode(SearchResult.self, from: validData) return (searchRes, response) } return (nil, response) } + + } diff --git a/Sources/Typesense/Shared/AnalyticsRuleCreateManyResponse.swift b/Sources/Typesense/Shared/AnalyticsRuleCreateManyResponse.swift index 056324e..fb64661 100644 --- a/Sources/Typesense/Shared/AnalyticsRuleCreateManyResponse.swift +++ b/Sources/Typesense/Shared/AnalyticsRuleCreateManyResponse.swift @@ -24,7 +24,7 @@ public enum AnalyticsRuleCreateManyResponseItem: Codable { } else if let value = try? container.decode(CreateAnalyticsRuleError.self) { self = .error(value) } else { - throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of PresetUpsertSchemaValue")) + throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of AnalyticsRuleCreateManyResponseItem")) } } } diff --git a/Sources/Typesense/Shared/MultiSearchResultPack.swift b/Sources/Typesense/Shared/MultiSearchResultPack.swift new file mode 100644 index 0000000..3fc08d7 --- /dev/null +++ b/Sources/Typesense/Shared/MultiSearchResultPack.swift @@ -0,0 +1,45 @@ +import Foundation + + +public enum MultiSearchResultPackCodingKeys: String, CodingKey { + case conversation + case results +} + +@available(macOS 14.0, iOS 17.0, tvOS 17.0, watchOS 10.0, visionOS 1.0, *) +public struct MultiSearchResultPack: Codable { + + public var conversation: SearchResultConversation? + public var results: (repeat MultiSearchResultItem) + + public init(results: (repeat MultiSearchResultItem), conversation: SearchResultConversation? = nil) { + self.conversation = conversation + self.results = results + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: MultiSearchResultPackCodingKeys.self) + self.conversation = try container.decodeIfPresent(SearchResultConversation.self, forKey: .conversation) + + var resultsContainer = try container.nestedUnkeyedContainer(forKey: .results) + + self.results = (repeat try resultsContainer.decode(MultiSearchResultItem.self)) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: MultiSearchResultPackCodingKeys.self) + try container.encodeIfPresent(conversation, forKey: .conversation) + + var resultsContainer = container.nestedUnkeyedContainer(forKey: .results) + + let mirror = Mirror(reflecting: results) + for child in mirror.children { + guard let value = child.value as? Encodable else { + continue + } + + let superEncoder = resultsContainer.superEncoder() + try value.encode(to: superEncoder) + } + } +} diff --git a/Tests/TypesenseTests/MultiSearchTests.swift b/Tests/TypesenseTests/MultiSearchTests.swift index 1fed0f4..1dc2d58 100644 --- a/Tests/TypesenseTests/MultiSearchTests.swift +++ b/Tests/TypesenseTests/MultiSearchTests.swift @@ -2,29 +2,57 @@ import XCTest @testable import Typesense final class MultiSearchTests: XCTestCase { - override func tearDown() async throws { - try await tearDownCollections() - } - - struct Brand: Codable { - var name: String - } - - - func testMultiSearch() async { + override func setUp() async throws { let productSchema = CollectionSchema(fields: [ Field(name: "name", type: "string"), Field(name: "price", type: "int32"), Field(name: "brand", type: "string"), Field(name: "desc", type: "string"), ], name: "products") - let brandSchema = CollectionSchema(fields: [ Field(name: "name", type: "string"), ], name: "brands") + + let _ = try await client.collections().create(schema: productSchema) + let _ = try await client.collections().create(schema: brandSchema) + } + + override func tearDown() async throws { + try await tearDownCollections() + } + + struct Brand: Codable, Equatable { + var name: String + } + + enum ProductOrBrand: Codable { + case brand(Brand) + case product(Product) + + // Define keys to look for the discriminator + enum CodingKeys: String, CodingKey { + case type // Assuming your JSON has a field distinguishing the data + } + + public func encode(to encoder: Encoder) throws {} + + init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if let value = try? container.decode(Product.self) { + self = .product(value) + } else if let value = try? container.decode(Brand.self) { + self = .brand(value) + } else { + throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of ProductOrBrand")) + } + } + } + + + func testMultiSearch() async { let searchRequests = [ - MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "shoe", collection: "products"), + MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "Jor", collection: "products"), MultiSearchCollectionParameters(q: "Nike", collection: "brands"), ] @@ -34,25 +62,12 @@ final class MultiSearchTests: XCTestCase { let commonParams = MultiSearchParameters(queryBy: "name") do { - do { - let _ = try await client.collections().create(schema: productSchema) - } catch (let error) { - print(error.localizedDescription) - XCTAssertTrue(false) - } - - do { - let _ = try await client.collections().create(schema: brandSchema) - } catch (let error) { - print(error.localizedDescription) - XCTAssertTrue(false) - } let (_,_) = try await client.collection(name: "products").documents().create(document: encoder.encode(product1)) let (_,_) = try await client.collection(name: "brands").documents().create(document: encoder.encode(brand1)) - let (data, _) = try await client.multiSearch().perform(searchRequests: searchRequests, commonParameters: commonParams, for: Product.self) + let (data, _) = try await client.multiSearch().perform(searchRequests: searchRequests, commonParameters: commonParams, for: ProductOrBrand.self) XCTAssertNotNil(data) @@ -66,6 +81,18 @@ final class MultiSearchTests: XCTestCase { XCTAssertNotNil(validResp.results[1].hits) XCTAssertEqual(validResp.results[1].hits?.count, 1) + if case let .product(product) = validResp.results[0].hits![0].document { + XCTAssertEqual(product.name, product1.name) + }else{ + XCTAssertTrue(false) + } + + if case let .brand(brand) = validResp.results[1].hits![0].document { + XCTAssertEqual(brand.name, brand1.name) + }else{ + XCTAssertTrue(false) + } + print(validResp.results[1].hits as Any) } catch HTTPError.serverError(let code, let desc) { print(desc) @@ -79,16 +106,6 @@ final class MultiSearchTests: XCTestCase { } func testMultiSearchReturnRawData() async { - let productSchema = CollectionSchema(fields: [ - Field(name: "name", type: "string"), - Field(name: "price", type: "int32"), - Field(name: "brand", type: "string"), - Field(name: "desc", type: "string"), - ], name: "products") - - let brandSchema = CollectionSchema(fields: [ - Field(name: "name", type: "string"), - ], name: "brands") let searchRequests = [ MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "shoe", collection: "products"), @@ -101,20 +118,6 @@ final class MultiSearchTests: XCTestCase { let commonParams = MultiSearchParameters(queryBy: "name") do { - do { - let _ = try await client.collections().create(schema: productSchema) - } catch (let error) { - print(error.localizedDescription) - XCTAssertTrue(false) - } - - do { - let _ = try await client.collections().create(schema: brandSchema) - } catch (let error) { - print(error.localizedDescription) - XCTAssertTrue(false) - } - let (_,_) = try await client.collection(name: "products").documents().create(document: encoder.encode(product1)) let (_,_) = try await client.collection(name: "brands").documents().create(document: encoder.encode(brand1)) @@ -143,16 +146,6 @@ final class MultiSearchTests: XCTestCase { } func testMultiSearchWithPreset() async { - let productSchema = CollectionSchema(fields: [ - Field(name: "name", type: "string"), - Field(name: "price", type: "int32"), - Field(name: "brand", type: "string"), - Field(name: "desc", type: "string"), - ], name: "products") - - let brandSchema = CollectionSchema(fields: [ - Field(name: "name", type: "string"), - ], name: "brands") let preset = PresetUpsertSchema( value: .typeMultiSearchSearchesParameter(MultiSearchSearchesParameter( @@ -171,25 +164,12 @@ final class MultiSearchTests: XCTestCase { do { let _ = try await client.presets().upsert(presetName: "test-multi-search", params: preset) - do { - let _ = try await client.collections().create(schema: productSchema) - } catch (let error) { - print(error.localizedDescription) - XCTAssertTrue(false) - } - - do { - let _ = try await client.collections().create(schema: brandSchema) - } catch (let error) { - print(error.localizedDescription) - XCTAssertTrue(false) - } let (_,_) = try await client.collection(name: "products").documents().create(document: encoder.encode(product1)) let (_,_) = try await client.collection(name: "brands").documents().create(document: encoder.encode(brand1)) - let (data, _) = try await client.multiSearch().perform(searchRequests: [], commonParameters: commonParams, for: Product.self) + let (data, _) = try await client.multiSearch().perform(searchRequests: [], commonParameters: commonParams, for: ProductOrBrand.self) XCTAssertNotNil(data) @@ -209,12 +189,130 @@ final class MultiSearchTests: XCTestCase { print("The response status code is \(code)") XCTAssertTrue(false) } catch (let error) { - print(error.localizedDescription) + print(error) XCTAssertTrue(false) } try? await tearDownPresets() } + func testMultiSearchUnionReturnRawData() async { + let searchRequests = [ + MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "shoe", collection: "products"), + MultiSearchCollectionParameters(q: "Nike", collection: "brands"), + ] + + let brand1 = Brand(name: "Nike") + let product1 = Product(name: "Jordan", price: 70, brand: "Nike", desc: "High quality shoe") + + let commonParams = MultiSearchParameters(queryBy: "name") + + do { + let (_,_) = try await client.collection(name: "products").documents().create(document: encoder.encode(product1)) + + let (_,_) = try await client.collection(name: "brands").documents().create(document: encoder.encode(brand1)) + + let (data, _) = try await client.multiSearch().performUnion(searchRequests: searchRequests, commonParameters: commonParams) + guard let validData = data else { + throw DataError.dataNotFound + } + if let json = try JSONSerialization.jsonObject(with: validData, options: []) as? [String: Any]{ + print(json) + XCTAssertNotNil(json["hits"]) + } else{ + XCTAssertTrue(false) + } + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error.localizedDescription) + XCTAssertTrue(false) + } + + } + + func testMultiSearchUnion() async { + let searchRequests = [ + MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "shoe", collection: "products"), + MultiSearchCollectionParameters(q: "Nike", collection: "brands"), + ] + + let brand1 = Brand(name: "Nike") + let product1 = Product(name: "Jordan", price: 70, brand: "Nike", desc: "High quality shoe") + + let commonParams = MultiSearchParameters(queryBy: "name") + + do { + + let (_,_) = try await client.collection(name: "products").documents().create(document: encoder.encode(product1)) + + let (_,_) = try await client.collection(name: "brands").documents().create(document: encoder.encode(brand1)) + + let (data, _) = try await client.multiSearch().performUnion(searchRequests: searchRequests, commonParameters: commonParams, for: ProductOrBrand.self) + + + XCTAssertNotNil(data) + guard let validResp = data else { + throw DataError.dataNotFound + } + + XCTAssertNotNil(validResp.hits) + XCTAssertNotEqual(validResp.hits!.count, 0) + if case let .product(product) = validResp.hits![0].document { + XCTAssertEqual(product.name, product1.name) + } else if case let .brand(brand) = validResp.hits![0].document { + XCTAssertEqual(brand.name, brand1.name) + } + + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error.localizedDescription) + XCTAssertTrue(false) + } + + } + + func testMultiSearchPack() async { + let searchRequests = [ + MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "Jor", collection: "products"), + MultiSearchCollectionParameters(q: "Nike", collection: "brands"), + ] + + let brand1 = Brand(name: "Nike") + let product1 = Product(name: "Jordan", price: 70, brand: "Nike", desc: "High quality shoe") + + let commonParams = MultiSearchParameters(queryBy: "name") + + do { + + let (_,_) = try await client.collection(name: "products").documents().create(document: encoder.encode(product1)) + + let (_,_) = try await client.collection(name: "brands").documents().create(document: encoder.encode(brand1)) + + let (data, _) = try await client.multiSearch().perform(searchRequests: searchRequests, commonParameters: commonParams, for: (Product.self, Brand.self)) + + + XCTAssertNotNil(data) + guard let validResp = data else { + throw DataError.dataNotFound + } + + XCTAssertEqual(validResp.results.0.hits?[0].document, product1) + XCTAssertEqual(validResp.results.1.hits?[0].document, brand1) + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error.localizedDescription) + XCTAssertTrue(false) + } + + } } diff --git a/Tests/TypesenseTests/TestUtils.swift b/Tests/TypesenseTests/TestUtils.swift index d1c492f..9b02584 100644 --- a/Tests/TypesenseTests/TestUtils.swift +++ b/Tests/TypesenseTests/TestUtils.swift @@ -139,7 +139,7 @@ func createConversationCollection() async throws { struct Product: Codable, Equatable { var name: String? - var price: Int? + var price: Int var brand: String? var desc: String? From 079d17e571a83ea8e3d58979bc0e0804d81f0a0d Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sat, 6 Dec 2025 11:51:52 +0700 Subject: [PATCH 07/21] feat: v30 curation API --- Sources/Typesense/Client.swift | 10 +- Sources/Typesense/Collection.swift | 8 - Sources/Typesense/CurationSet.swift | 47 ++++++ Sources/Typesense/CurationSetItem.swift | 41 ++++++ Sources/Typesense/CurationSetItems.swift | 46 ++++++ Sources/Typesense/CurationSets.swift | 44 ++++++ Sources/Typesense/Override.swift | 42 ------ Sources/Typesense/Overrides.swift | 48 ------ Tests/TypesenseTests/CurationSetTests.swift | 147 +++++++++++++++++++ Tests/TypesenseTests/CurationSetsTests.swift | 58 ++++++++ Tests/TypesenseTests/OverrideTests.swift | 51 ------- Tests/TypesenseTests/OverridesTests.swift | 74 ---------- Tests/TypesenseTests/TestUtils.swift | 31 +++- 13 files changed, 416 insertions(+), 231 deletions(-) create mode 100644 Sources/Typesense/CurationSet.swift create mode 100644 Sources/Typesense/CurationSetItem.swift create mode 100644 Sources/Typesense/CurationSetItems.swift create mode 100644 Sources/Typesense/CurationSets.swift delete mode 100644 Sources/Typesense/Override.swift delete mode 100644 Sources/Typesense/Overrides.swift create mode 100644 Tests/TypesenseTests/CurationSetTests.swift create mode 100644 Tests/TypesenseTests/CurationSetsTests.swift delete mode 100644 Tests/TypesenseTests/OverrideTests.swift delete mode 100644 Tests/TypesenseTests/OverridesTests.swift diff --git a/Sources/Typesense/Client.swift b/Sources/Typesense/Client.swift index a7b5ca4..fcb619e 100644 --- a/Sources/Typesense/Client.swift +++ b/Sources/Typesense/Client.swift @@ -9,7 +9,7 @@ public struct Client { self.configuration = config self.apiCall = ApiCall(config: config) } - + public func collections() -> Collections { return Collections(apiCall: apiCall) } @@ -22,6 +22,14 @@ public struct Client { return Conversations(apiCall: apiCall) } + public func curationSets() -> CurationSets { + return CurationSets(apiCall: apiCall) + } + + public func curationSet(_ name: String) -> CurationSet { + return CurationSet(apiCall: apiCall, curationSetName: name) + } + public func keys() -> ApiKeys { return ApiKeys(apiCall: apiCall) } diff --git a/Sources/Typesense/Collection.swift b/Sources/Typesense/Collection.swift index 95eef68..756a496 100644 --- a/Sources/Typesense/Collection.swift +++ b/Sources/Typesense/Collection.swift @@ -43,14 +43,6 @@ public struct Collection { return Synonyms(apiCall: apiCall, collectionName: self.collectionName) } - public func overrides() -> Overrides{ - return Overrides(apiCall: self.apiCall, collectionName: self.collectionName) - } - - public func override(_ overrideId: String) -> Override{ - return Override(apiCall: self.apiCall, collectionName: self.collectionName, overrideId: overrideId) - } - private func endpointPath() throws -> String { return "\(Collections.RESOURCEPATH)/\(try collectionName.encodeURL())" } diff --git a/Sources/Typesense/CurationSet.swift b/Sources/Typesense/CurationSet.swift new file mode 100644 index 0000000..eabb5b2 --- /dev/null +++ b/Sources/Typesense/CurationSet.swift @@ -0,0 +1,47 @@ +import Foundation +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +public struct CurationSet { + private var apiCall: ApiCall + private var curationSetName: String + + + init(apiCall: ApiCall, curationSetName: String) { + self.apiCall = apiCall + self.curationSetName = curationSetName + } + + public func item(_ name: String) -> CurationSetItem { + return CurationSetItem(apiCall: apiCall, curationSetName: curationSetName, itemName: name) + } + + public func items() -> CurationSetItems { + return CurationSetItems(apiCall: apiCall, curationSetName: curationSetName) + } + + public func retrieve() async throws -> (CurationSetSchema?, URLResponse?) { + let (data, response) = try await apiCall.get(endPoint: endpointPath()) + if let result = data { + let override = try decoder.decode(CurationSetSchema.self, from: result) + return (override, response) + } + return (nil, response) + } + + public func delete() async throws -> (CurationSetDeleteSchema?, URLResponse?) { + let (data, response) = try await apiCall.delete(endPoint: endpointPath()) + if let result = data { + let decodedData = try decoder.decode(CurationSetDeleteSchema.self, from: result) + return (decodedData, response) + } + return (nil, response) + } + + private func endpointPath() throws -> String { + return try "\(CurationSets.RESOURCEPATH)/\(curationSetName.encodeURL())" + } + + +} diff --git a/Sources/Typesense/CurationSetItem.swift b/Sources/Typesense/CurationSetItem.swift new file mode 100644 index 0000000..31a2f33 --- /dev/null +++ b/Sources/Typesense/CurationSetItem.swift @@ -0,0 +1,41 @@ +import Foundation +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +public struct CurationSetItem { + private var apiCall: ApiCall + private var curationSetName: String + private var itemName: String + + + init(apiCall: ApiCall, curationSetName: String, itemName: String) { + self.apiCall = apiCall + self.curationSetName = curationSetName + self.itemName = itemName + } + + public func retrieve() async throws -> (CurationItemSchema?, URLResponse?) { + let (data, response) = try await apiCall.get(endPoint: endpointPath()) + if let result = data { + let schema = try decoder.decode(CurationItemSchema.self, from: result) + return (schema, response) + } + return (nil, response) + } + + public func delete() async throws -> (CurationItemDeleteSchema?, URLResponse?) { + let (data, response) = try await apiCall.delete(endPoint: endpointPath()) + if let result = data { + let decodedData = try decoder.decode(CurationItemDeleteSchema.self, from: result) + return (decodedData, response) + } + return (nil, response) + } + + private func endpointPath() throws -> String { + return try "\(CurationSets.RESOURCEPATH)/\(curationSetName.encodeURL())/items/\(itemName.encodeURL())" + } + + +} diff --git a/Sources/Typesense/CurationSetItems.swift b/Sources/Typesense/CurationSetItems.swift new file mode 100644 index 0000000..d07c2bb --- /dev/null +++ b/Sources/Typesense/CurationSetItems.swift @@ -0,0 +1,46 @@ +import Foundation +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +public struct CurationSetItems { + private var apiCall: ApiCall + private var curationSetName: String + + + init(apiCall: ApiCall, curationSetName: String) { + self.apiCall = apiCall + self.curationSetName = curationSetName + } + + public func retrieve() async throws -> ([CurationItemSchema]?, URLResponse?) { + let (data, response) = try await apiCall.get(endPoint: endpointPath()) + if let result = data { + let schema = try decoder.decode([CurationItemSchema].self, from: result) + return (schema, response) + } + return (nil, response) + } + + public func upsert(_ itemName: String, _ schema: CurationItemCreateSchema) async throws -> (CurationItemSchema?, URLResponse?) { + let schemaData = try encoder.encode(schema) + let (data, response) = try await apiCall.put(endPoint: endpointPath(itemName), body: schemaData) + + if let result = data { + let decodedData = try decoder.decode(CurationItemSchema.self, from: result) + return (decodedData, response) + } + return (nil, response) + } + + private func endpointPath(_ operation: String? = nil) throws -> String { + let baseEndpoint = try "\(CurationSets.RESOURCEPATH)/\(curationSetName.encodeURL())/items" + if let operation = operation { + return try "\(baseEndpoint)/\(operation.encodeURL())" + } else { + return baseEndpoint + } + } + + +} diff --git a/Sources/Typesense/CurationSets.swift b/Sources/Typesense/CurationSets.swift new file mode 100644 index 0000000..3348261 --- /dev/null +++ b/Sources/Typesense/CurationSets.swift @@ -0,0 +1,44 @@ +import Foundation +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +public struct CurationSets { + static let RESOURCEPATH = "curation_sets" + private var apiCall: ApiCall + + + init(apiCall: ApiCall) { + self.apiCall = apiCall + } + + public func upsert(_ curationSetName: String, _ params: CurationSetCreateSchema) async throws -> (CurationSetSchema?, URLResponse?) { + let schemaData = try encoder.encode(params) + let (data, response) = try await self.apiCall.put(endPoint: endpointPath(curationSetName), body: schemaData) + + if let result = data { + let curationSet = try decoder.decode(CurationSetSchema.self, from: result) + return (curationSet, response) + } + return (nil, response) + } + + public func retrieve() async throws -> ([CurationSetSchema]?, URLResponse?) { + let (data, response) = try await self.apiCall.get(endPoint: endpointPath()) + if let result = data { + let curationSets = try decoder.decode([CurationSetSchema].self, from: result) + return (curationSets, response) + } + return (nil, nil) + } + + private func endpointPath(_ operation: String? = nil) throws -> String { + let baseEndpoint = "\(CurationSets.RESOURCEPATH)" + if let operation = operation { + return try "\(baseEndpoint)/\(operation.encodeURL())" + } else { + return baseEndpoint + } + } + +} diff --git a/Sources/Typesense/Override.swift b/Sources/Typesense/Override.swift deleted file mode 100644 index 6af1470..0000000 --- a/Sources/Typesense/Override.swift +++ /dev/null @@ -1,42 +0,0 @@ -import Foundation -#if canImport(FoundationNetworking) - import FoundationNetworking -#endif - -public struct Override { - private var apiCall: ApiCall - private var collectionName: String - private var overrideId: String - - - init(apiCall: ApiCall, collectionName: String, overrideId: String) { - self.apiCall = apiCall - self.collectionName = collectionName - self.overrideId = overrideId - } - - // public func retrieve(metadataType: T.Type) async throws -> (SearchOverride?, URLResponse?) { - // let (data, response) = try await apiCall.get(endPoint: endpointPath()) - // if let result = data { - // let override = try decoder.decode(SearchOverride.self, from: result) - // return (override, response) - // } - - // return (nil, response) - // } - - // public func delete() async throws -> (SearchOverrideDeleteResponse?, URLResponse?) { - // let (data, response) = try await apiCall.delete(endPoint: endpointPath()) - // if let result = data { - // let decodedData = try decoder.decode(SearchOverrideDeleteResponse.self, from: result) - // return (decodedData, response) - // } - // return (nil, response) - // } - - private func endpointPath() throws -> String { - return try "\(Collections.RESOURCEPATH)/\(collectionName.encodeURL())/\(Overrides.RESOURCEPATH)/\(overrideId.encodeURL())" - } - - -} diff --git a/Sources/Typesense/Overrides.swift b/Sources/Typesense/Overrides.swift deleted file mode 100644 index 4e8ea75..0000000 --- a/Sources/Typesense/Overrides.swift +++ /dev/null @@ -1,48 +0,0 @@ -import Foundation -#if canImport(FoundationNetworking) - import FoundationNetworking -#endif - -public struct Overrides { - static let RESOURCEPATH = "overrides" - private var apiCall: ApiCall - private var collectionName: String - - - init(apiCall: ApiCall, collectionName: String) { - self.apiCall = apiCall - self.collectionName = collectionName - } - - // public func upsert(overrideId: String, params: SearchOverrideSchema) async throws -> (SearchOverride?, URLResponse?) { - // let schemaData = try encoder.encode(params) - // let (data, response) = try await self.apiCall.put(endPoint: endpointPath(overrideId), body: schemaData) - - // if let result = data { - // let override = try decoder.decode(SearchOverride.self, from: result) - // return (override, response) - // } - - // return (nil, response) - // } - - // public func retrieve(metadataType: T.Type) async throws -> (SearchOverridesResponse?, URLResponse?) { - // let (data, response) = try await self.apiCall.get(endPoint: endpointPath()) - // if let result = data { - // let overrides = try decoder.decode(SearchOverridesResponse.self, from: result) - // return (overrides, response) - // } - // return (nil, nil) - // } - - private func endpointPath(_ operation: String? = nil) throws -> String { - let baseEndpoint = try "\(Collections.RESOURCEPATH)/\(collectionName.encodeURL())/\(Overrides.RESOURCEPATH)" - if let operation = operation { - return try "\(baseEndpoint)/\(operation.encodeURL())" - } else { - return baseEndpoint - } - } - - -} diff --git a/Tests/TypesenseTests/CurationSetTests.swift b/Tests/TypesenseTests/CurationSetTests.swift new file mode 100644 index 0000000..90d72d8 --- /dev/null +++ b/Tests/TypesenseTests/CurationSetTests.swift @@ -0,0 +1,147 @@ +import XCTest +@testable import Typesense + +final class CurationSetTests: XCTestCase { + override func setUp() async throws { + try await createCurationSet() + } + + override func tearDown() async throws { + try await tearDownCurationSets() + } + + func testCurationSetRetrieve() async { + do { + let (result, _) = try await client.curationSet("curate_products").retrieve() + guard let validData = result else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual("curate_products", validData.name) + XCTAssertEqual(2, validData.items[0].includes?.count) + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error) + XCTAssertTrue(false) + } + } + + func testCurationSetDelete() async { + do { + let (result, _) = try await client.curationSet("curate_products").delete() + guard let validData = result else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual("curate_products", validData.name) + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error) + XCTAssertTrue(false) + } + + do{ + let _ = try await client.curationSet("curate_products").retrieve() + } catch HTTPError.clientError(let code, _){ + if code != 404 { + XCTAssertTrue(false, "Curation set should have been deleted") + } + } catch (let error) { + print(error) + XCTAssertTrue(false) + } + } + + func testCurationSetItemsRetrieve() async { + do { + let (result, _) = try await client.curationSet("curate_products").items().retrieve() + guard let validData: [CurationItemSchema] = result else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual("customize-apple", validData[0].id) + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error) + XCTAssertTrue(false) + } + } + + func testCurationSetItemsUpsert() async { + do { + let (result, _) = try await client.curationSet("curate_products").items().upsert("customize-apple-2", CurationItemCreateSchema( + rule: CurationRule( match: .exact, query: "apple"), + excludes: [CurationExclude(id: "287")], + id: "customize-apple", + includes: [ + CurationInclude(id: "422", position: 1), + CurationInclude(id: "54", position: 2), + ] + )) + guard let validData = result else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual("customize-apple-2", validData.id) + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error) + XCTAssertTrue(false) + } + } + + func testCurationSetItemRetrieve() async { + do { + let (result, _) = try await client.curationSet("curate_products").item("customize-apple").retrieve() + guard let validData = result else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual("customize-apple", validData.id) + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error) + XCTAssertTrue(false) + } + } + + func testCurationSetItemDelere() async { + do { + let (result, _) = try await client.curationSet("curate_products").item("customize-apple").delete() + guard let validData = result else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual("customize-apple", validData.id) + + let (curationSet, _) = try await client.curationSet("curate_products").retrieve() + guard let validCurationSet = curationSet else { + throw DataError.dataNotFound + } + XCTAssertEqual(0, validCurationSet.items.count) + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error) + XCTAssertTrue(false) + } + } + +} diff --git a/Tests/TypesenseTests/CurationSetsTests.swift b/Tests/TypesenseTests/CurationSetsTests.swift new file mode 100644 index 0000000..226a017 --- /dev/null +++ b/Tests/TypesenseTests/CurationSetsTests.swift @@ -0,0 +1,58 @@ +import XCTest +@testable import Typesense + +final class CurationSetsTests: XCTestCase { + override func tearDown() async throws { + try await tearDownCurationSets() + } + + func testCurationSetsUpsert() async { + let schema = CurationSetCreateSchema(items: [ + CurationItemCreateSchema( + rule: CurationRule( match: .exact, query: "apple"), + excludes: [CurationExclude(id: "287")], + id: "customize-apple", + includes: [ + CurationInclude(id: "422", position: 1), + CurationInclude(id: "54", position: 2), + ] + ) + ]) + do { + let (result, _) = try await client.curationSets().upsert("curate_products_test", schema) + XCTAssertNotNil(result) + guard let validData = result else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual("curate_products_test", validData.name) + XCTAssertEqual("apple", validData.items[0].rule.query) + XCTAssertEqual("422", validData.items[0].includes?[0].id) + XCTAssertEqual("287", validData.items[0].excludes?[0].id) + } catch (let error) { + print(error.localizedDescription) + XCTAssertTrue(false) + } + } + + func testCurationSetsRetrieve() async { + do { + try await createCurationSet() + let (data, _) = try await client.curationSets().retrieve() + guard let validData = data else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual(1, validData.count) + XCTAssertEqual("curate_products", validData[0].name) + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error) + XCTAssertTrue(false) + } + } + +} diff --git a/Tests/TypesenseTests/OverrideTests.swift b/Tests/TypesenseTests/OverrideTests.swift deleted file mode 100644 index f9d2906..0000000 --- a/Tests/TypesenseTests/OverrideTests.swift +++ /dev/null @@ -1,51 +0,0 @@ -import XCTest -@testable import Typesense - -final class OverrideTests: XCTestCase { - // override func setUp() async throws { - // try await createCollection() - // try await createAnOverride() - // } - - // override func tearDown() async throws { - // try await tearDownCollections() - // } - - // func testOverrideRetrieve() async { - // do { - // let (result, _) = try await client.collection(name: "companies").override("test-id").retrieve(metadataType: SearchOverrideExclude.self ) - // guard let validOverride = result else { - // throw DataError.dataNotFound - // } - // print(validOverride) - // XCTAssertEqual("test-id", validOverride._id) - // XCTAssertEqual("exclude-id", validOverride.metadata?._id) - // } catch HTTPError.serverError(let code, let desc) { - // print(desc) - // print("The response status code is \(code)") - // XCTAssertTrue(false) - // } catch (let error) { - // print(error) - // XCTAssertTrue(false) - // } - // } - - // func testOverrideDelete() async { - // do { - // let (result, _) = try await client.collection(name: "companies").override("test-id").delete() - // guard let validOverride = result else { - // throw DataError.dataNotFound - // } - // print(validOverride) - // XCTAssertEqual("test-id", validOverride._id) - // } catch HTTPError.serverError(let code, let desc) { - // print(desc) - // print("The response status code is \(code)") - // XCTAssertTrue(false) - // } catch (let error) { - // print(error) - // XCTAssertTrue(false) - // } - // } - -} diff --git a/Tests/TypesenseTests/OverridesTests.swift b/Tests/TypesenseTests/OverridesTests.swift deleted file mode 100644 index 2951978..0000000 --- a/Tests/TypesenseTests/OverridesTests.swift +++ /dev/null @@ -1,74 +0,0 @@ -import XCTest -@testable import Typesense - -final class OverridesTests: XCTestCase { - // override func setUp() async throws { - // try await createCollection() - // } - - // override func tearDown() async throws { - // try await tearDownCollections() - // } - - // func testOverridesUpsert() async { - // let schema = SearchOverrideSchema( - // rule: SearchOverrideRule(tags: ["test"], query: "test", match: SearchOverrideRule.Match.exact, filterBy: "employees:=50"), - // includes: [SearchOverrideInclude(_id: "include-id", position: 1)], - // excludes: [SearchOverrideExclude(_id: "exclude-id")], - // filterBy: "test:=true", - // removeMatchedTokens: false, - // metadata: SearchOverrideExclude(_id: "test-json"), - // sortBy: "asc", - // replaceQuery: "test", - // filterCuratedHits: false, - // effectiveFromTs: 123, - // effectiveToTs: 456, - // stopProcessing: false - // ) - // do { - // let (result, _) = try await client.collection(name: "companies").overrides().upsert(overrideId: "test-id", params: schema) - // XCTAssertNotNil(result) - // guard let validOverride = result else { - // throw DataError.dataNotFound - // } - // print(validOverride) - // XCTAssertEqual("test-id", validOverride._id) - // XCTAssertEqual("test", validOverride.rule.query) - // XCTAssertEqual("test-json", validOverride.metadata?._id) - // XCTAssertEqual("include-id", validOverride.includes?[0]._id) - // XCTAssertEqual("exclude-id", validOverride.excludes?[0]._id) - // XCTAssertEqual("test:=true", validOverride.filterBy) - // XCTAssertEqual(false, validOverride.removeMatchedTokens) - // XCTAssertEqual("asc", validOverride.sortBy) - // XCTAssertEqual("test", validOverride.replaceQuery) - // XCTAssertEqual(false, validOverride.filterCuratedHits) - // XCTAssertEqual(123, validOverride.effectiveFromTs) - // XCTAssertEqual(456, validOverride.effectiveToTs) - // XCTAssertEqual(false, validOverride.stopProcessing) - // } catch (let error) { - // print(error.localizedDescription) - // XCTAssertTrue(false) - // } - // } - - // func testOverridesRetrieve() async { - // do { - // try await createAnOverride() - // let (overrides, _) = try await client.collection(name: "companies").overrides().retrieve(metadataType: SearchOverrideExclude.self ) - // guard let validOverrides = overrides else { - // throw DataError.dataNotFound - // } - // print(validOverrides) - // XCTAssertEqual(1, validOverrides.overrides.count) - // XCTAssertEqual("test-id", validOverrides.overrides[0]._id) - // } catch HTTPError.serverError(let code, let desc) { - // print(desc) - // print("The response status code is \(code)") - // XCTAssertTrue(false) - // } catch (let error) { - // print(error) - // XCTAssertTrue(false) - // } - // } - -} diff --git a/Tests/TypesenseTests/TestUtils.swift b/Tests/TypesenseTests/TestUtils.swift index 9b02584..da18ff7 100644 --- a/Tests/TypesenseTests/TestUtils.swift +++ b/Tests/TypesenseTests/TestUtils.swift @@ -64,6 +64,16 @@ func tearDownAliases() async throws { } } +func tearDownCurationSets() async throws { + let (data, _) = try await utilClient.curationSets().retrieve() + guard let validData = data else { + throw DataError.dataNotFound + } + for item in validData { + let _ = try await utilClient.curationSet(item.name).delete() + } +} + func createCollection() async throws { let schema = CollectionSchema( fields: [ Field(name: "company_name", type: "string"), @@ -81,13 +91,20 @@ func createDocument() async throws { let data = try encoder.encode(Company(id: "test-id", company_name: "Stark Industries", num_employees: 5215, country: "USA", metadata: ["open":false])) let _ = try await utilClient.collection(name: "companies").documents().create(document: data) } - -// func createAnOverride() async throws { -// let _ = try await utilClient.collection(name: "companies").overrides().upsert( -// overrideId: "test-id", -// params: SearchOverrideSchema(rule: SearchOverrideRule(filterBy: "test"), filterBy: "test:=true", metadata: SearchOverrideExclude(_id: "exclude-id")) -// ) -// } +func createCurationSet() async throws { + let schema = CurationSetCreateSchema(items: [ + CurationItemCreateSchema( + rule: CurationRule( match: .exact, query: "apple"), + excludes: [CurationExclude(id: "287")], + id: "customize-apple", + includes: [ + CurationInclude(id: "422", position: 1), + CurationInclude(id: "54", position: 2), + ] + ) + ]) + let _ = try await client.curationSets().upsert("curate_products", schema) +} func createSingleCollectionSearchPreset() async throws { let _ = try await utilClient.presets().upsert( From 7506cc7e562bb2d489af33395675b393fad22b55 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Wed, 10 Dec 2025 20:34:42 +0700 Subject: [PATCH 08/21] generator: preserve the field order according to the api spec file --- Sources/Typesense/Models/AnalyticsEvent.swift | 20 +- .../Typesense/Models/AnalyticsEventData.swift | 18 +- .../AnalyticsEventsResponseEventsInner.swift | 34 +- .../AnalyticsEventsRetrieveParams.swift | 20 +- Sources/Typesense/Models/AnalyticsRule.swift | 32 +- .../Models/AnalyticsRuleCreate.swift | 32 +- .../Models/AnalyticsRuleCreateParams.swift | 26 +- .../Typesense/Models/AnalyticsRuleType.swift | 18 + .../Models/AnalyticsRuleUpdate.swift | 10 +- .../Typesense/Models/AnalyticsStatus.swift | 42 +- Sources/Typesense/Models/ApiKey.swift | 18 +- Sources/Typesense/Models/ApiKeySchema.swift | 18 +- .../Typesense/Models/CollectionAlias.swift | 12 +- .../Typesense/Models/CollectionResponse.swift | 62 +- .../Typesense/Models/CollectionSchema.swift | 52 +- .../Models/CollectionUpdateSchema.swift | 12 +- .../ConversationModelCreateSchema.swift | 42 +- .../Models/ConversationModelSchema.swift | 42 +- .../ConversationModelUpdateSchema.swift | 42 +- ...lyticsRule200ResponseOneOfInnerAnyOf.swift | 31 - .../Models/CurationItemCreateSchema.swift | 80 +- .../Typesense/Models/CurationItemSchema.swift | 78 +- Sources/Typesense/Models/CurationRule.swift | 32 +- .../Models/CurationSetCreateSchema.swift | 10 +- .../Typesense/Models/CurationSetSchema.swift | 10 +- .../Models/DeleteDocumentsParameters.swift | 8 +- .../Models/ExportDocumentsParameters.swift | 12 +- .../Models/FacetCountsCountsInner.swift | 10 +- .../Typesense/Models/FacetCountsStats.swift | 10 +- Sources/Typesense/Models/Field.swift | 98 +- .../Models/FieldEmbedModelConfig.swift | 42 +- .../Models/ImportDocumentsParameters.swift | 28 +- .../MultiSearchCollectionParameters.swift | 490 +- .../Models/MultiSearchParameters.swift | 480 +- .../Typesense/Models/MultiSearchResult.swift | 8 +- .../Models/MultiSearchResultItem.swift | 58 +- .../Models/MultiSearchSearchesParameter.swift | 8 +- .../Typesense/Models/NLSearchModelBase.swift | 122 +- .../Models/NLSearchModelCreateSchema.swift | 122 +- .../Models/NLSearchModelSchema.swift | 122 +- .../Typesense/Models/SchemaChangeStatus.swift | 12 +- .../Typesense/Models/SearchHighlight.swift | 20 +- .../Typesense/Models/SearchParameters.swift | 550 +- .../Models/SearchRequestParams.swift | 10 +- Sources/Typesense/Models/SearchResult.swift | 58 +- .../Typesense/Models/SearchResultHit.swift | 48 +- Sources/Typesense/Models/SearchSynonym.swift | 22 +- .../Models/SearchSynonymSchema.swift | 22 +- .../Models/StemmingDictionaryWordsInner.swift | 12 +- .../Typesense/Models/StopwordsSetSchema.swift | 8 +- .../Models/StopwordsSetUpsertSchema.swift | 8 +- .../Typesense/Models/SynonymItemSchema.swift | 32 +- .../Models/SynonymItemUpsertSchema.swift | 47 + Tasks/AddVendorAttributes.swift | 6 +- Tasks/PreprocessOpenAPI.swift | 221 +- Tasks/VendorAttributes.swift | 59 +- Tasks/main.swift | 16 + openapi.yml | 42 +- preprocessed_openapi.yml | 10365 ++++++++-------- 59 files changed, 6879 insertions(+), 7090 deletions(-) create mode 100644 Sources/Typesense/Models/AnalyticsRuleType.swift delete mode 100644 Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift create mode 100644 Sources/Typesense/Models/SynonymItemUpsertSchema.swift diff --git a/Sources/Typesense/Models/AnalyticsEvent.swift b/Sources/Typesense/Models/AnalyticsEvent.swift index 2df3e36..9c9acfd 100644 --- a/Sources/Typesense/Models/AnalyticsEvent.swift +++ b/Sources/Typesense/Models/AnalyticsEvent.swift @@ -12,30 +12,30 @@ import AnyCodable public struct AnalyticsEvent: Codable { - public var data: AnalyticsEventData - /** Type of event (e.g., click, conversion, query, visit) */ - public var eventType: String /** Name of the analytics rule this event corresponds to */ public var name: String + /** Type of event (e.g., click, conversion, query, visit) */ + public var eventType: String + public var data: AnalyticsEventData - public init(data: AnalyticsEventData, eventType: String, name: String) { - self.data = data - self.eventType = eventType + public init(name: String, eventType: String, data: AnalyticsEventData) { self.name = name + self.eventType = eventType + self.data = data } public enum CodingKeys: String, CodingKey, CaseIterable { - case data - case eventType = "event_type" case name + case eventType = "event_type" + case data } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(data, forKey: .data) - try container.encode(eventType, forKey: .eventType) try container.encode(name, forKey: .name) + try container.encode(eventType, forKey: .eventType) + try container.encode(data, forKey: .data) } } diff --git a/Sources/Typesense/Models/AnalyticsEventData.swift b/Sources/Typesense/Models/AnalyticsEventData.swift index e1e78be..dc60eca 100644 --- a/Sources/Typesense/Models/AnalyticsEventData.swift +++ b/Sources/Typesense/Models/AnalyticsEventData.swift @@ -13,36 +13,36 @@ import AnyCodable /** Event payload */ public struct AnalyticsEventData: Codable { - public var analyticsTag: String? + public var userId: String? public var docId: String? public var docIds: [String]? public var q: String? - public var userId: String? + public var analyticsTag: String? - public init(analyticsTag: String? = nil, docId: String? = nil, docIds: [String]? = nil, q: String? = nil, userId: String? = nil) { - self.analyticsTag = analyticsTag + public init(userId: String? = nil, docId: String? = nil, docIds: [String]? = nil, q: String? = nil, analyticsTag: String? = nil) { + self.userId = userId self.docId = docId self.docIds = docIds self.q = q - self.userId = userId + self.analyticsTag = analyticsTag } public enum CodingKeys: String, CodingKey, CaseIterable { - case analyticsTag = "analytics_tag" + case userId = "user_id" case docId = "doc_id" case docIds = "doc_ids" case q - case userId = "user_id" + case analyticsTag = "analytics_tag" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(analyticsTag, forKey: .analyticsTag) + try container.encodeIfPresent(userId, forKey: .userId) try container.encodeIfPresent(docId, forKey: .docId) try container.encodeIfPresent(docIds, forKey: .docIds) try container.encodeIfPresent(q, forKey: .q) - try container.encodeIfPresent(userId, forKey: .userId) + try container.encodeIfPresent(analyticsTag, forKey: .analyticsTag) } } diff --git a/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift b/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift index 22d3067..5d1b2f9 100644 --- a/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift +++ b/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift @@ -12,48 +12,48 @@ import AnyCodable public struct AnalyticsEventsResponseEventsInner: Codable { + public var name: String? + public var eventType: String? public var collection: String? + public var timestamp: Int64? + public var userId: String? public var docId: String? public var docIds: [String]? - public var eventType: String? - public var name: String? public var query: String? - public var timestamp: Int64? - public var userId: String? - public init(collection: String? = nil, docId: String? = nil, docIds: [String]? = nil, eventType: String? = nil, name: String? = nil, query: String? = nil, timestamp: Int64? = nil, userId: String? = nil) { + public init(name: String? = nil, eventType: String? = nil, collection: String? = nil, timestamp: Int64? = nil, userId: String? = nil, docId: String? = nil, docIds: [String]? = nil, query: String? = nil) { + self.name = name + self.eventType = eventType self.collection = collection + self.timestamp = timestamp + self.userId = userId self.docId = docId self.docIds = docIds - self.eventType = eventType - self.name = name self.query = query - self.timestamp = timestamp - self.userId = userId } public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case eventType = "event_type" case collection + case timestamp + case userId = "user_id" case docId = "doc_id" case docIds = "doc_ids" - case eventType = "event_type" - case name case query - case timestamp - case userId = "user_id" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(eventType, forKey: .eventType) try container.encodeIfPresent(collection, forKey: .collection) + try container.encodeIfPresent(timestamp, forKey: .timestamp) + try container.encodeIfPresent(userId, forKey: .userId) try container.encodeIfPresent(docId, forKey: .docId) try container.encodeIfPresent(docIds, forKey: .docIds) - try container.encodeIfPresent(eventType, forKey: .eventType) - try container.encodeIfPresent(name, forKey: .name) try container.encodeIfPresent(query, forKey: .query) - try container.encodeIfPresent(timestamp, forKey: .timestamp) - try container.encodeIfPresent(userId, forKey: .userId) } } diff --git a/Sources/Typesense/Models/AnalyticsEventsRetrieveParams.swift b/Sources/Typesense/Models/AnalyticsEventsRetrieveParams.swift index 86aaf67..d56e657 100644 --- a/Sources/Typesense/Models/AnalyticsEventsRetrieveParams.swift +++ b/Sources/Typesense/Models/AnalyticsEventsRetrieveParams.swift @@ -12,30 +12,30 @@ import AnyCodable public struct AnalyticsEventsRetrieveParams: Codable { - /** Number of events to return (max 1000) */ - public var n: Int + public var userId: String /** Analytics rule name */ public var name: String - public var userId: String + /** Number of events to return (max 1000) */ + public var n: Int - public init(n: Int, name: String, userId: String) { - self.n = n - self.name = name + public init(userId: String, name: String, n: Int) { self.userId = userId + self.name = name + self.n = n } public enum CodingKeys: String, CodingKey, CaseIterable { - case n - case name case userId = "user_id" + case name + case n } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(n, forKey: .n) - try container.encode(name, forKey: .name) try container.encode(userId, forKey: .userId) + try container.encode(name, forKey: .name) + try container.encode(n, forKey: .n) } } diff --git a/Sources/Typesense/Models/AnalyticsRule.swift b/Sources/Typesense/Models/AnalyticsRule.swift index 2b15c75..75708a8 100644 --- a/Sources/Typesense/Models/AnalyticsRule.swift +++ b/Sources/Typesense/Models/AnalyticsRule.swift @@ -12,46 +12,40 @@ import AnyCodable public struct AnalyticsRule: Codable { - public enum ModelType: String, Codable, CaseIterable { - case popularQueries = "popular_queries" - case nohitsQueries = "nohits_queries" - case counter = "counter" - case log = "log" - } + public var name: String + public var type: AnalyticsRuleType public var collection: String public var eventType: String - public var name: String - public var params: AnalyticsRuleCreateParams? public var ruleTag: String? - public var type: ModelType + public var params: AnalyticsRuleCreateParams? - public init(collection: String, eventType: String, name: String, type: ModelType, params: AnalyticsRuleCreateParams? = nil, ruleTag: String? = nil) { + public init(name: String, type: AnalyticsRuleType, collection: String, eventType: String, ruleTag: String? = nil, params: AnalyticsRuleCreateParams? = nil) { + self.name = name + self.type = type self.collection = collection self.eventType = eventType - self.name = name - self.params = params self.ruleTag = ruleTag - self.type = type + self.params = params } public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case type case collection case eventType = "event_type" - case name - case params case ruleTag = "rule_tag" - case type + case params } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(type, forKey: .type) try container.encode(collection, forKey: .collection) try container.encode(eventType, forKey: .eventType) - try container.encode(name, forKey: .name) - try container.encodeIfPresent(params, forKey: .params) try container.encodeIfPresent(ruleTag, forKey: .ruleTag) - try container.encode(type, forKey: .type) + try container.encodeIfPresent(params, forKey: .params) } } diff --git a/Sources/Typesense/Models/AnalyticsRuleCreate.swift b/Sources/Typesense/Models/AnalyticsRuleCreate.swift index 8b77674..63d237d 100644 --- a/Sources/Typesense/Models/AnalyticsRuleCreate.swift +++ b/Sources/Typesense/Models/AnalyticsRuleCreate.swift @@ -12,46 +12,40 @@ import AnyCodable public struct AnalyticsRuleCreate: Codable { - public enum ModelType: String, Codable, CaseIterable { - case popularQueries = "popular_queries" - case nohitsQueries = "nohits_queries" - case counter = "counter" - case log = "log" - } + public var name: String + public var type: AnalyticsRuleType public var collection: String public var eventType: String - public var name: String - public var params: AnalyticsRuleCreateParams? public var ruleTag: String? - public var type: ModelType + public var params: AnalyticsRuleCreateParams? - public init(collection: String, eventType: String, name: String, type: ModelType, params: AnalyticsRuleCreateParams? = nil, ruleTag: String? = nil) { + public init(name: String, type: AnalyticsRuleType, collection: String, eventType: String, ruleTag: String? = nil, params: AnalyticsRuleCreateParams? = nil) { + self.name = name + self.type = type self.collection = collection self.eventType = eventType - self.name = name - self.params = params self.ruleTag = ruleTag - self.type = type + self.params = params } public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case type case collection case eventType = "event_type" - case name - case params case ruleTag = "rule_tag" - case type + case params } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(type, forKey: .type) try container.encode(collection, forKey: .collection) try container.encode(eventType, forKey: .eventType) - try container.encode(name, forKey: .name) - try container.encodeIfPresent(params, forKey: .params) try container.encodeIfPresent(ruleTag, forKey: .ruleTag) - try container.encode(type, forKey: .type) + try container.encodeIfPresent(params, forKey: .params) } } diff --git a/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift b/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift index 029256b..624c005 100644 --- a/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift +++ b/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift @@ -12,31 +12,31 @@ import AnyCodable public struct AnalyticsRuleCreateParams: Codable { - public var captureSearchRequests: Bool? - public var counterField: String? public var destinationCollection: String? - public var expandQuery: Bool? public var limit: Int? + public var captureSearchRequests: Bool? public var metaFields: [String]? + public var expandQuery: Bool? + public var counterField: String? public var weight: Int? - public init(captureSearchRequests: Bool? = nil, counterField: String? = nil, destinationCollection: String? = nil, expandQuery: Bool? = nil, limit: Int? = nil, metaFields: [String]? = nil, weight: Int? = nil) { - self.captureSearchRequests = captureSearchRequests - self.counterField = counterField + public init(destinationCollection: String? = nil, limit: Int? = nil, captureSearchRequests: Bool? = nil, metaFields: [String]? = nil, expandQuery: Bool? = nil, counterField: String? = nil, weight: Int? = nil) { self.destinationCollection = destinationCollection - self.expandQuery = expandQuery self.limit = limit + self.captureSearchRequests = captureSearchRequests self.metaFields = metaFields + self.expandQuery = expandQuery + self.counterField = counterField self.weight = weight } public enum CodingKeys: String, CodingKey, CaseIterable { - case captureSearchRequests = "capture_search_requests" - case counterField = "counter_field" case destinationCollection = "destination_collection" - case expandQuery = "expand_query" case limit + case captureSearchRequests = "capture_search_requests" case metaFields = "meta_fields" + case expandQuery = "expand_query" + case counterField = "counter_field" case weight } @@ -44,12 +44,12 @@ public struct AnalyticsRuleCreateParams: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(captureSearchRequests, forKey: .captureSearchRequests) - try container.encodeIfPresent(counterField, forKey: .counterField) try container.encodeIfPresent(destinationCollection, forKey: .destinationCollection) - try container.encodeIfPresent(expandQuery, forKey: .expandQuery) try container.encodeIfPresent(limit, forKey: .limit) + try container.encodeIfPresent(captureSearchRequests, forKey: .captureSearchRequests) try container.encodeIfPresent(metaFields, forKey: .metaFields) + try container.encodeIfPresent(expandQuery, forKey: .expandQuery) + try container.encodeIfPresent(counterField, forKey: .counterField) try container.encodeIfPresent(weight, forKey: .weight) } } diff --git a/Sources/Typesense/Models/AnalyticsRuleType.swift b/Sources/Typesense/Models/AnalyticsRuleType.swift new file mode 100644 index 0000000..125d2ae --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsRuleType.swift @@ -0,0 +1,18 @@ +// +// AnalyticsRuleType.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum AnalyticsRuleType: String, Codable, CaseIterable { + case popularQueries = "popular_queries" + case nohitsQueries = "nohits_queries" + case counter = "counter" + case log = "log" +} diff --git a/Sources/Typesense/Models/AnalyticsRuleUpdate.swift b/Sources/Typesense/Models/AnalyticsRuleUpdate.swift index 1bf1f68..2f08ccb 100644 --- a/Sources/Typesense/Models/AnalyticsRuleUpdate.swift +++ b/Sources/Typesense/Models/AnalyticsRuleUpdate.swift @@ -14,19 +14,19 @@ import AnyCodable public struct AnalyticsRuleUpdate: Codable { public var name: String? - public var params: AnalyticsRuleCreateParams? public var ruleTag: String? + public var params: AnalyticsRuleCreateParams? - public init(name: String? = nil, params: AnalyticsRuleCreateParams? = nil, ruleTag: String? = nil) { + public init(name: String? = nil, ruleTag: String? = nil, params: AnalyticsRuleCreateParams? = nil) { self.name = name - self.params = params self.ruleTag = ruleTag + self.params = params } public enum CodingKeys: String, CodingKey, CaseIterable { case name - case params case ruleTag = "rule_tag" + case params } // Encodable protocol methods @@ -34,7 +34,7 @@ public struct AnalyticsRuleUpdate: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(name, forKey: .name) - try container.encodeIfPresent(params, forKey: .params) try container.encodeIfPresent(ruleTag, forKey: .ruleTag) + try container.encodeIfPresent(params, forKey: .params) } } diff --git a/Sources/Typesense/Models/AnalyticsStatus.swift b/Sources/Typesense/Models/AnalyticsStatus.swift index 20cf623..996644e 100644 --- a/Sources/Typesense/Models/AnalyticsStatus.swift +++ b/Sources/Typesense/Models/AnalyticsStatus.swift @@ -12,44 +12,44 @@ import AnyCodable public struct AnalyticsStatus: Codable { - public var docCounterEvents: Int? - public var docLogEvents: Int? - public var logPrefixQueries: Int? - public var nohitsPrefixQueries: Int? public var popularPrefixQueries: Int? - public var queryCounterEvents: Int? + public var nohitsPrefixQueries: Int? + public var logPrefixQueries: Int? public var queryLogEvents: Int? + public var queryCounterEvents: Int? + public var docLogEvents: Int? + public var docCounterEvents: Int? - public init(docCounterEvents: Int? = nil, docLogEvents: Int? = nil, logPrefixQueries: Int? = nil, nohitsPrefixQueries: Int? = nil, popularPrefixQueries: Int? = nil, queryCounterEvents: Int? = nil, queryLogEvents: Int? = nil) { - self.docCounterEvents = docCounterEvents - self.docLogEvents = docLogEvents - self.logPrefixQueries = logPrefixQueries - self.nohitsPrefixQueries = nohitsPrefixQueries + public init(popularPrefixQueries: Int? = nil, nohitsPrefixQueries: Int? = nil, logPrefixQueries: Int? = nil, queryLogEvents: Int? = nil, queryCounterEvents: Int? = nil, docLogEvents: Int? = nil, docCounterEvents: Int? = nil) { self.popularPrefixQueries = popularPrefixQueries - self.queryCounterEvents = queryCounterEvents + self.nohitsPrefixQueries = nohitsPrefixQueries + self.logPrefixQueries = logPrefixQueries self.queryLogEvents = queryLogEvents + self.queryCounterEvents = queryCounterEvents + self.docLogEvents = docLogEvents + self.docCounterEvents = docCounterEvents } public enum CodingKeys: String, CodingKey, CaseIterable { - case docCounterEvents = "doc_counter_events" - case docLogEvents = "doc_log_events" - case logPrefixQueries = "log_prefix_queries" - case nohitsPrefixQueries = "nohits_prefix_queries" case popularPrefixQueries = "popular_prefix_queries" - case queryCounterEvents = "query_counter_events" + case nohitsPrefixQueries = "nohits_prefix_queries" + case logPrefixQueries = "log_prefix_queries" case queryLogEvents = "query_log_events" + case queryCounterEvents = "query_counter_events" + case docLogEvents = "doc_log_events" + case docCounterEvents = "doc_counter_events" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(docCounterEvents, forKey: .docCounterEvents) - try container.encodeIfPresent(docLogEvents, forKey: .docLogEvents) - try container.encodeIfPresent(logPrefixQueries, forKey: .logPrefixQueries) - try container.encodeIfPresent(nohitsPrefixQueries, forKey: .nohitsPrefixQueries) try container.encodeIfPresent(popularPrefixQueries, forKey: .popularPrefixQueries) - try container.encodeIfPresent(queryCounterEvents, forKey: .queryCounterEvents) + try container.encodeIfPresent(nohitsPrefixQueries, forKey: .nohitsPrefixQueries) + try container.encodeIfPresent(logPrefixQueries, forKey: .logPrefixQueries) try container.encodeIfPresent(queryLogEvents, forKey: .queryLogEvents) + try container.encodeIfPresent(queryCounterEvents, forKey: .queryCounterEvents) + try container.encodeIfPresent(docLogEvents, forKey: .docLogEvents) + try container.encodeIfPresent(docCounterEvents, forKey: .docCounterEvents) } } diff --git a/Sources/Typesense/Models/ApiKey.swift b/Sources/Typesense/Models/ApiKey.swift index 55afb2d..6e3bf18 100644 --- a/Sources/Typesense/Models/ApiKey.swift +++ b/Sources/Typesense/Models/ApiKey.swift @@ -12,30 +12,30 @@ import AnyCodable public struct ApiKey: Codable { + public var value: String? + public var description: String public var actions: [String] public var collections: [String] - public var description: String public var expiresAt: Int64? - public var value: String? public var id: Int64? public var valuePrefix: String? - public init(actions: [String], collections: [String], description: String, expiresAt: Int64? = nil, value: String? = nil, id: Int64? = nil, valuePrefix: String? = nil) { + public init(description: String, actions: [String], collections: [String], value: String? = nil, expiresAt: Int64? = nil, id: Int64? = nil, valuePrefix: String? = nil) { + self.value = value + self.description = description self.actions = actions self.collections = collections - self.description = description self.expiresAt = expiresAt - self.value = value self.id = id self.valuePrefix = valuePrefix } public enum CodingKeys: String, CodingKey, CaseIterable { + case value + case description case actions case collections - case description case expiresAt = "expires_at" - case value case id case valuePrefix = "value_prefix" } @@ -44,11 +44,11 @@ public struct ApiKey: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(value, forKey: .value) + try container.encode(description, forKey: .description) try container.encode(actions, forKey: .actions) try container.encode(collections, forKey: .collections) - try container.encode(description, forKey: .description) try container.encodeIfPresent(expiresAt, forKey: .expiresAt) - try container.encodeIfPresent(value, forKey: .value) try container.encodeIfPresent(id, forKey: .id) try container.encodeIfPresent(valuePrefix, forKey: .valuePrefix) } diff --git a/Sources/Typesense/Models/ApiKeySchema.swift b/Sources/Typesense/Models/ApiKeySchema.swift index 402246f..3419388 100644 --- a/Sources/Typesense/Models/ApiKeySchema.swift +++ b/Sources/Typesense/Models/ApiKeySchema.swift @@ -12,36 +12,36 @@ import AnyCodable public struct ApiKeySchema: Codable { + public var value: String? + public var description: String public var actions: [String] public var collections: [String] - public var description: String public var expiresAt: Int64? - public var value: String? - public init(actions: [String], collections: [String], description: String, expiresAt: Int64? = nil, value: String? = nil) { + public init(description: String, actions: [String], collections: [String], value: String? = nil, expiresAt: Int64? = nil) { + self.value = value + self.description = description self.actions = actions self.collections = collections - self.description = description self.expiresAt = expiresAt - self.value = value } public enum CodingKeys: String, CodingKey, CaseIterable { + case value + case description case actions case collections - case description case expiresAt = "expires_at" - case value } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(value, forKey: .value) + try container.encode(description, forKey: .description) try container.encode(actions, forKey: .actions) try container.encode(collections, forKey: .collections) - try container.encode(description, forKey: .description) try container.encodeIfPresent(expiresAt, forKey: .expiresAt) - try container.encodeIfPresent(value, forKey: .value) } } diff --git a/Sources/Typesense/Models/CollectionAlias.swift b/Sources/Typesense/Models/CollectionAlias.swift index 87b6707..bf78fed 100644 --- a/Sources/Typesense/Models/CollectionAlias.swift +++ b/Sources/Typesense/Models/CollectionAlias.swift @@ -12,26 +12,26 @@ import AnyCodable public struct CollectionAlias: Codable { - /** Name of the collection the alias mapped to */ - public var collectionName: String /** Name of the collection alias */ public var name: String + /** Name of the collection the alias mapped to */ + public var collectionName: String - public init(collectionName: String, name: String) { - self.collectionName = collectionName + public init(name: String, collectionName: String) { self.name = name + self.collectionName = collectionName } public enum CodingKeys: String, CodingKey, CaseIterable { - case collectionName = "collection_name" case name + case collectionName = "collection_name" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(collectionName, forKey: .collectionName) try container.encode(name, forKey: .name) + try container.encode(collectionName, forKey: .collectionName) } } diff --git a/Sources/Typesense/Models/CollectionResponse.swift b/Sources/Typesense/Models/CollectionResponse.swift index 2978ae7..1e2cbbd 100644 --- a/Sources/Typesense/Models/CollectionResponse.swift +++ b/Sources/Typesense/Models/CollectionResponse.swift @@ -12,70 +12,70 @@ import AnyCodable public struct CollectionResponse: Codable { + /** Name of the collection */ + public var name: String + /** A list of fields for querying, filtering and faceting */ + public var fields: [Field] /** 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. */ public var defaultSortingField: String? = "" + /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ + public var tokenSeparators: [String]? + /** List of synonym set names to associate with this collection */ + public var synonymSets: [String]? /** 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. */ public var enableNestedFields: Bool? = false - /** A list of fields for querying, filtering and faceting */ - public var fields: [Field] - /** Optional details about the collection, e.g., when it was created, who created it etc. */ - public var metadata: AnyCodable? - /** Name of the collection */ - public var name: String /** List of symbols or special characters to be indexed. */ public var symbolsToIndex: [String]? - /** List of synonym set names to associate with this collection */ - public var synonymSets: [String]? - /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ - public var tokenSeparators: [String]? public var voiceQueryModel: VoiceQueryModelCollectionConfig? - /** Timestamp of when the collection was created (Unix epoch in seconds) */ - public var createdAt: Int64 + /** Optional details about the collection, e.g., when it was created, who created it etc. */ + public var metadata: AnyCodable? /** Number of documents in the collection */ public var numDocuments: Int64 + /** Timestamp of when the collection was created (Unix epoch in seconds) */ + public var createdAt: Int64 - public init(fields: [Field], name: String, createdAt: Int64, numDocuments: Int64, defaultSortingField: String? = "", enableNestedFields: Bool? = false, metadata: AnyCodable? = nil, symbolsToIndex: [String]? = nil, synonymSets: [String]? = nil, tokenSeparators: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil) { + public init(name: String, fields: [Field], numDocuments: Int64, createdAt: Int64, defaultSortingField: String? = "", tokenSeparators: [String]? = nil, synonymSets: [String]? = nil, enableNestedFields: Bool? = false, symbolsToIndex: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil, metadata: AnyCodable? = nil) { + self.name = name + self.fields = fields self.defaultSortingField = defaultSortingField + self.tokenSeparators = tokenSeparators + self.synonymSets = synonymSets self.enableNestedFields = enableNestedFields - self.fields = fields - self.metadata = metadata - self.name = name self.symbolsToIndex = symbolsToIndex - self.synonymSets = synonymSets - self.tokenSeparators = tokenSeparators self.voiceQueryModel = voiceQueryModel - self.createdAt = createdAt + self.metadata = metadata self.numDocuments = numDocuments + self.createdAt = createdAt } public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case fields case defaultSortingField = "default_sorting_field" + case tokenSeparators = "token_separators" + case synonymSets = "synonym_sets" case enableNestedFields = "enable_nested_fields" - case fields - case metadata - case name case symbolsToIndex = "symbols_to_index" - case synonymSets = "synonym_sets" - case tokenSeparators = "token_separators" case voiceQueryModel = "voice_query_model" - case createdAt = "created_at" + case metadata case numDocuments = "num_documents" + case createdAt = "created_at" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(fields, forKey: .fields) try container.encodeIfPresent(defaultSortingField, forKey: .defaultSortingField) + try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) + try container.encodeIfPresent(synonymSets, forKey: .synonymSets) try container.encodeIfPresent(enableNestedFields, forKey: .enableNestedFields) - try container.encode(fields, forKey: .fields) - try container.encodeIfPresent(metadata, forKey: .metadata) - try container.encode(name, forKey: .name) try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) - try container.encodeIfPresent(synonymSets, forKey: .synonymSets) - try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) try container.encodeIfPresent(voiceQueryModel, forKey: .voiceQueryModel) - try container.encode(createdAt, forKey: .createdAt) + try container.encodeIfPresent(metadata, forKey: .metadata) try container.encode(numDocuments, forKey: .numDocuments) + try container.encode(createdAt, forKey: .createdAt) } } diff --git a/Sources/Typesense/Models/CollectionSchema.swift b/Sources/Typesense/Models/CollectionSchema.swift index 3774d5e..2534521 100644 --- a/Sources/Typesense/Models/CollectionSchema.swift +++ b/Sources/Typesense/Models/CollectionSchema.swift @@ -12,60 +12,60 @@ import AnyCodable public struct CollectionSchema: Codable { + /** Name of the collection */ + public var name: String + /** A list of fields for querying, filtering and faceting */ + public var fields: [Field] /** 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. */ public var defaultSortingField: String? = "" + /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ + public var tokenSeparators: [String]? + /** List of synonym set names to associate with this collection */ + public var synonymSets: [String]? /** 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. */ public var enableNestedFields: Bool? = false - /** A list of fields for querying, filtering and faceting */ - public var fields: [Field] - /** Optional details about the collection, e.g., when it was created, who created it etc. */ - public var metadata: AnyCodable? - /** Name of the collection */ - public var name: String /** List of symbols or special characters to be indexed. */ public var symbolsToIndex: [String]? - /** List of synonym set names to associate with this collection */ - public var synonymSets: [String]? - /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ - public var tokenSeparators: [String]? public var voiceQueryModel: VoiceQueryModelCollectionConfig? + /** Optional details about the collection, e.g., when it was created, who created it etc. */ + public var metadata: AnyCodable? - public init(fields: [Field], name: String, defaultSortingField: String? = "", enableNestedFields: Bool? = false, metadata: AnyCodable? = nil, symbolsToIndex: [String]? = nil, synonymSets: [String]? = nil, tokenSeparators: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil) { + public init(name: String, fields: [Field], defaultSortingField: String? = "", tokenSeparators: [String]? = nil, synonymSets: [String]? = nil, enableNestedFields: Bool? = false, symbolsToIndex: [String]? = nil, voiceQueryModel: VoiceQueryModelCollectionConfig? = nil, metadata: AnyCodable? = nil) { + self.name = name + self.fields = fields self.defaultSortingField = defaultSortingField + self.tokenSeparators = tokenSeparators + self.synonymSets = synonymSets self.enableNestedFields = enableNestedFields - self.fields = fields - self.metadata = metadata - self.name = name self.symbolsToIndex = symbolsToIndex - self.synonymSets = synonymSets - self.tokenSeparators = tokenSeparators self.voiceQueryModel = voiceQueryModel + self.metadata = metadata } public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case fields case defaultSortingField = "default_sorting_field" + case tokenSeparators = "token_separators" + case synonymSets = "synonym_sets" case enableNestedFields = "enable_nested_fields" - case fields - case metadata - case name case symbolsToIndex = "symbols_to_index" - case synonymSets = "synonym_sets" - case tokenSeparators = "token_separators" case voiceQueryModel = "voice_query_model" + case metadata } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(fields, forKey: .fields) try container.encodeIfPresent(defaultSortingField, forKey: .defaultSortingField) + try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) + try container.encodeIfPresent(synonymSets, forKey: .synonymSets) try container.encodeIfPresent(enableNestedFields, forKey: .enableNestedFields) - try container.encode(fields, forKey: .fields) - try container.encodeIfPresent(metadata, forKey: .metadata) - try container.encode(name, forKey: .name) try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) - try container.encodeIfPresent(synonymSets, forKey: .synonymSets) - try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) try container.encodeIfPresent(voiceQueryModel, forKey: .voiceQueryModel) + try container.encodeIfPresent(metadata, forKey: .metadata) } } diff --git a/Sources/Typesense/Models/CollectionUpdateSchema.swift b/Sources/Typesense/Models/CollectionUpdateSchema.swift index f697ad3..8dc6d6b 100644 --- a/Sources/Typesense/Models/CollectionUpdateSchema.swift +++ b/Sources/Typesense/Models/CollectionUpdateSchema.swift @@ -14,21 +14,21 @@ public struct CollectionUpdateSchema: Codable { /** A list of fields for querying, filtering and faceting */ public var fields: [Field] - /** Optional details about the collection, e.g., when it was created, who created it etc. */ - public var metadata: AnyCodable? /** List of synonym set names to associate with this collection */ public var synonymSets: [String]? + /** Optional details about the collection, e.g., when it was created, who created it etc. */ + public var metadata: AnyCodable? - public init(fields: [Field], metadata: AnyCodable? = nil, synonymSets: [String]? = nil) { + public init(fields: [Field], synonymSets: [String]? = nil, metadata: AnyCodable? = nil) { self.fields = fields - self.metadata = metadata self.synonymSets = synonymSets + self.metadata = metadata } public enum CodingKeys: String, CodingKey, CaseIterable { case fields - case metadata case synonymSets = "synonym_sets" + case metadata } // Encodable protocol methods @@ -36,7 +36,7 @@ public struct CollectionUpdateSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(fields, forKey: .fields) - try container.encodeIfPresent(metadata, forKey: .metadata) try container.encodeIfPresent(synonymSets, forKey: .synonymSets) + try container.encodeIfPresent(metadata, forKey: .metadata) } } diff --git a/Sources/Typesense/Models/ConversationModelCreateSchema.swift b/Sources/Typesense/Models/ConversationModelCreateSchema.swift index d053cb3..2f29948 100644 --- a/Sources/Typesense/Models/ConversationModelCreateSchema.swift +++ b/Sources/Typesense/Models/ConversationModelCreateSchema.swift @@ -12,46 +12,46 @@ import AnyCodable public struct ConversationModelCreateSchema: Codable { - /** LLM service's account ID (only applicable for Cloudflare) */ - public var accountId: String? - /** The LLM service's API Key */ - public var apiKey: String? - /** Typesense collection that stores the historical conversations */ - public var historyCollection: String /** An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. */ public var id: String? - /** 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. */ - public var maxBytes: Int /** Name of the LLM model offered by OpenAI, Cloudflare or vLLM */ public var modelName: String + /** The LLM service's API Key */ + public var apiKey: String? + /** Typesense collection that stores the historical conversations */ + public var historyCollection: String + /** LLM service's account ID (only applicable for Cloudflare) */ + public var accountId: String? /** The system prompt that contains special instructions to the LLM */ public var systemPrompt: String? /** Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) */ public var ttl: Int? + /** 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. */ + public var maxBytes: Int /** URL of vLLM service */ public var vllmUrl: String? - public init(historyCollection: String, maxBytes: Int, modelName: String, accountId: String? = nil, apiKey: String? = nil, id: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, vllmUrl: String? = nil) { - self.accountId = accountId - self.apiKey = apiKey - self.historyCollection = historyCollection + public init(modelName: String, historyCollection: String, maxBytes: Int, id: String? = nil, apiKey: String? = nil, accountId: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, vllmUrl: String? = nil) { self.id = id - self.maxBytes = maxBytes self.modelName = modelName + self.apiKey = apiKey + self.historyCollection = historyCollection + self.accountId = accountId self.systemPrompt = systemPrompt self.ttl = ttl + self.maxBytes = maxBytes self.vllmUrl = vllmUrl } public enum CodingKeys: String, CodingKey, CaseIterable { - case accountId = "account_id" - case apiKey = "api_key" - case historyCollection = "history_collection" case id - case maxBytes = "max_bytes" case modelName = "model_name" + case apiKey = "api_key" + case historyCollection = "history_collection" + case accountId = "account_id" case systemPrompt = "system_prompt" case ttl + case maxBytes = "max_bytes" case vllmUrl = "vllm_url" } @@ -59,14 +59,14 @@ public struct ConversationModelCreateSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(accountId, forKey: .accountId) - try container.encodeIfPresent(apiKey, forKey: .apiKey) - try container.encode(historyCollection, forKey: .historyCollection) try container.encodeIfPresent(id, forKey: .id) - try container.encode(maxBytes, forKey: .maxBytes) try container.encode(modelName, forKey: .modelName) + try container.encodeIfPresent(apiKey, forKey: .apiKey) + try container.encode(historyCollection, forKey: .historyCollection) + try container.encodeIfPresent(accountId, forKey: .accountId) try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) try container.encodeIfPresent(ttl, forKey: .ttl) + try container.encode(maxBytes, forKey: .maxBytes) try container.encodeIfPresent(vllmUrl, forKey: .vllmUrl) } } diff --git a/Sources/Typesense/Models/ConversationModelSchema.swift b/Sources/Typesense/Models/ConversationModelSchema.swift index bad45af..d92f166 100644 --- a/Sources/Typesense/Models/ConversationModelSchema.swift +++ b/Sources/Typesense/Models/ConversationModelSchema.swift @@ -12,46 +12,46 @@ import AnyCodable public struct ConversationModelSchema: Codable { - /** LLM service's account ID (only applicable for Cloudflare) */ - public var accountId: String? - /** The LLM service's API Key */ - public var apiKey: String? - /** Typesense collection that stores the historical conversations */ - public var historyCollection: String /** An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. */ public var id: String - /** 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. */ - public var maxBytes: Int /** Name of the LLM model offered by OpenAI, Cloudflare or vLLM */ public var modelName: String + /** The LLM service's API Key */ + public var apiKey: String? + /** Typesense collection that stores the historical conversations */ + public var historyCollection: String + /** LLM service's account ID (only applicable for Cloudflare) */ + public var accountId: String? /** The system prompt that contains special instructions to the LLM */ public var systemPrompt: String? /** Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) */ public var ttl: Int? + /** 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. */ + public var maxBytes: Int /** URL of vLLM service */ public var vllmUrl: String? - public init(historyCollection: String, id: String, maxBytes: Int, modelName: String, accountId: String? = nil, apiKey: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, vllmUrl: String? = nil) { - self.accountId = accountId - self.apiKey = apiKey - self.historyCollection = historyCollection + public init(id: String, modelName: String, historyCollection: String, maxBytes: Int, apiKey: String? = nil, accountId: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, vllmUrl: String? = nil) { self.id = id - self.maxBytes = maxBytes self.modelName = modelName + self.apiKey = apiKey + self.historyCollection = historyCollection + self.accountId = accountId self.systemPrompt = systemPrompt self.ttl = ttl + self.maxBytes = maxBytes self.vllmUrl = vllmUrl } public enum CodingKeys: String, CodingKey, CaseIterable { - case accountId = "account_id" - case apiKey = "api_key" - case historyCollection = "history_collection" case id - case maxBytes = "max_bytes" case modelName = "model_name" + case apiKey = "api_key" + case historyCollection = "history_collection" + case accountId = "account_id" case systemPrompt = "system_prompt" case ttl + case maxBytes = "max_bytes" case vllmUrl = "vllm_url" } @@ -59,14 +59,14 @@ public struct ConversationModelSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(accountId, forKey: .accountId) - try container.encodeIfPresent(apiKey, forKey: .apiKey) - try container.encode(historyCollection, forKey: .historyCollection) try container.encode(id, forKey: .id) - try container.encode(maxBytes, forKey: .maxBytes) try container.encode(modelName, forKey: .modelName) + try container.encodeIfPresent(apiKey, forKey: .apiKey) + try container.encode(historyCollection, forKey: .historyCollection) + try container.encodeIfPresent(accountId, forKey: .accountId) try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) try container.encodeIfPresent(ttl, forKey: .ttl) + try container.encode(maxBytes, forKey: .maxBytes) try container.encodeIfPresent(vllmUrl, forKey: .vllmUrl) } } diff --git a/Sources/Typesense/Models/ConversationModelUpdateSchema.swift b/Sources/Typesense/Models/ConversationModelUpdateSchema.swift index 3f48c0e..f3da479 100644 --- a/Sources/Typesense/Models/ConversationModelUpdateSchema.swift +++ b/Sources/Typesense/Models/ConversationModelUpdateSchema.swift @@ -12,46 +12,46 @@ import AnyCodable public struct ConversationModelUpdateSchema: Codable { - /** LLM service's account ID (only applicable for Cloudflare) */ - public var accountId: String? - /** The LLM service's API Key */ - public var apiKey: String? - /** Typesense collection that stores the historical conversations */ - public var historyCollection: String? /** An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. */ public var id: String? - /** 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. */ - public var maxBytes: Int? /** Name of the LLM model offered by OpenAI, Cloudflare or vLLM */ public var modelName: String? + /** The LLM service's API Key */ + public var apiKey: String? + /** Typesense collection that stores the historical conversations */ + public var historyCollection: String? + /** LLM service's account ID (only applicable for Cloudflare) */ + public var accountId: String? /** The system prompt that contains special instructions to the LLM */ public var systemPrompt: String? /** Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) */ public var ttl: Int? + /** 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. */ + public var maxBytes: Int? /** URL of vLLM service */ public var vllmUrl: String? - public init(accountId: String? = nil, apiKey: String? = nil, historyCollection: String? = nil, id: String? = nil, maxBytes: Int? = nil, modelName: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, vllmUrl: String? = nil) { - self.accountId = accountId - self.apiKey = apiKey - self.historyCollection = historyCollection + public init(id: String? = nil, modelName: String? = nil, apiKey: String? = nil, historyCollection: String? = nil, accountId: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, maxBytes: Int? = nil, vllmUrl: String? = nil) { self.id = id - self.maxBytes = maxBytes self.modelName = modelName + self.apiKey = apiKey + self.historyCollection = historyCollection + self.accountId = accountId self.systemPrompt = systemPrompt self.ttl = ttl + self.maxBytes = maxBytes self.vllmUrl = vllmUrl } public enum CodingKeys: String, CodingKey, CaseIterable { - case accountId = "account_id" - case apiKey = "api_key" - case historyCollection = "history_collection" case id - case maxBytes = "max_bytes" case modelName = "model_name" + case apiKey = "api_key" + case historyCollection = "history_collection" + case accountId = "account_id" case systemPrompt = "system_prompt" case ttl + case maxBytes = "max_bytes" case vllmUrl = "vllm_url" } @@ -59,14 +59,14 @@ public struct ConversationModelUpdateSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(accountId, forKey: .accountId) - try container.encodeIfPresent(apiKey, forKey: .apiKey) - try container.encodeIfPresent(historyCollection, forKey: .historyCollection) try container.encodeIfPresent(id, forKey: .id) - try container.encodeIfPresent(maxBytes, forKey: .maxBytes) try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(apiKey, forKey: .apiKey) + try container.encodeIfPresent(historyCollection, forKey: .historyCollection) + try container.encodeIfPresent(accountId, forKey: .accountId) try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) try container.encodeIfPresent(ttl, forKey: .ttl) + try container.encodeIfPresent(maxBytes, forKey: .maxBytes) try container.encodeIfPresent(vllmUrl, forKey: .vllmUrl) } } diff --git a/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift b/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift deleted file mode 100644 index e6be6f9..0000000 --- a/Sources/Typesense/Models/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// CreateAnalyticsRule200ResponseOneOfInnerAnyOf.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation -#if canImport(AnyCodable) -import AnyCodable -#endif - -public struct CreateAnalyticsRule200ResponseOneOfInnerAnyOf: Codable { - - public var error: String? - - public init(error: String? = nil) { - self.error = error - } - - public enum CodingKeys: String, CodingKey, CaseIterable { - case error - } - - // Encodable protocol methods - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(error, forKey: .error) - } -} diff --git a/Sources/Typesense/Models/CurationItemCreateSchema.swift b/Sources/Typesense/Models/CurationItemCreateSchema.swift index 9567a38..70d77c9 100644 --- a/Sources/Typesense/Models/CurationItemCreateSchema.swift +++ b/Sources/Typesense/Models/CurationItemCreateSchema.swift @@ -12,80 +12,80 @@ import AnyCodable public struct CurationItemCreateSchema: Codable { - /** A Unix timestamp that indicates the date/time from which the curation will be active. You can use this to create rules that start applying from a future point in time. */ - public var effectiveFromTs: Int? - /** A Unix timestamp that indicates the date/time until which the curation will be active. You can use this to create rules that stop applying after a period of time. */ - public var effectiveToTs: Int? + public var rule: CurationRule + /** List of document `id`s that should be included in the search results with their corresponding `position`s. */ + public var includes: [CurationInclude]? /** List of document `id`s that should be excluded from the search results. */ public var excludes: [CurationExclude]? /** A filter by clause that is applied to any search query that matches the curation rule. */ public var filterBy: String? - /** When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. */ - public var filterCuratedHits: Bool? - /** ID of the curation item */ - public var id: String? - /** List of document `id`s that should be included in the search results with their corresponding `position`s. */ - public var includes: [CurationInclude]? - /** 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. */ - public var metadata: AnyCodable? /** Indicates whether search query tokens that exist in the curation's rule should be removed from the search query. */ public var removeMatchedTokens: Bool? - /** Replaces the current search query with this value, when the search query matches the curation rule. */ - public var replaceQuery: String? - public var rule: CurationRule + /** 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. */ + public var metadata: AnyCodable? /** A sort by clause that is applied to any search query that matches the curation rule. */ public var sortBy: String? + /** Replaces the current search query with this value, when the search query matches the curation rule. */ + public var replaceQuery: String? + /** When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. */ + public var filterCuratedHits: Bool? + /** A Unix timestamp that indicates the date/time from which the curation will be active. You can use this to create rules that start applying from a future point in time. */ + public var effectiveFromTs: Int? + /** A Unix timestamp that indicates the date/time until which the curation will be active. You can use this to create rules that stop applying after a period of time. */ + public var effectiveToTs: Int? /** When set to true, curation processing will stop at the first matching rule. When set to false curation processing will continue and multiple curation actions will be triggered in sequence. Curations are processed in the lexical sort order of their id field. */ public var stopProcessing: Bool? + /** ID of the curation item */ + public var id: String? - public init(rule: CurationRule, effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, id: String? = nil, includes: [CurationInclude]? = nil, metadata: AnyCodable? = nil, removeMatchedTokens: Bool? = nil, replaceQuery: String? = nil, sortBy: String? = nil, stopProcessing: Bool? = nil) { - self.effectiveFromTs = effectiveFromTs - self.effectiveToTs = effectiveToTs + public init(rule: CurationRule, includes: [CurationInclude]? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, removeMatchedTokens: Bool? = nil, metadata: AnyCodable? = nil, sortBy: String? = nil, replaceQuery: String? = nil, filterCuratedHits: Bool? = nil, effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, stopProcessing: Bool? = nil, id: String? = nil) { + self.rule = rule + self.includes = includes self.excludes = excludes self.filterBy = filterBy - self.filterCuratedHits = filterCuratedHits - self.id = id - self.includes = includes - self.metadata = metadata self.removeMatchedTokens = removeMatchedTokens - self.replaceQuery = replaceQuery - self.rule = rule + self.metadata = metadata self.sortBy = sortBy + self.replaceQuery = replaceQuery + self.filterCuratedHits = filterCuratedHits + self.effectiveFromTs = effectiveFromTs + self.effectiveToTs = effectiveToTs self.stopProcessing = stopProcessing + self.id = id } public enum CodingKeys: String, CodingKey, CaseIterable { - case effectiveFromTs = "effective_from_ts" - case effectiveToTs = "effective_to_ts" + case rule + case includes case excludes case filterBy = "filter_by" - case filterCuratedHits = "filter_curated_hits" - case id - case includes - case metadata case removeMatchedTokens = "remove_matched_tokens" - case replaceQuery = "replace_query" - case rule + case metadata case sortBy = "sort_by" + case replaceQuery = "replace_query" + case filterCuratedHits = "filter_curated_hits" + case effectiveFromTs = "effective_from_ts" + case effectiveToTs = "effective_to_ts" case stopProcessing = "stop_processing" + case id } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(effectiveFromTs, forKey: .effectiveFromTs) - try container.encodeIfPresent(effectiveToTs, forKey: .effectiveToTs) + try container.encode(rule, forKey: .rule) + try container.encodeIfPresent(includes, forKey: .includes) try container.encodeIfPresent(excludes, forKey: .excludes) try container.encodeIfPresent(filterBy, forKey: .filterBy) - try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) - try container.encodeIfPresent(id, forKey: .id) - try container.encodeIfPresent(includes, forKey: .includes) - try container.encodeIfPresent(metadata, forKey: .metadata) try container.encodeIfPresent(removeMatchedTokens, forKey: .removeMatchedTokens) - try container.encodeIfPresent(replaceQuery, forKey: .replaceQuery) - try container.encode(rule, forKey: .rule) + try container.encodeIfPresent(metadata, forKey: .metadata) try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(replaceQuery, forKey: .replaceQuery) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) + try container.encodeIfPresent(effectiveFromTs, forKey: .effectiveFromTs) + try container.encodeIfPresent(effectiveToTs, forKey: .effectiveToTs) try container.encodeIfPresent(stopProcessing, forKey: .stopProcessing) + try container.encodeIfPresent(id, forKey: .id) } } diff --git a/Sources/Typesense/Models/CurationItemSchema.swift b/Sources/Typesense/Models/CurationItemSchema.swift index b5d0da4..fa02dd4 100644 --- a/Sources/Typesense/Models/CurationItemSchema.swift +++ b/Sources/Typesense/Models/CurationItemSchema.swift @@ -12,79 +12,79 @@ import AnyCodable public struct CurationItemSchema: Codable { - /** A Unix timestamp that indicates the date/time from which the curation will be active. You can use this to create rules that start applying from a future point in time. */ - public var effectiveFromTs: Int? - /** A Unix timestamp that indicates the date/time until which the curation will be active. You can use this to create rules that stop applying after a period of time. */ - public var effectiveToTs: Int? + public var rule: CurationRule + /** List of document `id`s that should be included in the search results with their corresponding `position`s. */ + public var includes: [CurationInclude]? /** List of document `id`s that should be excluded from the search results. */ public var excludes: [CurationExclude]? /** A filter by clause that is applied to any search query that matches the curation rule. */ public var filterBy: String? - /** When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. */ - public var filterCuratedHits: Bool? - public var id: String - /** List of document `id`s that should be included in the search results with their corresponding `position`s. */ - public var includes: [CurationInclude]? - /** 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. */ - public var metadata: AnyCodable? /** Indicates whether search query tokens that exist in the curation's rule should be removed from the search query. */ public var removeMatchedTokens: Bool? - /** Replaces the current search query with this value, when the search query matches the curation rule. */ - public var replaceQuery: String? - public var rule: CurationRule + /** 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. */ + public var metadata: AnyCodable? /** A sort by clause that is applied to any search query that matches the curation rule. */ public var sortBy: String? + /** Replaces the current search query with this value, when the search query matches the curation rule. */ + public var replaceQuery: String? + /** When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. */ + public var filterCuratedHits: Bool? + /** A Unix timestamp that indicates the date/time from which the curation will be active. You can use this to create rules that start applying from a future point in time. */ + public var effectiveFromTs: Int? + /** A Unix timestamp that indicates the date/time until which the curation will be active. You can use this to create rules that stop applying after a period of time. */ + public var effectiveToTs: Int? /** When set to true, curation processing will stop at the first matching rule. When set to false curation processing will continue and multiple curation actions will be triggered in sequence. Curations are processed in the lexical sort order of their id field. */ public var stopProcessing: Bool? + public var id: String - public init(id: String, rule: CurationRule, effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, includes: [CurationInclude]? = nil, metadata: AnyCodable? = nil, removeMatchedTokens: Bool? = nil, replaceQuery: String? = nil, sortBy: String? = nil, stopProcessing: Bool? = nil) { - self.effectiveFromTs = effectiveFromTs - self.effectiveToTs = effectiveToTs + public init(rule: CurationRule, id: String, includes: [CurationInclude]? = nil, excludes: [CurationExclude]? = nil, filterBy: String? = nil, removeMatchedTokens: Bool? = nil, metadata: AnyCodable? = nil, sortBy: String? = nil, replaceQuery: String? = nil, filterCuratedHits: Bool? = nil, effectiveFromTs: Int? = nil, effectiveToTs: Int? = nil, stopProcessing: Bool? = nil) { + self.rule = rule + self.includes = includes self.excludes = excludes self.filterBy = filterBy - self.filterCuratedHits = filterCuratedHits - self.id = id - self.includes = includes - self.metadata = metadata self.removeMatchedTokens = removeMatchedTokens - self.replaceQuery = replaceQuery - self.rule = rule + self.metadata = metadata self.sortBy = sortBy + self.replaceQuery = replaceQuery + self.filterCuratedHits = filterCuratedHits + self.effectiveFromTs = effectiveFromTs + self.effectiveToTs = effectiveToTs self.stopProcessing = stopProcessing + self.id = id } public enum CodingKeys: String, CodingKey, CaseIterable { - case effectiveFromTs = "effective_from_ts" - case effectiveToTs = "effective_to_ts" + case rule + case includes case excludes case filterBy = "filter_by" - case filterCuratedHits = "filter_curated_hits" - case id - case includes - case metadata case removeMatchedTokens = "remove_matched_tokens" - case replaceQuery = "replace_query" - case rule + case metadata case sortBy = "sort_by" + case replaceQuery = "replace_query" + case filterCuratedHits = "filter_curated_hits" + case effectiveFromTs = "effective_from_ts" + case effectiveToTs = "effective_to_ts" case stopProcessing = "stop_processing" + case id } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(effectiveFromTs, forKey: .effectiveFromTs) - try container.encodeIfPresent(effectiveToTs, forKey: .effectiveToTs) + try container.encode(rule, forKey: .rule) + try container.encodeIfPresent(includes, forKey: .includes) try container.encodeIfPresent(excludes, forKey: .excludes) try container.encodeIfPresent(filterBy, forKey: .filterBy) - try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) - try container.encode(id, forKey: .id) - try container.encodeIfPresent(includes, forKey: .includes) - try container.encodeIfPresent(metadata, forKey: .metadata) try container.encodeIfPresent(removeMatchedTokens, forKey: .removeMatchedTokens) - try container.encodeIfPresent(replaceQuery, forKey: .replaceQuery) - try container.encode(rule, forKey: .rule) + try container.encodeIfPresent(metadata, forKey: .metadata) try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(replaceQuery, forKey: .replaceQuery) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) + try container.encodeIfPresent(effectiveFromTs, forKey: .effectiveFromTs) + try container.encodeIfPresent(effectiveToTs, forKey: .effectiveToTs) try container.encodeIfPresent(stopProcessing, forKey: .stopProcessing) + try container.encode(id, forKey: .id) } } diff --git a/Sources/Typesense/Models/CurationRule.swift b/Sources/Typesense/Models/CurationRule.swift index b627fe3..f77b495 100644 --- a/Sources/Typesense/Models/CurationRule.swift +++ b/Sources/Typesense/Models/CurationRule.swift @@ -16,36 +16,36 @@ public struct CurationRule: Codable { case exact = "exact" case contains = "contains" } - /** Indicates that the curation should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). */ - public var filterBy: 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. */ - public var match: Match? - /** Indicates what search queries should be curated */ - public var query: String? /** List of tag values to associate with this curation rule. */ public var tags: [String]? + /** Indicates what search queries should be curated */ + public var 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. */ + public var match: Match? + /** Indicates that the curation should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). */ + public var filterBy: String? - public init(filterBy: String? = nil, match: Match? = nil, query: String? = nil, tags: [String]? = nil) { - self.filterBy = filterBy - self.match = match - self.query = query + public init(tags: [String]? = nil, query: String? = nil, match: Match? = nil, filterBy: String? = nil) { self.tags = tags + self.query = query + self.match = match + self.filterBy = filterBy } public enum CodingKeys: String, CodingKey, CaseIterable { - case filterBy = "filter_by" - case match - case query case tags + case query + case match + case filterBy = "filter_by" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(filterBy, forKey: .filterBy) - try container.encodeIfPresent(match, forKey: .match) - try container.encodeIfPresent(query, forKey: .query) try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(query, forKey: .query) + try container.encodeIfPresent(match, forKey: .match) + try container.encodeIfPresent(filterBy, forKey: .filterBy) } } diff --git a/Sources/Typesense/Models/CurationSetCreateSchema.swift b/Sources/Typesense/Models/CurationSetCreateSchema.swift index 7831154..e8c6fc6 100644 --- a/Sources/Typesense/Models/CurationSetCreateSchema.swift +++ b/Sources/Typesense/Models/CurationSetCreateSchema.swift @@ -12,26 +12,26 @@ import AnyCodable public struct CurationSetCreateSchema: Codable { - /** Optional description for the curation set */ - public var description: String? /** Array of curation items */ public var items: [CurationItemCreateSchema] + /** Optional description for the curation set */ + public var description: String? public init(items: [CurationItemCreateSchema], description: String? = nil) { - self.description = description self.items = items + self.description = description } public enum CodingKeys: String, CodingKey, CaseIterable { - case description case items + case description } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(description, forKey: .description) try container.encode(items, forKey: .items) + try container.encodeIfPresent(description, forKey: .description) } } diff --git a/Sources/Typesense/Models/CurationSetSchema.swift b/Sources/Typesense/Models/CurationSetSchema.swift index a661733..f67b4d0 100644 --- a/Sources/Typesense/Models/CurationSetSchema.swift +++ b/Sources/Typesense/Models/CurationSetSchema.swift @@ -12,21 +12,21 @@ import AnyCodable public struct CurationSetSchema: Codable { - /** Optional description for the curation set */ - public var description: String? /** Array of curation items */ public var items: [CurationItemCreateSchema] + /** Optional description for the curation set */ + public var description: String? public var name: String public init(items: [CurationItemCreateSchema], name: String, description: String? = nil) { - self.description = description self.items = items + self.description = description self.name = name } public enum CodingKeys: String, CodingKey, CaseIterable { - case description case items + case description case name } @@ -34,8 +34,8 @@ public struct CurationSetSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(description, forKey: .description) try container.encode(items, forKey: .items) + try container.encodeIfPresent(description, forKey: .description) try container.encode(name, forKey: .name) } } diff --git a/Sources/Typesense/Models/DeleteDocumentsParameters.swift b/Sources/Typesense/Models/DeleteDocumentsParameters.swift index 6c6ca48..8c6ed01 100644 --- a/Sources/Typesense/Models/DeleteDocumentsParameters.swift +++ b/Sources/Typesense/Models/DeleteDocumentsParameters.swift @@ -12,23 +12,23 @@ import AnyCodable public struct DeleteDocumentsParameters: Codable { + public var filterBy: 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. */ public var batchSize: Int? - public var filterBy: String public var ignoreNotFound: Bool? /** When true, removes all documents from the collection while preserving the collection and its schema. */ public var truncate: Bool? public init(filterBy: String, batchSize: Int? = nil, ignoreNotFound: Bool? = nil, truncate: Bool? = nil) { - self.batchSize = batchSize self.filterBy = filterBy + self.batchSize = batchSize self.ignoreNotFound = ignoreNotFound self.truncate = truncate } public enum CodingKeys: String, CodingKey, CaseIterable { - case batchSize = "batch_size" case filterBy = "filter_by" + case batchSize = "batch_size" case ignoreNotFound = "ignore_not_found" case truncate } @@ -37,8 +37,8 @@ public struct DeleteDocumentsParameters: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(batchSize, forKey: .batchSize) try container.encode(filterBy, forKey: .filterBy) + try container.encodeIfPresent(batchSize, forKey: .batchSize) try container.encodeIfPresent(ignoreNotFound, forKey: .ignoreNotFound) try container.encodeIfPresent(truncate, forKey: .truncate) } diff --git a/Sources/Typesense/Models/ExportDocumentsParameters.swift b/Sources/Typesense/Models/ExportDocumentsParameters.swift index 35036f1..8725d70 100644 --- a/Sources/Typesense/Models/ExportDocumentsParameters.swift +++ b/Sources/Typesense/Models/ExportDocumentsParameters.swift @@ -12,31 +12,31 @@ import AnyCodable public struct ExportDocumentsParameters: Codable { - /** List of fields from the document to exclude in the search result */ - public var excludeFields: String? /** Filter conditions for refining your search results. Separate multiple conditions with &&. */ public var filterBy: String? /** List of fields from the document to include in the search result */ public var includeFields: String? + /** List of fields from the document to exclude in the search result */ + public var excludeFields: String? - public init(excludeFields: String? = nil, filterBy: String? = nil, includeFields: String? = nil) { - self.excludeFields = excludeFields + public init(filterBy: String? = nil, includeFields: String? = nil, excludeFields: String? = nil) { self.filterBy = filterBy self.includeFields = includeFields + self.excludeFields = excludeFields } public enum CodingKeys: String, CodingKey, CaseIterable { - case excludeFields = "exclude_fields" case filterBy = "filter_by" case includeFields = "include_fields" + case excludeFields = "exclude_fields" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(excludeFields, forKey: .excludeFields) try container.encodeIfPresent(filterBy, forKey: .filterBy) try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(excludeFields, forKey: .excludeFields) } } diff --git a/Sources/Typesense/Models/FacetCountsCountsInner.swift b/Sources/Typesense/Models/FacetCountsCountsInner.swift index 7eea689..b07d31a 100644 --- a/Sources/Typesense/Models/FacetCountsCountsInner.swift +++ b/Sources/Typesense/Models/FacetCountsCountsInner.swift @@ -14,21 +14,21 @@ public struct FacetCountsCountsInner: Codable { public var count: Int? public var highlighted: String? - public var parent: AnyCodable? public var value: String? + public var parent: AnyCodable? - public init(count: Int? = nil, highlighted: String? = nil, parent: AnyCodable? = nil, value: String? = nil) { + public init(count: Int? = nil, highlighted: String? = nil, value: String? = nil, parent: AnyCodable? = nil) { self.count = count self.highlighted = highlighted - self.parent = parent self.value = value + self.parent = parent } public enum CodingKeys: String, CodingKey, CaseIterable { case count case highlighted - case parent case value + case parent } // Encodable protocol methods @@ -37,7 +37,7 @@ public struct FacetCountsCountsInner: Codable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(count, forKey: .count) try container.encodeIfPresent(highlighted, forKey: .highlighted) - try container.encodeIfPresent(parent, forKey: .parent) try container.encodeIfPresent(value, forKey: .value) + try container.encodeIfPresent(parent, forKey: .parent) } } diff --git a/Sources/Typesense/Models/FacetCountsStats.swift b/Sources/Typesense/Models/FacetCountsStats.swift index ab04324..b78151f 100644 --- a/Sources/Typesense/Models/FacetCountsStats.swift +++ b/Sources/Typesense/Models/FacetCountsStats.swift @@ -12,36 +12,36 @@ import AnyCodable public struct FacetCountsStats: Codable { - public var avg: Double? public var max: Double? public var min: Double? public var sum: Double? public var totalValues: Int? + public var avg: Double? - public init(avg: Double? = nil, max: Double? = nil, min: Double? = nil, sum: Double? = nil, totalValues: Int? = nil) { - self.avg = avg + public init(max: Double? = nil, min: Double? = nil, sum: Double? = nil, totalValues: Int? = nil, avg: Double? = nil) { self.max = max self.min = min self.sum = sum self.totalValues = totalValues + self.avg = avg } public enum CodingKeys: String, CodingKey, CaseIterable { - case avg case max case min case sum case totalValues = "total_values" + case avg } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(avg, forKey: .avg) try container.encodeIfPresent(max, forKey: .max) try container.encodeIfPresent(min, forKey: .min) try container.encodeIfPresent(sum, forKey: .sum) try container.encodeIfPresent(totalValues, forKey: .totalValues) + try container.encodeIfPresent(avg, forKey: .avg) } } diff --git a/Sources/Typesense/Models/Field.swift b/Sources/Typesense/Models/Field.swift index 27eebb0..cea6c85 100644 --- a/Sources/Typesense/Models/Field.swift +++ b/Sources/Typesense/Models/Field.swift @@ -12,100 +12,100 @@ import AnyCodable public struct Field: Codable { - public var drop: Bool? - public var embed: FieldEmbed? + public var name: String + public var type: String + public var _optional: Bool? public var facet: Bool? public var index: Bool? = true - public var _infix: Bool? = false public var locale: String? - public var name: String + public var sort: Bool? + public var _infix: Bool? = false + /** Name of a field in another collection that should be linked to this collection so that it can be joined during query. */ + public var reference: String? public var numDim: Int? - public var _optional: Bool? + public var drop: Bool? + /** When set to false, the field value will not be stored on disk. Default: true. */ + public var store: Bool? + /** The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. */ + public var vecDist: String? /** Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. */ public var rangeIndex: Bool? - /** Name of a field in another collection that should be linked to this collection so that it can be joined during query. */ - public var reference: String? - public var sort: Bool? /** Values are stemmed before indexing in-memory. Default: false. */ public var stem: Bool? /** Name of the stemming dictionary to use for this field */ public var stemDictionary: String? - /** When set to false, the field value will not be stored on disk. Default: true. */ - public var store: Bool? - /** List of symbols or special characters to be indexed. */ - public var symbolsToIndex: [String]? /** List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. */ public var tokenSeparators: [String]? - public var type: String - /** The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. */ - public var vecDist: String? + /** List of symbols or special characters to be indexed. */ + public var symbolsToIndex: [String]? + public var embed: FieldEmbed? - public init(name: String, type: String, drop: Bool? = nil, embed: FieldEmbed? = nil, facet: Bool? = nil, index: Bool? = true, _infix: Bool? = false, locale: String? = nil, numDim: Int? = nil, _optional: Bool? = nil, rangeIndex: Bool? = nil, reference: String? = nil, sort: Bool? = nil, stem: Bool? = nil, stemDictionary: String? = nil, store: Bool? = nil, symbolsToIndex: [String]? = nil, tokenSeparators: [String]? = nil, vecDist: String? = nil) { - self.drop = drop - self.embed = embed + public init(name: String, type: String, _optional: Bool? = nil, facet: Bool? = nil, index: Bool? = true, locale: String? = nil, sort: Bool? = nil, _infix: Bool? = false, reference: String? = nil, numDim: Int? = nil, drop: Bool? = nil, store: Bool? = nil, vecDist: String? = nil, rangeIndex: Bool? = nil, stem: Bool? = nil, stemDictionary: String? = nil, tokenSeparators: [String]? = nil, symbolsToIndex: [String]? = nil, embed: FieldEmbed? = nil) { + self.name = name + self.type = type + self._optional = _optional self.facet = facet self.index = index - self._infix = _infix self.locale = locale - self.name = name + self.sort = sort + self._infix = _infix + self.reference = reference self.numDim = numDim - self._optional = _optional + self.drop = drop + self.store = store + self.vecDist = vecDist self.rangeIndex = rangeIndex - self.reference = reference - self.sort = sort self.stem = stem self.stemDictionary = stemDictionary - self.store = store - self.symbolsToIndex = symbolsToIndex self.tokenSeparators = tokenSeparators - self.type = type - self.vecDist = vecDist + self.symbolsToIndex = symbolsToIndex + self.embed = embed } public enum CodingKeys: String, CodingKey, CaseIterable { - case drop - case embed + case name + case type + case _optional = "optional" case facet case index - case _infix = "infix" case locale - case name + case sort + case _infix = "infix" + case reference case numDim = "num_dim" - case _optional = "optional" + case drop + case store + case vecDist = "vec_dist" case rangeIndex = "range_index" - case reference - case sort case stem case stemDictionary = "stem_dictionary" - case store - case symbolsToIndex = "symbols_to_index" case tokenSeparators = "token_separators" - case type - case vecDist = "vec_dist" + case symbolsToIndex = "symbols_to_index" + case embed } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(drop, forKey: .drop) - try container.encodeIfPresent(embed, forKey: .embed) + try container.encode(name, forKey: .name) + try container.encode(type, forKey: .type) + try container.encodeIfPresent(_optional, forKey: ._optional) try container.encodeIfPresent(facet, forKey: .facet) try container.encodeIfPresent(index, forKey: .index) - try container.encodeIfPresent(_infix, forKey: ._infix) try container.encodeIfPresent(locale, forKey: .locale) - try container.encode(name, forKey: .name) + try container.encodeIfPresent(sort, forKey: .sort) + try container.encodeIfPresent(_infix, forKey: ._infix) + try container.encodeIfPresent(reference, forKey: .reference) try container.encodeIfPresent(numDim, forKey: .numDim) - try container.encodeIfPresent(_optional, forKey: ._optional) + try container.encodeIfPresent(drop, forKey: .drop) + try container.encodeIfPresent(store, forKey: .store) + try container.encodeIfPresent(vecDist, forKey: .vecDist) try container.encodeIfPresent(rangeIndex, forKey: .rangeIndex) - try container.encodeIfPresent(reference, forKey: .reference) - try container.encodeIfPresent(sort, forKey: .sort) try container.encodeIfPresent(stem, forKey: .stem) try container.encodeIfPresent(stemDictionary, forKey: .stemDictionary) - try container.encodeIfPresent(store, forKey: .store) - try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) try container.encodeIfPresent(tokenSeparators, forKey: .tokenSeparators) - try container.encode(type, forKey: .type) - try container.encodeIfPresent(vecDist, forKey: .vecDist) + try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) + try container.encodeIfPresent(embed, forKey: .embed) } } diff --git a/Sources/Typesense/Models/FieldEmbedModelConfig.swift b/Sources/Typesense/Models/FieldEmbedModelConfig.swift index 16c8b77..a0fd5ee 100644 --- a/Sources/Typesense/Models/FieldEmbedModelConfig.swift +++ b/Sources/Typesense/Models/FieldEmbedModelConfig.swift @@ -12,56 +12,56 @@ import AnyCodable public struct FieldEmbedModelConfig: Codable { - public var accessToken: String? + public var modelName: String public var apiKey: String? + public var url: String? + public var accessToken: String? + public var refreshToken: String? public var clientId: String? public var clientSecret: String? - public var indexingPrefix: String? - public var modelName: String public var projectId: String? + public var indexingPrefix: String? public var queryPrefix: String? - public var refreshToken: String? - public var url: String? - public init(modelName: String, accessToken: String? = nil, apiKey: String? = nil, clientId: String? = nil, clientSecret: String? = nil, indexingPrefix: String? = nil, projectId: String? = nil, queryPrefix: String? = nil, refreshToken: String? = nil, url: String? = nil) { - self.accessToken = accessToken + public init(modelName: String, apiKey: String? = nil, url: String? = nil, accessToken: String? = nil, refreshToken: String? = nil, clientId: String? = nil, clientSecret: String? = nil, projectId: String? = nil, indexingPrefix: String? = nil, queryPrefix: String? = nil) { + self.modelName = modelName self.apiKey = apiKey + self.url = url + self.accessToken = accessToken + self.refreshToken = refreshToken self.clientId = clientId self.clientSecret = clientSecret - self.indexingPrefix = indexingPrefix - self.modelName = modelName self.projectId = projectId + self.indexingPrefix = indexingPrefix self.queryPrefix = queryPrefix - self.refreshToken = refreshToken - self.url = url } public enum CodingKeys: String, CodingKey, CaseIterable { - case accessToken = "access_token" + case modelName = "model_name" case apiKey = "api_key" + case url + case accessToken = "access_token" + case refreshToken = "refresh_token" case clientId = "client_id" case clientSecret = "client_secret" - case indexingPrefix = "indexing_prefix" - case modelName = "model_name" case projectId = "project_id" + case indexingPrefix = "indexing_prefix" case queryPrefix = "query_prefix" - case refreshToken = "refresh_token" - case url } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(accessToken, forKey: .accessToken) + try container.encode(modelName, forKey: .modelName) try container.encodeIfPresent(apiKey, forKey: .apiKey) + try container.encodeIfPresent(url, forKey: .url) + try container.encodeIfPresent(accessToken, forKey: .accessToken) + try container.encodeIfPresent(refreshToken, forKey: .refreshToken) try container.encodeIfPresent(clientId, forKey: .clientId) try container.encodeIfPresent(clientSecret, forKey: .clientSecret) - try container.encodeIfPresent(indexingPrefix, forKey: .indexingPrefix) - try container.encode(modelName, forKey: .modelName) try container.encodeIfPresent(projectId, forKey: .projectId) + try container.encodeIfPresent(indexingPrefix, forKey: .indexingPrefix) try container.encodeIfPresent(queryPrefix, forKey: .queryPrefix) - try container.encodeIfPresent(refreshToken, forKey: .refreshToken) - try container.encodeIfPresent(url, forKey: .url) } } diff --git a/Sources/Typesense/Models/ImportDocumentsParameters.swift b/Sources/Typesense/Models/ImportDocumentsParameters.swift index aa6a49e..96e6127 100644 --- a/Sources/Typesense/Models/ImportDocumentsParameters.swift +++ b/Sources/Typesense/Models/ImportDocumentsParameters.swift @@ -12,41 +12,41 @@ import AnyCodable public struct ImportDocumentsParameters: Codable { - public var action: IndexAction? public var batchSize: Int? - public var dirtyValues: DirtyValues? - public var remoteEmbeddingBatchSize: Int? - public var returnDoc: 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. */ public var returnId: Bool? + public var remoteEmbeddingBatchSize: Int? + public var returnDoc: Bool? + public var action: IndexAction? + public var dirtyValues: DirtyValues? - public init(action: IndexAction? = nil, batchSize: Int? = nil, dirtyValues: DirtyValues? = nil, remoteEmbeddingBatchSize: Int? = nil, returnDoc: Bool? = nil, returnId: Bool? = nil) { - self.action = action + public init(batchSize: Int? = nil, returnId: Bool? = nil, remoteEmbeddingBatchSize: Int? = nil, returnDoc: Bool? = nil, action: IndexAction? = nil, dirtyValues: DirtyValues? = nil) { self.batchSize = batchSize - self.dirtyValues = dirtyValues + self.returnId = returnId self.remoteEmbeddingBatchSize = remoteEmbeddingBatchSize self.returnDoc = returnDoc - self.returnId = returnId + self.action = action + self.dirtyValues = dirtyValues } public enum CodingKeys: String, CodingKey, CaseIterable { - case action case batchSize = "batch_size" - case dirtyValues = "dirty_values" + case returnId = "return_id" case remoteEmbeddingBatchSize = "remote_embedding_batch_size" case returnDoc = "return_doc" - case returnId = "return_id" + case action + case dirtyValues = "dirty_values" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(action, forKey: .action) try container.encodeIfPresent(batchSize, forKey: .batchSize) - try container.encodeIfPresent(dirtyValues, forKey: .dirtyValues) + try container.encodeIfPresent(returnId, forKey: .returnId) try container.encodeIfPresent(remoteEmbeddingBatchSize, forKey: .remoteEmbeddingBatchSize) try container.encodeIfPresent(returnDoc, forKey: .returnDoc) - try container.encodeIfPresent(returnId, forKey: .returnId) + try container.encodeIfPresent(action, forKey: .action) + try container.encodeIfPresent(dirtyValues, forKey: .dirtyValues) } } diff --git a/Sources/Typesense/Models/MultiSearchCollectionParameters.swift b/Sources/Typesense/Models/MultiSearchCollectionParameters.swift index 0e381c0..8ae335a 100644 --- a/Sources/Typesense/Models/MultiSearchCollectionParameters.swift +++ b/Sources/Typesense/Models/MultiSearchCollectionParameters.swift @@ -12,350 +12,350 @@ import AnyCodable public struct MultiSearchCollectionParameters: Codable { - /** 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. */ - public var cacheTtl: Int? - /** Enable conversational search. */ - public var conversation: Bool? - /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ - public var conversationId: String? - /** The Id of Conversation Model to be used. */ - public var conversationModelId: String? - public var dropTokensMode: DropTokensMode? - /** 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 */ - public var dropTokensThreshold: Int? - /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ - public var enableAnalytics: Bool? = true - /** 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 */ - public var enableOverrides: Bool? = false - /** 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 */ - public var enableSynonyms: Bool? - /** Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. */ - public var enableTyposForAlphaNumericalTokens: Bool? - /** Make Typesense disable typos for numerical tokens. */ - public var enableTyposForNumericalTokens: Bool? = true - /** List of fields from the document to exclude in the search result */ - public var excludeFields: String? - /** 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). */ - public var exhaustiveSearch: Bool? - /** A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. */ - public var facetBy: String? - /** 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\". */ - public var facetQuery: String? - /** Comma separated string of nested facet fields whose parent object should be returned in facet response. */ - public var facetReturnParent: String? - /** Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). */ - public var facetStrategy: String? - /** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */ - public var filterBy: String? - /** Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false */ - public var filterCuratedHits: Bool? - /** 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. */ - public var groupBy: String? - /** 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 */ - public var groupLimit: Int? - /** 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 */ - public var groupMissingValues: Bool? - /** 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`. */ - public var hiddenHits: String? - /** The number of tokens that should surround the highlighted text on each side. Default: 4 */ - public var highlightAffixNumTokens: Int? - /** The end tag used for the highlighted snippets. Default: `` */ - public var highlightEndTag: String? - /** A list of custom fields that must be highlighted even if you don't query for them */ - public var highlightFields: String? - /** List of fields which should be highlighted fully without snippeting */ - public var highlightFullFields: String? - /** The start tag used for the highlighted snippets. Default: `` */ - public var highlightStartTag: String? - /** List of fields from the document to include in the search result */ - public var includeFields: 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. */ + public var q: String? + /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ + public var queryBy: 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. */ + public var queryByWeights: 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. */ + public var textMatchType: 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. */ + public var _prefix: String? /** 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 */ public var _infix: String? - /** Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. */ - public var limit: Int? /** 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. */ public var maxExtraPrefix: Int? /** 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. */ public var maxExtraSuffix: Int? + /** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */ + public var filterBy: 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` */ + public var sortBy: String? + /** A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. */ + public var facetBy: String? /** Maximum number of facet values to be returned. */ public var maxFacetValues: Int? - /** Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ - public var minLen1typo: Int? - /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ - public var minLen2typo: Int? + /** 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\". */ + public var facetQuery: String? /** The number of typographical errors (1 or 2) that would be tolerated. Default: 2 */ public var numTypos: String? - /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ - public var offset: Int? - /** Comma separated list of tags to trigger the curations rules that match the tags. */ - public var overrideTags: String? /** Results from this specific page number would be fetched. */ public var page: Int? /** Number of results to fetch per page. Default: 10 */ public var perPage: Int? + /** Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. */ + public var limit: Int? + /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ + public var offset: Int? + /** 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. */ + public var groupBy: String? + /** 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 */ + public var groupLimit: Int? + /** 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 */ + public var groupMissingValues: Bool? + /** List of fields from the document to include in the search result */ + public var includeFields: String? + /** List of fields from the document to exclude in the search result */ + public var excludeFields: String? + /** List of fields which should be highlighted fully without snippeting */ + public var highlightFullFields: String? + /** The number of tokens that should surround the highlighted text on each side. Default: 4 */ + public var highlightAffixNumTokens: Int? + /** The start tag used for the highlighted snippets. Default: `` */ + public var highlightStartTag: String? + /** The end tag used for the highlighted snippets. Default: `` */ + public var highlightEndTag: String? + /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ + public var snippetThreshold: Int? + /** 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 */ + public var dropTokensThreshold: Int? + public var dropTokensMode: DropTokensMode? + /** 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 */ + public var typoTokensThreshold: Int? + /** Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. */ + public var enableTyposForAlphaNumericalTokens: 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 */ + public var filterCuratedHits: 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 */ + public var enableSynonyms: Bool? + /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ + public var enableAnalytics: Bool? = true + /** Allow synonym resolution on word prefixes in the query. Default: false */ + public var synonymPrefix: Bool? + /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ + public var synonymNumTypos: Int? /** 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`. */ public var pinnedHits: 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`. */ + public var hiddenHits: String? + /** Comma separated list of tags to trigger the curations rules that match the tags. */ + public var overrideTags: String? + /** A list of custom fields that must be highlighted even if you don't query for them */ + public var highlightFields: String? /** 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 */ public var preSegmentedQuery: Bool? = false - /** 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. */ - public var _prefix: String? /** Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. */ public var preset: String? + /** 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 */ + public var enableOverrides: Bool? = false /** Set this parameter to true to ensure that an exact match is ranked above the others */ public var prioritizeExactMatch: Bool? = true - /** Make Typesense prioritize documents where the query words appear in more number of fields. */ - public var prioritizeNumMatchingFields: Bool? = true /** Make Typesense prioritize documents where the query words appear earlier in the text. */ public var prioritizeTokenPosition: Bool? = false - /** 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. */ - public var q: String? - /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ - public var queryBy: 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. */ - public var queryByWeights: String? - /** Number of times to retry fetching remote embeddings. */ - public var remoteEmbeddingNumTries: Int? - /** Timeout (in milliseconds) for fetching remote embeddings. */ - public var remoteEmbeddingTimeoutMs: Int? + /** Make Typesense prioritize documents where the query words appear in more number of fields. */ + public var prioritizeNumMatchingFields: Bool? = true + /** Make Typesense disable typos for numerical tokens. */ + public var enableTyposForNumericalTokens: Bool? = true + /** 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). */ + public var exhaustiveSearch: Bool? /** 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. */ public var searchCutoffMs: Int? - /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ - public var snippetThreshold: Int? - /** 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` */ - public var sortBy: String? - /** Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. */ - public var stopwords: String? - /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ - public var synonymNumTypos: Int? - /** Allow synonym resolution on word prefixes in the query. Default: false */ - public var synonymPrefix: Bool? - /** 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. */ - public var textMatchType: String? - /** 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 */ - public var typoTokensThreshold: Int? /** Enable server side caching of search query results. By default, caching is disabled. */ public var useCache: Bool? + /** 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. */ + public var cacheTtl: Int? + /** Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ + public var minLen1typo: Int? + /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ + public var minLen2typo: Int? /** Vector query expression for fetching documents \"closest\" to a given query/document vector. */ public var vectorQuery: String? + /** Timeout (in milliseconds) for fetching remote embeddings. */ + public var remoteEmbeddingTimeoutMs: Int? + /** Number of times to retry fetching remote embeddings. */ + public var remoteEmbeddingNumTries: Int? + /** Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). */ + public var facetStrategy: String? + /** Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. */ + public var stopwords: String? + /** Comma separated string of nested facet fields whose parent object should be returned in facet response. */ + public var facetReturnParent: String? /** The base64 encoded audio file in 16 khz 16-bit WAV format. */ public var voiceQuery: String? + /** Enable conversational search. */ + public var conversation: Bool? + /** The Id of Conversation Model to be used. */ + public var conversationModelId: String? + /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ + public var conversationId: String? /** The collection to search in. */ public var collection: String? - /** 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. */ - public var rerankHybridMatches: Bool? = false /** A separate search API key for each search within a multi_search request */ public var xTypesenseApiKey: String? + /** 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. */ + public var rerankHybridMatches: Bool? = false - public init(cacheTtl: Int? = nil, conversation: Bool? = nil, conversationId: String? = nil, conversationModelId: String? = nil, dropTokensMode: DropTokensMode? = nil, dropTokensThreshold: Int? = nil, enableAnalytics: Bool? = true, enableOverrides: Bool? = false, enableSynonyms: Bool? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, enableTyposForNumericalTokens: Bool? = true, excludeFields: String? = nil, exhaustiveSearch: Bool? = nil, facetBy: String? = nil, facetQuery: String? = nil, facetReturnParent: String? = nil, facetStrategy: String? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, hiddenHits: String? = nil, highlightAffixNumTokens: Int? = nil, highlightEndTag: String? = nil, highlightFields: String? = nil, highlightFullFields: String? = nil, highlightStartTag: String? = nil, includeFields: String? = nil, _infix: String? = nil, limit: Int? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, maxFacetValues: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, numTypos: String? = nil, offset: Int? = nil, overrideTags: String? = nil, page: Int? = nil, perPage: Int? = nil, pinnedHits: String? = nil, preSegmentedQuery: Bool? = false, _prefix: String? = nil, preset: String? = nil, prioritizeExactMatch: Bool? = true, prioritizeNumMatchingFields: Bool? = true, prioritizeTokenPosition: Bool? = false, q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, remoteEmbeddingNumTries: Int? = nil, remoteEmbeddingTimeoutMs: Int? = nil, searchCutoffMs: Int? = nil, snippetThreshold: Int? = nil, sortBy: String? = nil, stopwords: String? = nil, synonymNumTypos: Int? = nil, synonymPrefix: Bool? = nil, textMatchType: String? = nil, typoTokensThreshold: Int? = nil, useCache: Bool? = nil, vectorQuery: String? = nil, voiceQuery: String? = nil, collection: String? = nil, rerankHybridMatches: Bool? = false, xTypesenseApiKey: String? = nil) { - self.cacheTtl = cacheTtl - self.conversation = conversation - self.conversationId = conversationId - self.conversationModelId = conversationModelId - self.dropTokensMode = dropTokensMode - self.dropTokensThreshold = dropTokensThreshold - self.enableAnalytics = enableAnalytics - self.enableOverrides = enableOverrides - self.enableSynonyms = enableSynonyms - self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens - self.enableTyposForNumericalTokens = enableTyposForNumericalTokens - self.excludeFields = excludeFields - self.exhaustiveSearch = exhaustiveSearch - self.facetBy = facetBy - self.facetQuery = facetQuery - self.facetReturnParent = facetReturnParent - self.facetStrategy = facetStrategy - self.filterBy = filterBy - self.filterCuratedHits = filterCuratedHits - self.groupBy = groupBy - self.groupLimit = groupLimit - self.groupMissingValues = groupMissingValues - self.hiddenHits = hiddenHits - self.highlightAffixNumTokens = highlightAffixNumTokens - self.highlightEndTag = highlightEndTag - self.highlightFields = highlightFields - self.highlightFullFields = highlightFullFields - self.highlightStartTag = highlightStartTag - self.includeFields = includeFields + public init(q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, textMatchType: String? = nil, _prefix: String? = nil, _infix: String? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, filterBy: String? = nil, sortBy: String? = nil, facetBy: String? = nil, maxFacetValues: Int? = nil, facetQuery: String? = nil, numTypos: String? = nil, page: Int? = nil, perPage: Int? = nil, limit: Int? = nil, offset: Int? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, includeFields: String? = nil, excludeFields: String? = nil, highlightFullFields: String? = nil, highlightAffixNumTokens: Int? = nil, highlightStartTag: String? = nil, highlightEndTag: String? = nil, snippetThreshold: Int? = nil, dropTokensThreshold: Int? = nil, dropTokensMode: DropTokensMode? = nil, typoTokensThreshold: Int? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, filterCuratedHits: Bool? = nil, enableSynonyms: Bool? = nil, enableAnalytics: Bool? = true, synonymPrefix: Bool? = nil, synonymNumTypos: Int? = nil, pinnedHits: String? = nil, hiddenHits: String? = nil, overrideTags: String? = nil, highlightFields: String? = nil, preSegmentedQuery: Bool? = false, preset: String? = nil, enableOverrides: Bool? = false, prioritizeExactMatch: Bool? = true, prioritizeTokenPosition: Bool? = false, prioritizeNumMatchingFields: Bool? = true, enableTyposForNumericalTokens: Bool? = true, exhaustiveSearch: Bool? = nil, searchCutoffMs: Int? = nil, useCache: Bool? = nil, cacheTtl: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, vectorQuery: String? = nil, remoteEmbeddingTimeoutMs: Int? = nil, remoteEmbeddingNumTries: Int? = nil, facetStrategy: String? = nil, stopwords: String? = nil, facetReturnParent: String? = nil, voiceQuery: String? = nil, conversation: Bool? = nil, conversationModelId: String? = nil, conversationId: String? = nil, collection: String? = nil, xTypesenseApiKey: String? = nil, rerankHybridMatches: Bool? = false) { + self.q = q + self.queryBy = queryBy + self.queryByWeights = queryByWeights + self.textMatchType = textMatchType + self._prefix = _prefix self._infix = _infix - self.limit = limit self.maxExtraPrefix = maxExtraPrefix self.maxExtraSuffix = maxExtraSuffix + self.filterBy = filterBy + self.sortBy = sortBy + self.facetBy = facetBy self.maxFacetValues = maxFacetValues - self.minLen1typo = minLen1typo - self.minLen2typo = minLen2typo + self.facetQuery = facetQuery self.numTypos = numTypos - self.offset = offset - self.overrideTags = overrideTags self.page = page self.perPage = perPage + self.limit = limit + self.offset = offset + self.groupBy = groupBy + self.groupLimit = groupLimit + self.groupMissingValues = groupMissingValues + self.includeFields = includeFields + self.excludeFields = excludeFields + self.highlightFullFields = highlightFullFields + self.highlightAffixNumTokens = highlightAffixNumTokens + self.highlightStartTag = highlightStartTag + self.highlightEndTag = highlightEndTag + self.snippetThreshold = snippetThreshold + self.dropTokensThreshold = dropTokensThreshold + self.dropTokensMode = dropTokensMode + self.typoTokensThreshold = typoTokensThreshold + self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens + self.filterCuratedHits = filterCuratedHits + self.enableSynonyms = enableSynonyms + self.enableAnalytics = enableAnalytics + self.synonymPrefix = synonymPrefix + self.synonymNumTypos = synonymNumTypos self.pinnedHits = pinnedHits + self.hiddenHits = hiddenHits + self.overrideTags = overrideTags + self.highlightFields = highlightFields self.preSegmentedQuery = preSegmentedQuery - self._prefix = _prefix self.preset = preset + self.enableOverrides = enableOverrides self.prioritizeExactMatch = prioritizeExactMatch - self.prioritizeNumMatchingFields = prioritizeNumMatchingFields self.prioritizeTokenPosition = prioritizeTokenPosition - self.q = q - self.queryBy = queryBy - self.queryByWeights = queryByWeights - self.remoteEmbeddingNumTries = remoteEmbeddingNumTries - self.remoteEmbeddingTimeoutMs = remoteEmbeddingTimeoutMs + self.prioritizeNumMatchingFields = prioritizeNumMatchingFields + self.enableTyposForNumericalTokens = enableTyposForNumericalTokens + self.exhaustiveSearch = exhaustiveSearch self.searchCutoffMs = searchCutoffMs - self.snippetThreshold = snippetThreshold - self.sortBy = sortBy - self.stopwords = stopwords - self.synonymNumTypos = synonymNumTypos - self.synonymPrefix = synonymPrefix - self.textMatchType = textMatchType - self.typoTokensThreshold = typoTokensThreshold self.useCache = useCache + self.cacheTtl = cacheTtl + self.minLen1typo = minLen1typo + self.minLen2typo = minLen2typo self.vectorQuery = vectorQuery + self.remoteEmbeddingTimeoutMs = remoteEmbeddingTimeoutMs + self.remoteEmbeddingNumTries = remoteEmbeddingNumTries + self.facetStrategy = facetStrategy + self.stopwords = stopwords + self.facetReturnParent = facetReturnParent self.voiceQuery = voiceQuery + self.conversation = conversation + self.conversationModelId = conversationModelId + self.conversationId = conversationId self.collection = collection - self.rerankHybridMatches = rerankHybridMatches self.xTypesenseApiKey = xTypesenseApiKey + self.rerankHybridMatches = rerankHybridMatches } public enum CodingKeys: String, CodingKey, CaseIterable { - case cacheTtl = "cache_ttl" - case conversation - case conversationId = "conversation_id" - case conversationModelId = "conversation_model_id" - case dropTokensMode = "drop_tokens_mode" - case dropTokensThreshold = "drop_tokens_threshold" - case enableAnalytics = "enable_analytics" - case enableOverrides = "enable_overrides" - case enableSynonyms = "enable_synonyms" - case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" - case enableTyposForNumericalTokens = "enable_typos_for_numerical_tokens" - case excludeFields = "exclude_fields" - case exhaustiveSearch = "exhaustive_search" - case facetBy = "facet_by" - case facetQuery = "facet_query" - case facetReturnParent = "facet_return_parent" - case facetStrategy = "facet_strategy" - case filterBy = "filter_by" - case filterCuratedHits = "filter_curated_hits" - case groupBy = "group_by" - case groupLimit = "group_limit" - case groupMissingValues = "group_missing_values" - case hiddenHits = "hidden_hits" - case highlightAffixNumTokens = "highlight_affix_num_tokens" - case highlightEndTag = "highlight_end_tag" - case highlightFields = "highlight_fields" - case highlightFullFields = "highlight_full_fields" - case highlightStartTag = "highlight_start_tag" - case includeFields = "include_fields" + case q + case queryBy = "query_by" + case queryByWeights = "query_by_weights" + case textMatchType = "text_match_type" + case _prefix = "prefix" case _infix = "infix" - case limit case maxExtraPrefix = "max_extra_prefix" case maxExtraSuffix = "max_extra_suffix" + case filterBy = "filter_by" + case sortBy = "sort_by" + case facetBy = "facet_by" case maxFacetValues = "max_facet_values" - case minLen1typo = "min_len_1typo" - case minLen2typo = "min_len_2typo" + case facetQuery = "facet_query" case numTypos = "num_typos" - case offset - case overrideTags = "override_tags" case page case perPage = "per_page" + case limit + case offset + case groupBy = "group_by" + case groupLimit = "group_limit" + case groupMissingValues = "group_missing_values" + case includeFields = "include_fields" + case excludeFields = "exclude_fields" + case highlightFullFields = "highlight_full_fields" + case highlightAffixNumTokens = "highlight_affix_num_tokens" + case highlightStartTag = "highlight_start_tag" + case highlightEndTag = "highlight_end_tag" + case snippetThreshold = "snippet_threshold" + case dropTokensThreshold = "drop_tokens_threshold" + case dropTokensMode = "drop_tokens_mode" + case typoTokensThreshold = "typo_tokens_threshold" + case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" + case filterCuratedHits = "filter_curated_hits" + case enableSynonyms = "enable_synonyms" + case enableAnalytics = "enable_analytics" + case synonymPrefix = "synonym_prefix" + case synonymNumTypos = "synonym_num_typos" case pinnedHits = "pinned_hits" + case hiddenHits = "hidden_hits" + case overrideTags = "override_tags" + case highlightFields = "highlight_fields" case preSegmentedQuery = "pre_segmented_query" - case _prefix = "prefix" case preset + case enableOverrides = "enable_overrides" case prioritizeExactMatch = "prioritize_exact_match" - case prioritizeNumMatchingFields = "prioritize_num_matching_fields" case prioritizeTokenPosition = "prioritize_token_position" - case q - case queryBy = "query_by" - case queryByWeights = "query_by_weights" - case remoteEmbeddingNumTries = "remote_embedding_num_tries" - case remoteEmbeddingTimeoutMs = "remote_embedding_timeout_ms" + case prioritizeNumMatchingFields = "prioritize_num_matching_fields" + case enableTyposForNumericalTokens = "enable_typos_for_numerical_tokens" + case exhaustiveSearch = "exhaustive_search" case searchCutoffMs = "search_cutoff_ms" - case snippetThreshold = "snippet_threshold" - case sortBy = "sort_by" - case stopwords - case synonymNumTypos = "synonym_num_typos" - case synonymPrefix = "synonym_prefix" - case textMatchType = "text_match_type" - case typoTokensThreshold = "typo_tokens_threshold" case useCache = "use_cache" + case cacheTtl = "cache_ttl" + case minLen1typo = "min_len_1typo" + case minLen2typo = "min_len_2typo" case vectorQuery = "vector_query" + case remoteEmbeddingTimeoutMs = "remote_embedding_timeout_ms" + case remoteEmbeddingNumTries = "remote_embedding_num_tries" + case facetStrategy = "facet_strategy" + case stopwords + case facetReturnParent = "facet_return_parent" case voiceQuery = "voice_query" + case conversation + case conversationModelId = "conversation_model_id" + case conversationId = "conversation_id" case collection - case rerankHybridMatches = "rerank_hybrid_matches" case xTypesenseApiKey = "x-typesense-api-key" + case rerankHybridMatches = "rerank_hybrid_matches" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) - try container.encodeIfPresent(conversation, forKey: .conversation) - try container.encodeIfPresent(conversationId, forKey: .conversationId) - try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) - try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) - try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) - try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) - try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) - try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) - try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) - try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) - try container.encodeIfPresent(excludeFields, forKey: .excludeFields) - try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) - try container.encodeIfPresent(facetBy, forKey: .facetBy) - try container.encodeIfPresent(facetQuery, forKey: .facetQuery) - try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) - try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) - try container.encodeIfPresent(filterBy, forKey: .filterBy) - try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) - try container.encodeIfPresent(groupBy, forKey: .groupBy) - try container.encodeIfPresent(groupLimit, forKey: .groupLimit) - try container.encodeIfPresent(groupMissingValues, forKey: .groupMissingValues) - try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) - try container.encodeIfPresent(highlightAffixNumTokens, forKey: .highlightAffixNumTokens) - try container.encodeIfPresent(highlightEndTag, forKey: .highlightEndTag) - try container.encodeIfPresent(highlightFields, forKey: .highlightFields) - try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) - try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) - try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(q, forKey: .q) + try container.encodeIfPresent(queryBy, forKey: .queryBy) + try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) + try container.encodeIfPresent(textMatchType, forKey: .textMatchType) + try container.encodeIfPresent(_prefix, forKey: ._prefix) try container.encodeIfPresent(_infix, forKey: ._infix) - try container.encodeIfPresent(limit, forKey: .limit) try container.encodeIfPresent(maxExtraPrefix, forKey: .maxExtraPrefix) try container.encodeIfPresent(maxExtraSuffix, forKey: .maxExtraSuffix) + try container.encodeIfPresent(filterBy, forKey: .filterBy) + try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(facetBy, forKey: .facetBy) try container.encodeIfPresent(maxFacetValues, forKey: .maxFacetValues) - try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) - try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) + try container.encodeIfPresent(facetQuery, forKey: .facetQuery) try container.encodeIfPresent(numTypos, forKey: .numTypos) - try container.encodeIfPresent(offset, forKey: .offset) - try container.encodeIfPresent(overrideTags, forKey: .overrideTags) try container.encodeIfPresent(page, forKey: .page) try container.encodeIfPresent(perPage, forKey: .perPage) + try container.encodeIfPresent(limit, forKey: .limit) + try container.encodeIfPresent(offset, forKey: .offset) + try container.encodeIfPresent(groupBy, forKey: .groupBy) + try container.encodeIfPresent(groupLimit, forKey: .groupLimit) + try container.encodeIfPresent(groupMissingValues, forKey: .groupMissingValues) + try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(excludeFields, forKey: .excludeFields) + try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) + try container.encodeIfPresent(highlightAffixNumTokens, forKey: .highlightAffixNumTokens) + try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) + try container.encodeIfPresent(highlightEndTag, forKey: .highlightEndTag) + try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) + try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) + try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) + try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) + try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) + try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) + try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) + try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) + try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) try container.encodeIfPresent(pinnedHits, forKey: .pinnedHits) + try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) + try container.encodeIfPresent(overrideTags, forKey: .overrideTags) + try container.encodeIfPresent(highlightFields, forKey: .highlightFields) try container.encodeIfPresent(preSegmentedQuery, forKey: .preSegmentedQuery) - try container.encodeIfPresent(_prefix, forKey: ._prefix) try container.encodeIfPresent(preset, forKey: .preset) + try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) try container.encodeIfPresent(prioritizeExactMatch, forKey: .prioritizeExactMatch) - try container.encodeIfPresent(prioritizeNumMatchingFields, forKey: .prioritizeNumMatchingFields) try container.encodeIfPresent(prioritizeTokenPosition, forKey: .prioritizeTokenPosition) - try container.encodeIfPresent(q, forKey: .q) - try container.encodeIfPresent(queryBy, forKey: .queryBy) - try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) - try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) - try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) + try container.encodeIfPresent(prioritizeNumMatchingFields, forKey: .prioritizeNumMatchingFields) + try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) + try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) try container.encodeIfPresent(searchCutoffMs, forKey: .searchCutoffMs) - try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) - try container.encodeIfPresent(sortBy, forKey: .sortBy) - try container.encodeIfPresent(stopwords, forKey: .stopwords) - try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) - try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) - try container.encodeIfPresent(textMatchType, forKey: .textMatchType) - try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) try container.encodeIfPresent(useCache, forKey: .useCache) + try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) + try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) + try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) try container.encodeIfPresent(vectorQuery, forKey: .vectorQuery) + try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) + try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) + try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) + try container.encodeIfPresent(stopwords, forKey: .stopwords) + try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) + try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) + try container.encodeIfPresent(conversationId, forKey: .conversationId) try container.encodeIfPresent(collection, forKey: .collection) - try container.encodeIfPresent(rerankHybridMatches, forKey: .rerankHybridMatches) try container.encodeIfPresent(xTypesenseApiKey, forKey: .xTypesenseApiKey) + try container.encodeIfPresent(rerankHybridMatches, forKey: .rerankHybridMatches) } } diff --git a/Sources/Typesense/Models/MultiSearchParameters.swift b/Sources/Typesense/Models/MultiSearchParameters.swift index 29b26ae..94747f7 100644 --- a/Sources/Typesense/Models/MultiSearchParameters.swift +++ b/Sources/Typesense/Models/MultiSearchParameters.swift @@ -13,335 +13,335 @@ import AnyCodable /** Parameters for the multi search API. */ public struct MultiSearchParameters: Codable { - /** 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. */ - public var cacheTtl: Int? - /** Enable conversational search. */ - public var conversation: Bool? - /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ - public var conversationId: String? - /** The Id of Conversation Model to be used. */ - public var conversationModelId: String? - public var dropTokensMode: DropTokensMode? - /** 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 */ - public var dropTokensThreshold: Int? - /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ - public var enableAnalytics: Bool? = true - /** 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 */ - public var enableOverrides: Bool? = false - /** 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 */ - public var enableSynonyms: Bool? - /** Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. */ - public var enableTyposForAlphaNumericalTokens: Bool? - /** Make Typesense disable typos for numerical tokens. */ - public var enableTyposForNumericalTokens: Bool? = true - /** List of fields from the document to exclude in the search result */ - public var excludeFields: String? - /** 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). */ - public var exhaustiveSearch: Bool? - /** A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. */ - public var facetBy: String? - /** 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\". */ - public var facetQuery: String? - /** Comma separated string of nested facet fields whose parent object should be returned in facet response. */ - public var facetReturnParent: String? - /** Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). */ - public var facetStrategy: String? - /** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */ - public var filterBy: String? - /** Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false */ - public var filterCuratedHits: Bool? - /** 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. */ - public var groupBy: String? - /** 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 */ - public var groupLimit: Int? - /** 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 */ - public var groupMissingValues: Bool? - /** 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`. */ - public var hiddenHits: String? - /** The number of tokens that should surround the highlighted text on each side. Default: 4 */ - public var highlightAffixNumTokens: Int? - /** The end tag used for the highlighted snippets. Default: `` */ - public var highlightEndTag: String? - /** A list of custom fields that must be highlighted even if you don't query for them */ - public var highlightFields: String? - /** List of fields which should be highlighted fully without snippeting */ - public var highlightFullFields: String? - /** The start tag used for the highlighted snippets. Default: `` */ - public var highlightStartTag: String? - /** List of fields from the document to include in the search result */ - public var includeFields: 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. */ + public var q: String? + /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ + public var queryBy: 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. */ + public var queryByWeights: 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. */ + public var textMatchType: 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. */ + public var _prefix: String? /** 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 */ public var _infix: String? - /** Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. */ - public var limit: Int? /** 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. */ public var maxExtraPrefix: Int? /** 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. */ public var maxExtraSuffix: Int? + /** Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. */ + public var filterBy: 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` */ + public var sortBy: String? + /** A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. */ + public var facetBy: String? /** Maximum number of facet values to be returned. */ public var maxFacetValues: Int? - /** Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ - public var minLen1typo: Int? - /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ - public var minLen2typo: Int? + /** 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\". */ + public var facetQuery: String? /** The number of typographical errors (1 or 2) that would be tolerated. Default: 2 */ public var numTypos: String? - /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ - public var offset: Int? - /** Comma separated list of tags to trigger the curations rules that match the tags. */ - public var overrideTags: String? /** Results from this specific page number would be fetched. */ public var page: Int? /** Number of results to fetch per page. Default: 10 */ public var perPage: Int? + /** Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. */ + public var limit: Int? + /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ + public var offset: Int? + /** 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. */ + public var groupBy: String? + /** 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 */ + public var groupLimit: Int? + /** 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 */ + public var groupMissingValues: Bool? + /** List of fields from the document to include in the search result */ + public var includeFields: String? + /** List of fields from the document to exclude in the search result */ + public var excludeFields: String? + /** List of fields which should be highlighted fully without snippeting */ + public var highlightFullFields: String? + /** The number of tokens that should surround the highlighted text on each side. Default: 4 */ + public var highlightAffixNumTokens: Int? + /** The start tag used for the highlighted snippets. Default: `` */ + public var highlightStartTag: String? + /** The end tag used for the highlighted snippets. Default: `` */ + public var highlightEndTag: String? + /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ + public var snippetThreshold: Int? + /** 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 */ + public var dropTokensThreshold: Int? + public var dropTokensMode: DropTokensMode? + /** 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 */ + public var typoTokensThreshold: Int? + /** Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. */ + public var enableTyposForAlphaNumericalTokens: 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 */ + public var filterCuratedHits: 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 */ + public var enableSynonyms: Bool? + /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ + public var enableAnalytics: Bool? = true + /** Allow synonym resolution on word prefixes in the query. Default: false */ + public var synonymPrefix: Bool? + /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ + public var synonymNumTypos: Int? /** 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`. */ public var pinnedHits: 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`. */ + public var hiddenHits: String? + /** Comma separated list of tags to trigger the curations rules that match the tags. */ + public var overrideTags: String? + /** A list of custom fields that must be highlighted even if you don't query for them */ + public var highlightFields: String? /** 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 */ public var preSegmentedQuery: Bool? = false - /** 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. */ - public var _prefix: String? /** Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. */ public var preset: String? + /** 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 */ + public var enableOverrides: Bool? = false /** Set this parameter to true to ensure that an exact match is ranked above the others */ public var prioritizeExactMatch: Bool? = true - /** Make Typesense prioritize documents where the query words appear in more number of fields. */ - public var prioritizeNumMatchingFields: Bool? = true /** Make Typesense prioritize documents where the query words appear earlier in the text. */ public var prioritizeTokenPosition: Bool? = false - /** 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. */ - public var q: String? - /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ - public var queryBy: 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. */ - public var queryByWeights: String? - /** Number of times to retry fetching remote embeddings. */ - public var remoteEmbeddingNumTries: Int? - /** Timeout (in milliseconds) for fetching remote embeddings. */ - public var remoteEmbeddingTimeoutMs: Int? + /** Make Typesense prioritize documents where the query words appear in more number of fields. */ + public var prioritizeNumMatchingFields: Bool? = true + /** Make Typesense disable typos for numerical tokens. */ + public var enableTyposForNumericalTokens: Bool? = true + /** 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). */ + public var exhaustiveSearch: Bool? /** 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. */ public var searchCutoffMs: Int? - /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ - public var snippetThreshold: Int? - /** 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` */ - public var sortBy: String? - /** Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. */ - public var stopwords: String? - /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ - public var synonymNumTypos: Int? - /** Allow synonym resolution on word prefixes in the query. Default: false */ - public var synonymPrefix: Bool? - /** 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. */ - public var textMatchType: String? - /** 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 */ - public var typoTokensThreshold: Int? /** Enable server side caching of search query results. By default, caching is disabled. */ public var useCache: Bool? + /** 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. */ + public var cacheTtl: Int? + /** Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ + public var minLen1typo: Int? + /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ + public var minLen2typo: Int? /** Vector query expression for fetching documents \"closest\" to a given query/document vector. */ public var vectorQuery: String? + /** Timeout (in milliseconds) for fetching remote embeddings. */ + public var remoteEmbeddingTimeoutMs: Int? + /** Number of times to retry fetching remote embeddings. */ + public var remoteEmbeddingNumTries: Int? + /** Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). */ + public var facetStrategy: String? + /** Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. */ + public var stopwords: String? + /** Comma separated string of nested facet fields whose parent object should be returned in facet response. */ + public var facetReturnParent: String? /** The base64 encoded audio file in 16 khz 16-bit WAV format. */ public var voiceQuery: String? + /** Enable conversational search. */ + public var conversation: Bool? + /** The Id of Conversation Model to be used. */ + public var conversationModelId: String? + /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ + public var conversationId: String? - public init(cacheTtl: Int? = nil, conversation: Bool? = nil, conversationId: String? = nil, conversationModelId: String? = nil, dropTokensMode: DropTokensMode? = nil, dropTokensThreshold: Int? = nil, enableAnalytics: Bool? = true, enableOverrides: Bool? = false, enableSynonyms: Bool? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, enableTyposForNumericalTokens: Bool? = true, excludeFields: String? = nil, exhaustiveSearch: Bool? = nil, facetBy: String? = nil, facetQuery: String? = nil, facetReturnParent: String? = nil, facetStrategy: String? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, hiddenHits: String? = nil, highlightAffixNumTokens: Int? = nil, highlightEndTag: String? = nil, highlightFields: String? = nil, highlightFullFields: String? = nil, highlightStartTag: String? = nil, includeFields: String? = nil, _infix: String? = nil, limit: Int? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, maxFacetValues: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, numTypos: String? = nil, offset: Int? = nil, overrideTags: String? = nil, page: Int? = nil, perPage: Int? = nil, pinnedHits: String? = nil, preSegmentedQuery: Bool? = false, _prefix: String? = nil, preset: String? = nil, prioritizeExactMatch: Bool? = true, prioritizeNumMatchingFields: Bool? = true, prioritizeTokenPosition: Bool? = false, q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, remoteEmbeddingNumTries: Int? = nil, remoteEmbeddingTimeoutMs: Int? = nil, searchCutoffMs: Int? = nil, snippetThreshold: Int? = nil, sortBy: String? = nil, stopwords: String? = nil, synonymNumTypos: Int? = nil, synonymPrefix: Bool? = nil, textMatchType: String? = nil, typoTokensThreshold: Int? = nil, useCache: Bool? = nil, vectorQuery: String? = nil, voiceQuery: String? = nil) { - self.cacheTtl = cacheTtl - self.conversation = conversation - self.conversationId = conversationId - self.conversationModelId = conversationModelId - self.dropTokensMode = dropTokensMode - self.dropTokensThreshold = dropTokensThreshold - self.enableAnalytics = enableAnalytics - self.enableOverrides = enableOverrides - self.enableSynonyms = enableSynonyms - self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens - self.enableTyposForNumericalTokens = enableTyposForNumericalTokens - self.excludeFields = excludeFields - self.exhaustiveSearch = exhaustiveSearch - self.facetBy = facetBy - self.facetQuery = facetQuery - self.facetReturnParent = facetReturnParent - self.facetStrategy = facetStrategy - self.filterBy = filterBy - self.filterCuratedHits = filterCuratedHits - self.groupBy = groupBy - self.groupLimit = groupLimit - self.groupMissingValues = groupMissingValues - self.hiddenHits = hiddenHits - self.highlightAffixNumTokens = highlightAffixNumTokens - self.highlightEndTag = highlightEndTag - self.highlightFields = highlightFields - self.highlightFullFields = highlightFullFields - self.highlightStartTag = highlightStartTag - self.includeFields = includeFields + public init(q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, textMatchType: String? = nil, _prefix: String? = nil, _infix: String? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, filterBy: String? = nil, sortBy: String? = nil, facetBy: String? = nil, maxFacetValues: Int? = nil, facetQuery: String? = nil, numTypos: String? = nil, page: Int? = nil, perPage: Int? = nil, limit: Int? = nil, offset: Int? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, includeFields: String? = nil, excludeFields: String? = nil, highlightFullFields: String? = nil, highlightAffixNumTokens: Int? = nil, highlightStartTag: String? = nil, highlightEndTag: String? = nil, snippetThreshold: Int? = nil, dropTokensThreshold: Int? = nil, dropTokensMode: DropTokensMode? = nil, typoTokensThreshold: Int? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, filterCuratedHits: Bool? = nil, enableSynonyms: Bool? = nil, enableAnalytics: Bool? = true, synonymPrefix: Bool? = nil, synonymNumTypos: Int? = nil, pinnedHits: String? = nil, hiddenHits: String? = nil, overrideTags: String? = nil, highlightFields: String? = nil, preSegmentedQuery: Bool? = false, preset: String? = nil, enableOverrides: Bool? = false, prioritizeExactMatch: Bool? = true, prioritizeTokenPosition: Bool? = false, prioritizeNumMatchingFields: Bool? = true, enableTyposForNumericalTokens: Bool? = true, exhaustiveSearch: Bool? = nil, searchCutoffMs: Int? = nil, useCache: Bool? = nil, cacheTtl: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, vectorQuery: String? = nil, remoteEmbeddingTimeoutMs: Int? = nil, remoteEmbeddingNumTries: Int? = nil, facetStrategy: String? = nil, stopwords: String? = nil, facetReturnParent: String? = nil, voiceQuery: String? = nil, conversation: Bool? = nil, conversationModelId: String? = nil, conversationId: String? = nil) { + self.q = q + self.queryBy = queryBy + self.queryByWeights = queryByWeights + self.textMatchType = textMatchType + self._prefix = _prefix self._infix = _infix - self.limit = limit self.maxExtraPrefix = maxExtraPrefix self.maxExtraSuffix = maxExtraSuffix + self.filterBy = filterBy + self.sortBy = sortBy + self.facetBy = facetBy self.maxFacetValues = maxFacetValues - self.minLen1typo = minLen1typo - self.minLen2typo = minLen2typo + self.facetQuery = facetQuery self.numTypos = numTypos - self.offset = offset - self.overrideTags = overrideTags self.page = page self.perPage = perPage + self.limit = limit + self.offset = offset + self.groupBy = groupBy + self.groupLimit = groupLimit + self.groupMissingValues = groupMissingValues + self.includeFields = includeFields + self.excludeFields = excludeFields + self.highlightFullFields = highlightFullFields + self.highlightAffixNumTokens = highlightAffixNumTokens + self.highlightStartTag = highlightStartTag + self.highlightEndTag = highlightEndTag + self.snippetThreshold = snippetThreshold + self.dropTokensThreshold = dropTokensThreshold + self.dropTokensMode = dropTokensMode + self.typoTokensThreshold = typoTokensThreshold + self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens + self.filterCuratedHits = filterCuratedHits + self.enableSynonyms = enableSynonyms + self.enableAnalytics = enableAnalytics + self.synonymPrefix = synonymPrefix + self.synonymNumTypos = synonymNumTypos self.pinnedHits = pinnedHits + self.hiddenHits = hiddenHits + self.overrideTags = overrideTags + self.highlightFields = highlightFields self.preSegmentedQuery = preSegmentedQuery - self._prefix = _prefix self.preset = preset + self.enableOverrides = enableOverrides self.prioritizeExactMatch = prioritizeExactMatch - self.prioritizeNumMatchingFields = prioritizeNumMatchingFields self.prioritizeTokenPosition = prioritizeTokenPosition - self.q = q - self.queryBy = queryBy - self.queryByWeights = queryByWeights - self.remoteEmbeddingNumTries = remoteEmbeddingNumTries - self.remoteEmbeddingTimeoutMs = remoteEmbeddingTimeoutMs + self.prioritizeNumMatchingFields = prioritizeNumMatchingFields + self.enableTyposForNumericalTokens = enableTyposForNumericalTokens + self.exhaustiveSearch = exhaustiveSearch self.searchCutoffMs = searchCutoffMs - self.snippetThreshold = snippetThreshold - self.sortBy = sortBy - self.stopwords = stopwords - self.synonymNumTypos = synonymNumTypos - self.synonymPrefix = synonymPrefix - self.textMatchType = textMatchType - self.typoTokensThreshold = typoTokensThreshold self.useCache = useCache + self.cacheTtl = cacheTtl + self.minLen1typo = minLen1typo + self.minLen2typo = minLen2typo self.vectorQuery = vectorQuery + self.remoteEmbeddingTimeoutMs = remoteEmbeddingTimeoutMs + self.remoteEmbeddingNumTries = remoteEmbeddingNumTries + self.facetStrategy = facetStrategy + self.stopwords = stopwords + self.facetReturnParent = facetReturnParent self.voiceQuery = voiceQuery + self.conversation = conversation + self.conversationModelId = conversationModelId + self.conversationId = conversationId } public enum CodingKeys: String, CodingKey, CaseIterable { - case cacheTtl = "cache_ttl" - case conversation - case conversationId = "conversation_id" - case conversationModelId = "conversation_model_id" - case dropTokensMode = "drop_tokens_mode" - case dropTokensThreshold = "drop_tokens_threshold" - case enableAnalytics = "enable_analytics" - case enableOverrides = "enable_overrides" - case enableSynonyms = "enable_synonyms" - case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" - case enableTyposForNumericalTokens = "enable_typos_for_numerical_tokens" - case excludeFields = "exclude_fields" - case exhaustiveSearch = "exhaustive_search" - case facetBy = "facet_by" - case facetQuery = "facet_query" - case facetReturnParent = "facet_return_parent" - case facetStrategy = "facet_strategy" - case filterBy = "filter_by" - case filterCuratedHits = "filter_curated_hits" - case groupBy = "group_by" - case groupLimit = "group_limit" - case groupMissingValues = "group_missing_values" - case hiddenHits = "hidden_hits" - case highlightAffixNumTokens = "highlight_affix_num_tokens" - case highlightEndTag = "highlight_end_tag" - case highlightFields = "highlight_fields" - case highlightFullFields = "highlight_full_fields" - case highlightStartTag = "highlight_start_tag" - case includeFields = "include_fields" + case q + case queryBy = "query_by" + case queryByWeights = "query_by_weights" + case textMatchType = "text_match_type" + case _prefix = "prefix" case _infix = "infix" - case limit case maxExtraPrefix = "max_extra_prefix" case maxExtraSuffix = "max_extra_suffix" + case filterBy = "filter_by" + case sortBy = "sort_by" + case facetBy = "facet_by" case maxFacetValues = "max_facet_values" - case minLen1typo = "min_len_1typo" - case minLen2typo = "min_len_2typo" + case facetQuery = "facet_query" case numTypos = "num_typos" - case offset - case overrideTags = "override_tags" case page case perPage = "per_page" + case limit + case offset + case groupBy = "group_by" + case groupLimit = "group_limit" + case groupMissingValues = "group_missing_values" + case includeFields = "include_fields" + case excludeFields = "exclude_fields" + case highlightFullFields = "highlight_full_fields" + case highlightAffixNumTokens = "highlight_affix_num_tokens" + case highlightStartTag = "highlight_start_tag" + case highlightEndTag = "highlight_end_tag" + case snippetThreshold = "snippet_threshold" + case dropTokensThreshold = "drop_tokens_threshold" + case dropTokensMode = "drop_tokens_mode" + case typoTokensThreshold = "typo_tokens_threshold" + case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" + case filterCuratedHits = "filter_curated_hits" + case enableSynonyms = "enable_synonyms" + case enableAnalytics = "enable_analytics" + case synonymPrefix = "synonym_prefix" + case synonymNumTypos = "synonym_num_typos" case pinnedHits = "pinned_hits" + case hiddenHits = "hidden_hits" + case overrideTags = "override_tags" + case highlightFields = "highlight_fields" case preSegmentedQuery = "pre_segmented_query" - case _prefix = "prefix" case preset + case enableOverrides = "enable_overrides" case prioritizeExactMatch = "prioritize_exact_match" - case prioritizeNumMatchingFields = "prioritize_num_matching_fields" case prioritizeTokenPosition = "prioritize_token_position" - case q - case queryBy = "query_by" - case queryByWeights = "query_by_weights" - case remoteEmbeddingNumTries = "remote_embedding_num_tries" - case remoteEmbeddingTimeoutMs = "remote_embedding_timeout_ms" + case prioritizeNumMatchingFields = "prioritize_num_matching_fields" + case enableTyposForNumericalTokens = "enable_typos_for_numerical_tokens" + case exhaustiveSearch = "exhaustive_search" case searchCutoffMs = "search_cutoff_ms" - case snippetThreshold = "snippet_threshold" - case sortBy = "sort_by" - case stopwords - case synonymNumTypos = "synonym_num_typos" - case synonymPrefix = "synonym_prefix" - case textMatchType = "text_match_type" - case typoTokensThreshold = "typo_tokens_threshold" case useCache = "use_cache" + case cacheTtl = "cache_ttl" + case minLen1typo = "min_len_1typo" + case minLen2typo = "min_len_2typo" case vectorQuery = "vector_query" + case remoteEmbeddingTimeoutMs = "remote_embedding_timeout_ms" + case remoteEmbeddingNumTries = "remote_embedding_num_tries" + case facetStrategy = "facet_strategy" + case stopwords + case facetReturnParent = "facet_return_parent" case voiceQuery = "voice_query" + case conversation + case conversationModelId = "conversation_model_id" + case conversationId = "conversation_id" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) - try container.encodeIfPresent(conversation, forKey: .conversation) - try container.encodeIfPresent(conversationId, forKey: .conversationId) - try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) - try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) - try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) - try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) - try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) - try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) - try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) - try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) - try container.encodeIfPresent(excludeFields, forKey: .excludeFields) - try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) - try container.encodeIfPresent(facetBy, forKey: .facetBy) - try container.encodeIfPresent(facetQuery, forKey: .facetQuery) - try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) - try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) - try container.encodeIfPresent(filterBy, forKey: .filterBy) - try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) - try container.encodeIfPresent(groupBy, forKey: .groupBy) - try container.encodeIfPresent(groupLimit, forKey: .groupLimit) - try container.encodeIfPresent(groupMissingValues, forKey: .groupMissingValues) - try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) - try container.encodeIfPresent(highlightAffixNumTokens, forKey: .highlightAffixNumTokens) - try container.encodeIfPresent(highlightEndTag, forKey: .highlightEndTag) - try container.encodeIfPresent(highlightFields, forKey: .highlightFields) - try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) - try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) - try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(q, forKey: .q) + try container.encodeIfPresent(queryBy, forKey: .queryBy) + try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) + try container.encodeIfPresent(textMatchType, forKey: .textMatchType) + try container.encodeIfPresent(_prefix, forKey: ._prefix) try container.encodeIfPresent(_infix, forKey: ._infix) - try container.encodeIfPresent(limit, forKey: .limit) try container.encodeIfPresent(maxExtraPrefix, forKey: .maxExtraPrefix) try container.encodeIfPresent(maxExtraSuffix, forKey: .maxExtraSuffix) + try container.encodeIfPresent(filterBy, forKey: .filterBy) + try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(facetBy, forKey: .facetBy) try container.encodeIfPresent(maxFacetValues, forKey: .maxFacetValues) - try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) - try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) + try container.encodeIfPresent(facetQuery, forKey: .facetQuery) try container.encodeIfPresent(numTypos, forKey: .numTypos) - try container.encodeIfPresent(offset, forKey: .offset) - try container.encodeIfPresent(overrideTags, forKey: .overrideTags) try container.encodeIfPresent(page, forKey: .page) try container.encodeIfPresent(perPage, forKey: .perPage) + try container.encodeIfPresent(limit, forKey: .limit) + try container.encodeIfPresent(offset, forKey: .offset) + try container.encodeIfPresent(groupBy, forKey: .groupBy) + try container.encodeIfPresent(groupLimit, forKey: .groupLimit) + try container.encodeIfPresent(groupMissingValues, forKey: .groupMissingValues) + try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(excludeFields, forKey: .excludeFields) + try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) + try container.encodeIfPresent(highlightAffixNumTokens, forKey: .highlightAffixNumTokens) + try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) + try container.encodeIfPresent(highlightEndTag, forKey: .highlightEndTag) + try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) + try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) + try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) + try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) + try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) + try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) + try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) + try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) + try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) try container.encodeIfPresent(pinnedHits, forKey: .pinnedHits) + try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) + try container.encodeIfPresent(overrideTags, forKey: .overrideTags) + try container.encodeIfPresent(highlightFields, forKey: .highlightFields) try container.encodeIfPresent(preSegmentedQuery, forKey: .preSegmentedQuery) - try container.encodeIfPresent(_prefix, forKey: ._prefix) try container.encodeIfPresent(preset, forKey: .preset) + try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) try container.encodeIfPresent(prioritizeExactMatch, forKey: .prioritizeExactMatch) - try container.encodeIfPresent(prioritizeNumMatchingFields, forKey: .prioritizeNumMatchingFields) try container.encodeIfPresent(prioritizeTokenPosition, forKey: .prioritizeTokenPosition) - try container.encodeIfPresent(q, forKey: .q) - try container.encodeIfPresent(queryBy, forKey: .queryBy) - try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) - try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) - try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) + try container.encodeIfPresent(prioritizeNumMatchingFields, forKey: .prioritizeNumMatchingFields) + try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) + try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) try container.encodeIfPresent(searchCutoffMs, forKey: .searchCutoffMs) - try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) - try container.encodeIfPresent(sortBy, forKey: .sortBy) - try container.encodeIfPresent(stopwords, forKey: .stopwords) - try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) - try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) - try container.encodeIfPresent(textMatchType, forKey: .textMatchType) - try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) try container.encodeIfPresent(useCache, forKey: .useCache) + try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) + try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) + try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) try container.encodeIfPresent(vectorQuery, forKey: .vectorQuery) + try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) + try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) + try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) + try container.encodeIfPresent(stopwords, forKey: .stopwords) + try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) + try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) + try container.encodeIfPresent(conversationId, forKey: .conversationId) } } diff --git a/Sources/Typesense/Models/MultiSearchResult.swift b/Sources/Typesense/Models/MultiSearchResult.swift index 1d8c445..b9452b7 100644 --- a/Sources/Typesense/Models/MultiSearchResult.swift +++ b/Sources/Typesense/Models/MultiSearchResult.swift @@ -12,24 +12,24 @@ import AnyCodable public struct MultiSearchResult: Codable { - public var conversation: SearchResultConversation? public var results: [MultiSearchResultItem] + public var conversation: SearchResultConversation? public init(results: [MultiSearchResultItem], conversation: SearchResultConversation? = nil) { - self.conversation = conversation self.results = results + self.conversation = conversation } public enum CodingKeys: String, CodingKey, CaseIterable { - case conversation case results + case conversation } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(conversation, forKey: .conversation) try container.encode(results, forKey: .results) + try container.encodeIfPresent(conversation, forKey: .conversation) } } diff --git a/Sources/Typesense/Models/MultiSearchResultItem.swift b/Sources/Typesense/Models/MultiSearchResultItem.swift index e58b13d..cce397b 100644 --- a/Sources/Typesense/Models/MultiSearchResultItem.swift +++ b/Sources/Typesense/Models/MultiSearchResultItem.swift @@ -12,64 +12,64 @@ import AnyCodable public struct MultiSearchResultItem: Codable { - public var conversation: SearchResultConversation? public var facetCounts: [FacetCounts]? /** The number of documents found */ public var found: Int? public var foundDocs: Int? - public var groupedHits: [SearchGroupedHit]? - /** The documents that matched the search query */ - public var hits: [SearchResultHit]? - /** Custom JSON object that can be returned in the search response */ - public var metadata: [String: AnyCodable]? + /** The number of milliseconds the search took */ + public var searchTimeMs: Int? /** The total number of documents in the collection */ public var outOf: Int? + /** Whether the search was cut off */ + public var searchCutoff: Bool? /** The search result page number */ public var page: Int? + public var groupedHits: [SearchGroupedHit]? + /** The documents that matched the search query */ + public var hits: [SearchResultHit]? public var requestParams: SearchRequestParams? - /** Whether the search was cut off */ - public var searchCutoff: Bool? - /** The number of milliseconds the search took */ - public var searchTimeMs: Int? + public var conversation: SearchResultConversation? /** Returned only for union query response. */ public var unionRequestParams: [SearchRequestParams]? + /** Custom JSON object that can be returned in the search response */ + public var metadata: [String: AnyCodable]? /** HTTP error code */ public var code: Int64? /** Error description */ public var error: String? - public init(conversation: SearchResultConversation? = nil, facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, metadata: [String: AnyCodable]? = nil, outOf: Int? = nil, page: Int? = nil, requestParams: SearchRequestParams? = nil, searchCutoff: Bool? = nil, searchTimeMs: Int? = nil, unionRequestParams: [SearchRequestParams]? = nil, code: Int64? = nil, error: String? = nil) { - self.conversation = conversation + public init(facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, searchTimeMs: Int? = nil, outOf: Int? = nil, searchCutoff: Bool? = nil, page: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, requestParams: SearchRequestParams? = nil, conversation: SearchResultConversation? = nil, unionRequestParams: [SearchRequestParams]? = nil, metadata: [String: AnyCodable]? = nil, code: Int64? = nil, error: String? = nil) { self.facetCounts = facetCounts self.found = found self.foundDocs = foundDocs - self.groupedHits = groupedHits - self.hits = hits - self.metadata = metadata + self.searchTimeMs = searchTimeMs self.outOf = outOf + self.searchCutoff = searchCutoff self.page = page + self.groupedHits = groupedHits + self.hits = hits self.requestParams = requestParams - self.searchCutoff = searchCutoff - self.searchTimeMs = searchTimeMs + self.conversation = conversation self.unionRequestParams = unionRequestParams + self.metadata = metadata self.code = code self.error = error } public enum CodingKeys: String, CodingKey, CaseIterable { - case conversation case facetCounts = "facet_counts" case found case foundDocs = "found_docs" - case groupedHits = "grouped_hits" - case hits - case metadata + case searchTimeMs = "search_time_ms" case outOf = "out_of" + case searchCutoff = "search_cutoff" case page + case groupedHits = "grouped_hits" + case hits case requestParams = "request_params" - case searchCutoff = "search_cutoff" - case searchTimeMs = "search_time_ms" + case conversation case unionRequestParams = "union_request_params" + case metadata case code case error } @@ -78,19 +78,19 @@ public struct MultiSearchResultItem: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(conversation, forKey: .conversation) try container.encodeIfPresent(facetCounts, forKey: .facetCounts) try container.encodeIfPresent(found, forKey: .found) try container.encodeIfPresent(foundDocs, forKey: .foundDocs) - try container.encodeIfPresent(groupedHits, forKey: .groupedHits) - try container.encodeIfPresent(hits, forKey: .hits) - try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encodeIfPresent(searchTimeMs, forKey: .searchTimeMs) try container.encodeIfPresent(outOf, forKey: .outOf) + try container.encodeIfPresent(searchCutoff, forKey: .searchCutoff) try container.encodeIfPresent(page, forKey: .page) + try container.encodeIfPresent(groupedHits, forKey: .groupedHits) + try container.encodeIfPresent(hits, forKey: .hits) try container.encodeIfPresent(requestParams, forKey: .requestParams) - try container.encodeIfPresent(searchCutoff, forKey: .searchCutoff) - try container.encodeIfPresent(searchTimeMs, forKey: .searchTimeMs) + try container.encodeIfPresent(conversation, forKey: .conversation) try container.encodeIfPresent(unionRequestParams, forKey: .unionRequestParams) + try container.encodeIfPresent(metadata, forKey: .metadata) try container.encodeIfPresent(code, forKey: .code) try container.encodeIfPresent(error, forKey: .error) } diff --git a/Sources/Typesense/Models/MultiSearchSearchesParameter.swift b/Sources/Typesense/Models/MultiSearchSearchesParameter.swift index 7dca9a3..e4dc3d9 100644 --- a/Sources/Typesense/Models/MultiSearchSearchesParameter.swift +++ b/Sources/Typesense/Models/MultiSearchSearchesParameter.swift @@ -12,25 +12,25 @@ import AnyCodable public struct MultiSearchSearchesParameter: Codable { - public var searches: [MultiSearchCollectionParameters] /** When true, merges the search results from each search query into a single ordered set of hits. */ public var union: Bool? = false + public var searches: [MultiSearchCollectionParameters] public init(searches: [MultiSearchCollectionParameters], union: Bool? = false) { - self.searches = searches self.union = union + self.searches = searches } public enum CodingKeys: String, CodingKey, CaseIterable { - case searches case union + case searches } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(searches, forKey: .searches) try container.encodeIfPresent(union, forKey: .union) + try container.encode(searches, forKey: .searches) } } diff --git a/Sources/Typesense/Models/NLSearchModelBase.swift b/Sources/Typesense/Models/NLSearchModelBase.swift index 6af36c8..084446d 100644 --- a/Sources/Typesense/Models/NLSearchModelBase.swift +++ b/Sources/Typesense/Models/NLSearchModelBase.swift @@ -12,106 +12,106 @@ import AnyCodable public struct NLSearchModelBase: Codable { - /** Access token for GCP Vertex AI */ - public var accessToken: String? - /** Account ID for Cloudflare-specific models */ - public var accountId: String? + /** Name of the NL model to use */ + public var modelName: String? /** API key for the NL model service */ public var apiKey: String? /** Custom API URL for the NL model service */ public var apiUrl: String? - /** API version for the NL model service */ - public var apiVersion: String? - /** Client ID for GCP Vertex AI */ - public var clientId: String? - /** Client secret for GCP Vertex AI */ - public var clientSecret: String? /** Maximum number of bytes to process */ public var maxBytes: Int? - /** Maximum output tokens for GCP Vertex AI */ - public var maxOutputTokens: Int? - /** Name of the NL model to use */ - public var modelName: String? + /** Temperature parameter for the NL model */ + public var temperature: Double? + /** System prompt for the NL model */ + public var systemPrompt: String? + /** Top-p parameter for the NL model (Google-specific) */ + public var topP: Double? + /** Top-k parameter for the NL model (Google-specific) */ + public var topK: Int? + /** Stop sequences for the NL model (Google-specific) */ + public var stopSequences: [String]? + /** API version for the NL model service */ + public var apiVersion: String? /** Project ID for GCP Vertex AI */ public var projectId: String? + /** Access token for GCP Vertex AI */ + public var accessToken: String? /** Refresh token for GCP Vertex AI */ public var refreshToken: String? + /** Client ID for GCP Vertex AI */ + public var clientId: String? + /** Client secret for GCP Vertex AI */ + public var clientSecret: String? /** Region for GCP Vertex AI */ public var region: String? - /** Stop sequences for the NL model (Google-specific) */ - public var stopSequences: [String]? - /** System prompt for the NL model */ - public var systemPrompt: String? - /** Temperature parameter for the NL model */ - public var temperature: Double? - /** Top-k parameter for the NL model (Google-specific) */ - public var topK: Int? - /** Top-p parameter for the NL model (Google-specific) */ - public var topP: Double? + /** Maximum output tokens for GCP Vertex AI */ + public var maxOutputTokens: Int? + /** Account ID for Cloudflare-specific models */ + public var accountId: String? - public init(accessToken: String? = nil, accountId: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, apiVersion: String? = nil, clientId: String? = nil, clientSecret: String? = nil, maxBytes: Int? = nil, maxOutputTokens: Int? = nil, modelName: String? = nil, projectId: String? = nil, refreshToken: String? = nil, region: String? = nil, stopSequences: [String]? = nil, systemPrompt: String? = nil, temperature: Double? = nil, topK: Int? = nil, topP: Double? = nil) { - self.accessToken = accessToken - self.accountId = accountId + public init(modelName: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, maxBytes: Int? = nil, temperature: Double? = nil, systemPrompt: String? = nil, topP: Double? = nil, topK: Int? = nil, stopSequences: [String]? = nil, apiVersion: String? = nil, projectId: String? = nil, accessToken: String? = nil, refreshToken: String? = nil, clientId: String? = nil, clientSecret: String? = nil, region: String? = nil, maxOutputTokens: Int? = nil, accountId: String? = nil) { + self.modelName = modelName self.apiKey = apiKey self.apiUrl = apiUrl - self.apiVersion = apiVersion - self.clientId = clientId - self.clientSecret = clientSecret self.maxBytes = maxBytes - self.maxOutputTokens = maxOutputTokens - self.modelName = modelName + self.temperature = temperature + self.systemPrompt = systemPrompt + self.topP = topP + self.topK = topK + self.stopSequences = stopSequences + self.apiVersion = apiVersion self.projectId = projectId + self.accessToken = accessToken self.refreshToken = refreshToken + self.clientId = clientId + self.clientSecret = clientSecret self.region = region - self.stopSequences = stopSequences - self.systemPrompt = systemPrompt - self.temperature = temperature - self.topK = topK - self.topP = topP + self.maxOutputTokens = maxOutputTokens + self.accountId = accountId } public enum CodingKeys: String, CodingKey, CaseIterable { - case accessToken = "access_token" - case accountId = "account_id" + case modelName = "model_name" case apiKey = "api_key" case apiUrl = "api_url" - case apiVersion = "api_version" - case clientId = "client_id" - case clientSecret = "client_secret" case maxBytes = "max_bytes" - case maxOutputTokens = "max_output_tokens" - case modelName = "model_name" + case temperature + case systemPrompt = "system_prompt" + case topP = "top_p" + case topK = "top_k" + case stopSequences = "stop_sequences" + case apiVersion = "api_version" case projectId = "project_id" + case accessToken = "access_token" case refreshToken = "refresh_token" + case clientId = "client_id" + case clientSecret = "client_secret" case region - case stopSequences = "stop_sequences" - case systemPrompt = "system_prompt" - case temperature - case topK = "top_k" - case topP = "top_p" + case maxOutputTokens = "max_output_tokens" + case accountId = "account_id" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(accessToken, forKey: .accessToken) - try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encodeIfPresent(modelName, forKey: .modelName) try container.encodeIfPresent(apiKey, forKey: .apiKey) try container.encodeIfPresent(apiUrl, forKey: .apiUrl) - try container.encodeIfPresent(apiVersion, forKey: .apiVersion) - try container.encodeIfPresent(clientId, forKey: .clientId) - try container.encodeIfPresent(clientSecret, forKey: .clientSecret) try container.encodeIfPresent(maxBytes, forKey: .maxBytes) - try container.encodeIfPresent(maxOutputTokens, forKey: .maxOutputTokens) - try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(temperature, forKey: .temperature) + try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) + try container.encodeIfPresent(topP, forKey: .topP) + try container.encodeIfPresent(topK, forKey: .topK) + try container.encodeIfPresent(stopSequences, forKey: .stopSequences) + try container.encodeIfPresent(apiVersion, forKey: .apiVersion) try container.encodeIfPresent(projectId, forKey: .projectId) + try container.encodeIfPresent(accessToken, forKey: .accessToken) try container.encodeIfPresent(refreshToken, forKey: .refreshToken) + try container.encodeIfPresent(clientId, forKey: .clientId) + try container.encodeIfPresent(clientSecret, forKey: .clientSecret) try container.encodeIfPresent(region, forKey: .region) - try container.encodeIfPresent(stopSequences, forKey: .stopSequences) - try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) - try container.encodeIfPresent(temperature, forKey: .temperature) - try container.encodeIfPresent(topK, forKey: .topK) - try container.encodeIfPresent(topP, forKey: .topP) + try container.encodeIfPresent(maxOutputTokens, forKey: .maxOutputTokens) + try container.encodeIfPresent(accountId, forKey: .accountId) } } diff --git a/Sources/Typesense/Models/NLSearchModelCreateSchema.swift b/Sources/Typesense/Models/NLSearchModelCreateSchema.swift index ddb4db3..f36c105 100644 --- a/Sources/Typesense/Models/NLSearchModelCreateSchema.swift +++ b/Sources/Typesense/Models/NLSearchModelCreateSchema.swift @@ -12,86 +12,86 @@ import AnyCodable public struct NLSearchModelCreateSchema: Codable { - /** Access token for GCP Vertex AI */ - public var accessToken: String? - /** Account ID for Cloudflare-specific models */ - public var accountId: String? + /** Name of the NL model to use */ + public var modelName: String? /** API key for the NL model service */ public var apiKey: String? /** Custom API URL for the NL model service */ public var apiUrl: String? - /** API version for the NL model service */ - public var apiVersion: String? - /** Client ID for GCP Vertex AI */ - public var clientId: String? - /** Client secret for GCP Vertex AI */ - public var clientSecret: String? /** Maximum number of bytes to process */ public var maxBytes: Int? - /** Maximum output tokens for GCP Vertex AI */ - public var maxOutputTokens: Int? - /** Name of the NL model to use */ - public var modelName: String? + /** Temperature parameter for the NL model */ + public var temperature: Double? + /** System prompt for the NL model */ + public var systemPrompt: String? + /** Top-p parameter for the NL model (Google-specific) */ + public var topP: Double? + /** Top-k parameter for the NL model (Google-specific) */ + public var topK: Int? + /** Stop sequences for the NL model (Google-specific) */ + public var stopSequences: [String]? + /** API version for the NL model service */ + public var apiVersion: String? /** Project ID for GCP Vertex AI */ public var projectId: String? + /** Access token for GCP Vertex AI */ + public var accessToken: String? /** Refresh token for GCP Vertex AI */ public var refreshToken: String? + /** Client ID for GCP Vertex AI */ + public var clientId: String? + /** Client secret for GCP Vertex AI */ + public var clientSecret: String? /** Region for GCP Vertex AI */ public var region: String? - /** Stop sequences for the NL model (Google-specific) */ - public var stopSequences: [String]? - /** System prompt for the NL model */ - public var systemPrompt: String? - /** Temperature parameter for the NL model */ - public var temperature: Double? - /** Top-k parameter for the NL model (Google-specific) */ - public var topK: Int? - /** Top-p parameter for the NL model (Google-specific) */ - public var topP: Double? + /** Maximum output tokens for GCP Vertex AI */ + public var maxOutputTokens: Int? + /** Account ID for Cloudflare-specific models */ + public var accountId: String? /** Optional ID for the NL search model */ public var id: String? - public init(accessToken: String? = nil, accountId: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, apiVersion: String? = nil, clientId: String? = nil, clientSecret: String? = nil, maxBytes: Int? = nil, maxOutputTokens: Int? = nil, modelName: String? = nil, projectId: String? = nil, refreshToken: String? = nil, region: String? = nil, stopSequences: [String]? = nil, systemPrompt: String? = nil, temperature: Double? = nil, topK: Int? = nil, topP: Double? = nil, id: String? = nil) { - self.accessToken = accessToken - self.accountId = accountId + public init(modelName: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, maxBytes: Int? = nil, temperature: Double? = nil, systemPrompt: String? = nil, topP: Double? = nil, topK: Int? = nil, stopSequences: [String]? = nil, apiVersion: String? = nil, projectId: String? = nil, accessToken: String? = nil, refreshToken: String? = nil, clientId: String? = nil, clientSecret: String? = nil, region: String? = nil, maxOutputTokens: Int? = nil, accountId: String? = nil, id: String? = nil) { + self.modelName = modelName self.apiKey = apiKey self.apiUrl = apiUrl - self.apiVersion = apiVersion - self.clientId = clientId - self.clientSecret = clientSecret self.maxBytes = maxBytes - self.maxOutputTokens = maxOutputTokens - self.modelName = modelName + self.temperature = temperature + self.systemPrompt = systemPrompt + self.topP = topP + self.topK = topK + self.stopSequences = stopSequences + self.apiVersion = apiVersion self.projectId = projectId + self.accessToken = accessToken self.refreshToken = refreshToken + self.clientId = clientId + self.clientSecret = clientSecret self.region = region - self.stopSequences = stopSequences - self.systemPrompt = systemPrompt - self.temperature = temperature - self.topK = topK - self.topP = topP + self.maxOutputTokens = maxOutputTokens + self.accountId = accountId self.id = id } public enum CodingKeys: String, CodingKey, CaseIterable { - case accessToken = "access_token" - case accountId = "account_id" + case modelName = "model_name" case apiKey = "api_key" case apiUrl = "api_url" - case apiVersion = "api_version" - case clientId = "client_id" - case clientSecret = "client_secret" case maxBytes = "max_bytes" - case maxOutputTokens = "max_output_tokens" - case modelName = "model_name" + case temperature + case systemPrompt = "system_prompt" + case topP = "top_p" + case topK = "top_k" + case stopSequences = "stop_sequences" + case apiVersion = "api_version" case projectId = "project_id" + case accessToken = "access_token" case refreshToken = "refresh_token" + case clientId = "client_id" + case clientSecret = "client_secret" case region - case stopSequences = "stop_sequences" - case systemPrompt = "system_prompt" - case temperature - case topK = "top_k" - case topP = "top_p" + case maxOutputTokens = "max_output_tokens" + case accountId = "account_id" case id } @@ -99,24 +99,24 @@ public struct NLSearchModelCreateSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(accessToken, forKey: .accessToken) - try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encodeIfPresent(modelName, forKey: .modelName) try container.encodeIfPresent(apiKey, forKey: .apiKey) try container.encodeIfPresent(apiUrl, forKey: .apiUrl) - try container.encodeIfPresent(apiVersion, forKey: .apiVersion) - try container.encodeIfPresent(clientId, forKey: .clientId) - try container.encodeIfPresent(clientSecret, forKey: .clientSecret) try container.encodeIfPresent(maxBytes, forKey: .maxBytes) - try container.encodeIfPresent(maxOutputTokens, forKey: .maxOutputTokens) - try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(temperature, forKey: .temperature) + try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) + try container.encodeIfPresent(topP, forKey: .topP) + try container.encodeIfPresent(topK, forKey: .topK) + try container.encodeIfPresent(stopSequences, forKey: .stopSequences) + try container.encodeIfPresent(apiVersion, forKey: .apiVersion) try container.encodeIfPresent(projectId, forKey: .projectId) + try container.encodeIfPresent(accessToken, forKey: .accessToken) try container.encodeIfPresent(refreshToken, forKey: .refreshToken) + try container.encodeIfPresent(clientId, forKey: .clientId) + try container.encodeIfPresent(clientSecret, forKey: .clientSecret) try container.encodeIfPresent(region, forKey: .region) - try container.encodeIfPresent(stopSequences, forKey: .stopSequences) - try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) - try container.encodeIfPresent(temperature, forKey: .temperature) - try container.encodeIfPresent(topK, forKey: .topK) - try container.encodeIfPresent(topP, forKey: .topP) + try container.encodeIfPresent(maxOutputTokens, forKey: .maxOutputTokens) + try container.encodeIfPresent(accountId, forKey: .accountId) try container.encodeIfPresent(id, forKey: .id) } } diff --git a/Sources/Typesense/Models/NLSearchModelSchema.swift b/Sources/Typesense/Models/NLSearchModelSchema.swift index 03843f6..26c15b0 100644 --- a/Sources/Typesense/Models/NLSearchModelSchema.swift +++ b/Sources/Typesense/Models/NLSearchModelSchema.swift @@ -12,86 +12,86 @@ import AnyCodable public struct NLSearchModelSchema: Codable { - /** Access token for GCP Vertex AI */ - public var accessToken: String? - /** Account ID for Cloudflare-specific models */ - public var accountId: String? + /** Name of the NL model to use */ + public var modelName: String? /** API key for the NL model service */ public var apiKey: String? /** Custom API URL for the NL model service */ public var apiUrl: String? - /** API version for the NL model service */ - public var apiVersion: String? - /** Client ID for GCP Vertex AI */ - public var clientId: String? - /** Client secret for GCP Vertex AI */ - public var clientSecret: String? /** Maximum number of bytes to process */ public var maxBytes: Int? - /** Maximum output tokens for GCP Vertex AI */ - public var maxOutputTokens: Int? - /** Name of the NL model to use */ - public var modelName: String? + /** Temperature parameter for the NL model */ + public var temperature: Double? + /** System prompt for the NL model */ + public var systemPrompt: String? + /** Top-p parameter for the NL model (Google-specific) */ + public var topP: Double? + /** Top-k parameter for the NL model (Google-specific) */ + public var topK: Int? + /** Stop sequences for the NL model (Google-specific) */ + public var stopSequences: [String]? + /** API version for the NL model service */ + public var apiVersion: String? /** Project ID for GCP Vertex AI */ public var projectId: String? + /** Access token for GCP Vertex AI */ + public var accessToken: String? /** Refresh token for GCP Vertex AI */ public var refreshToken: String? + /** Client ID for GCP Vertex AI */ + public var clientId: String? + /** Client secret for GCP Vertex AI */ + public var clientSecret: String? /** Region for GCP Vertex AI */ public var region: String? - /** Stop sequences for the NL model (Google-specific) */ - public var stopSequences: [String]? - /** System prompt for the NL model */ - public var systemPrompt: String? - /** Temperature parameter for the NL model */ - public var temperature: Double? - /** Top-k parameter for the NL model (Google-specific) */ - public var topK: Int? - /** Top-p parameter for the NL model (Google-specific) */ - public var topP: Double? + /** Maximum output tokens for GCP Vertex AI */ + public var maxOutputTokens: Int? + /** Account ID for Cloudflare-specific models */ + public var accountId: String? /** ID of the NL search model */ public var id: String - public init(id: String, accessToken: String? = nil, accountId: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, apiVersion: String? = nil, clientId: String? = nil, clientSecret: String? = nil, maxBytes: Int? = nil, maxOutputTokens: Int? = nil, modelName: String? = nil, projectId: String? = nil, refreshToken: String? = nil, region: String? = nil, stopSequences: [String]? = nil, systemPrompt: String? = nil, temperature: Double? = nil, topK: Int? = nil, topP: Double? = nil) { - self.accessToken = accessToken - self.accountId = accountId + public init(id: String, modelName: String? = nil, apiKey: String? = nil, apiUrl: String? = nil, maxBytes: Int? = nil, temperature: Double? = nil, systemPrompt: String? = nil, topP: Double? = nil, topK: Int? = nil, stopSequences: [String]? = nil, apiVersion: String? = nil, projectId: String? = nil, accessToken: String? = nil, refreshToken: String? = nil, clientId: String? = nil, clientSecret: String? = nil, region: String? = nil, maxOutputTokens: Int? = nil, accountId: String? = nil) { + self.modelName = modelName self.apiKey = apiKey self.apiUrl = apiUrl - self.apiVersion = apiVersion - self.clientId = clientId - self.clientSecret = clientSecret self.maxBytes = maxBytes - self.maxOutputTokens = maxOutputTokens - self.modelName = modelName + self.temperature = temperature + self.systemPrompt = systemPrompt + self.topP = topP + self.topK = topK + self.stopSequences = stopSequences + self.apiVersion = apiVersion self.projectId = projectId + self.accessToken = accessToken self.refreshToken = refreshToken + self.clientId = clientId + self.clientSecret = clientSecret self.region = region - self.stopSequences = stopSequences - self.systemPrompt = systemPrompt - self.temperature = temperature - self.topK = topK - self.topP = topP + self.maxOutputTokens = maxOutputTokens + self.accountId = accountId self.id = id } public enum CodingKeys: String, CodingKey, CaseIterable { - case accessToken = "access_token" - case accountId = "account_id" + case modelName = "model_name" case apiKey = "api_key" case apiUrl = "api_url" - case apiVersion = "api_version" - case clientId = "client_id" - case clientSecret = "client_secret" case maxBytes = "max_bytes" - case maxOutputTokens = "max_output_tokens" - case modelName = "model_name" + case temperature + case systemPrompt = "system_prompt" + case topP = "top_p" + case topK = "top_k" + case stopSequences = "stop_sequences" + case apiVersion = "api_version" case projectId = "project_id" + case accessToken = "access_token" case refreshToken = "refresh_token" + case clientId = "client_id" + case clientSecret = "client_secret" case region - case stopSequences = "stop_sequences" - case systemPrompt = "system_prompt" - case temperature - case topK = "top_k" - case topP = "top_p" + case maxOutputTokens = "max_output_tokens" + case accountId = "account_id" case id } @@ -99,24 +99,24 @@ public struct NLSearchModelSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(accessToken, forKey: .accessToken) - try container.encodeIfPresent(accountId, forKey: .accountId) + try container.encodeIfPresent(modelName, forKey: .modelName) try container.encodeIfPresent(apiKey, forKey: .apiKey) try container.encodeIfPresent(apiUrl, forKey: .apiUrl) - try container.encodeIfPresent(apiVersion, forKey: .apiVersion) - try container.encodeIfPresent(clientId, forKey: .clientId) - try container.encodeIfPresent(clientSecret, forKey: .clientSecret) try container.encodeIfPresent(maxBytes, forKey: .maxBytes) - try container.encodeIfPresent(maxOutputTokens, forKey: .maxOutputTokens) - try container.encodeIfPresent(modelName, forKey: .modelName) + try container.encodeIfPresent(temperature, forKey: .temperature) + try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) + try container.encodeIfPresent(topP, forKey: .topP) + try container.encodeIfPresent(topK, forKey: .topK) + try container.encodeIfPresent(stopSequences, forKey: .stopSequences) + try container.encodeIfPresent(apiVersion, forKey: .apiVersion) try container.encodeIfPresent(projectId, forKey: .projectId) + try container.encodeIfPresent(accessToken, forKey: .accessToken) try container.encodeIfPresent(refreshToken, forKey: .refreshToken) + try container.encodeIfPresent(clientId, forKey: .clientId) + try container.encodeIfPresent(clientSecret, forKey: .clientSecret) try container.encodeIfPresent(region, forKey: .region) - try container.encodeIfPresent(stopSequences, forKey: .stopSequences) - try container.encodeIfPresent(systemPrompt, forKey: .systemPrompt) - try container.encodeIfPresent(temperature, forKey: .temperature) - try container.encodeIfPresent(topK, forKey: .topK) - try container.encodeIfPresent(topP, forKey: .topP) + try container.encodeIfPresent(maxOutputTokens, forKey: .maxOutputTokens) + try container.encodeIfPresent(accountId, forKey: .accountId) try container.encode(id, forKey: .id) } } diff --git a/Sources/Typesense/Models/SchemaChangeStatus.swift b/Sources/Typesense/Models/SchemaChangeStatus.swift index c57b459..89d5bbe 100644 --- a/Sources/Typesense/Models/SchemaChangeStatus.swift +++ b/Sources/Typesense/Models/SchemaChangeStatus.swift @@ -12,31 +12,31 @@ import AnyCodable public struct SchemaChangeStatus: Codable { - /** Number of documents that have been altered */ - public var alteredDocs: Int? /** Name of the collection being modified */ public var collection: String? /** Number of documents that have been validated */ public var validatedDocs: Int? + /** Number of documents that have been altered */ + public var alteredDocs: Int? - public init(alteredDocs: Int? = nil, collection: String? = nil, validatedDocs: Int? = nil) { - self.alteredDocs = alteredDocs + public init(collection: String? = nil, validatedDocs: Int? = nil, alteredDocs: Int? = nil) { self.collection = collection self.validatedDocs = validatedDocs + self.alteredDocs = alteredDocs } public enum CodingKeys: String, CodingKey, CaseIterable { - case alteredDocs = "altered_docs" case collection case validatedDocs = "validated_docs" + case alteredDocs = "altered_docs" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(alteredDocs, forKey: .alteredDocs) try container.encodeIfPresent(collection, forKey: .collection) try container.encodeIfPresent(validatedDocs, forKey: .validatedDocs) + try container.encodeIfPresent(alteredDocs, forKey: .alteredDocs) } } diff --git a/Sources/Typesense/Models/SearchHighlight.swift b/Sources/Typesense/Models/SearchHighlight.swift index f02014a..1d3cfda 100644 --- a/Sources/Typesense/Models/SearchHighlight.swift +++ b/Sources/Typesense/Models/SearchHighlight.swift @@ -13,9 +13,6 @@ import AnyCodable public struct SearchHighlight: Codable { public var field: String? - /** The indices property will be present only for string[] fields and will contain the corresponding indices of the snippets in the search field */ - public var indices: [Int]? - public var matchedTokens: [AnyCodable]? /** Present only for (non-array) string fields */ public var snippet: String? /** Present only for (array) string[] fields */ @@ -24,25 +21,28 @@ public struct SearchHighlight: Codable { public var value: String? /** Full field value with highlighting, present only for (array) string[] fields */ public var values: [String]? + /** The indices property will be present only for string[] fields and will contain the corresponding indices of the snippets in the search field */ + public var indices: [Int]? + public var matchedTokens: [AnyCodable]? - public init(field: String? = nil, indices: [Int]? = nil, matchedTokens: [AnyCodable]? = nil, snippet: String? = nil, snippets: [String]? = nil, value: String? = nil, values: [String]? = nil) { + public init(field: String? = nil, snippet: String? = nil, snippets: [String]? = nil, value: String? = nil, values: [String]? = nil, indices: [Int]? = nil, matchedTokens: [AnyCodable]? = nil) { self.field = field - self.indices = indices - self.matchedTokens = matchedTokens self.snippet = snippet self.snippets = snippets self.value = value self.values = values + self.indices = indices + self.matchedTokens = matchedTokens } public enum CodingKeys: String, CodingKey, CaseIterable { case field - case indices - case matchedTokens = "matched_tokens" case snippet case snippets case value case values + case indices + case matchedTokens = "matched_tokens" } // Encodable protocol methods @@ -50,11 +50,11 @@ public struct SearchHighlight: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(field, forKey: .field) - try container.encodeIfPresent(indices, forKey: .indices) - try container.encodeIfPresent(matchedTokens, forKey: .matchedTokens) try container.encodeIfPresent(snippet, forKey: .snippet) try container.encodeIfPresent(snippets, forKey: .snippets) try container.encodeIfPresent(value, forKey: .value) try container.encodeIfPresent(values, forKey: .values) + try container.encodeIfPresent(indices, forKey: .indices) + try container.encodeIfPresent(matchedTokens, forKey: .matchedTokens) } } diff --git a/Sources/Typesense/Models/SearchParameters.swift b/Sources/Typesense/Models/SearchParameters.swift index 87d1462..d556845 100644 --- a/Sources/Typesense/Models/SearchParameters.swift +++ b/Sources/Typesense/Models/SearchParameters.swift @@ -12,370 +12,370 @@ import AnyCodable public struct SearchParameters: Codable { - /** 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. */ - public var cacheTtl: Int? - /** Enable conversational search. */ - public var conversation: Bool? - /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ - public var conversationId: String? - /** The Id of Conversation Model to be used. */ - public var conversationModelId: String? - public var dropTokensMode: DropTokensMode? - /** 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 */ - public var dropTokensThreshold: Int? - /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ - public var enableAnalytics: Bool? = true - /** Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true */ - public var enableHighlightV1: Bool? = true - /** 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 */ - public var enableOverrides: Bool? = false - /** 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 */ - public var enableSynonyms: Bool? - /** Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. */ - public var enableTyposForAlphaNumericalTokens: Bool? - /** Make Typesense disable typos for numerical tokens. */ - public var enableTyposForNumericalTokens: Bool? = true - /** List of fields from the document to exclude in the search result */ - public var excludeFields: String? - /** 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). */ - public var exhaustiveSearch: Bool? - /** A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. */ - public var facetBy: String? - /** 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\". */ - public var facetQuery: String? - /** Comma separated string of nested facet fields whose parent object should be returned in facet response. */ - public var facetReturnParent: String? - /** Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). */ - public var facetStrategy: String? - /** Filter conditions for refining your open api validator search results. Separate multiple conditions with &&. */ - public var filterBy: String? - /** Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false */ - public var filterCuratedHits: Bool? - /** 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. */ - public var groupBy: String? - /** 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 */ - public var groupLimit: Int? - /** 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 */ - public var groupMissingValues: Bool? - /** 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`. */ - public var hiddenHits: String? - /** The number of tokens that should surround the highlighted text on each side. Default: 4 */ - public var highlightAffixNumTokens: Int? - /** The end tag used for the highlighted snippets. Default: `` */ - public var highlightEndTag: String? - /** A list of custom fields that must be highlighted even if you don't query for them */ - public var highlightFields: String? - /** List of fields which should be highlighted fully without snippeting */ - public var highlightFullFields: String? - /** The start tag used for the highlighted snippets. Default: `` */ - public var highlightStartTag: String? - /** List of fields from the document to include in the search result */ - public var includeFields: 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. */ + public var q: String? + /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ + public var queryBy: String? + /** Whether to use natural language processing to parse the query. */ + public var nlQuery: Bool? + /** The ID of the natural language model to use. */ + public var nlModelId: 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. */ + public var queryByWeights: 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. */ + public var textMatchType: 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. */ + public var _prefix: String? /** 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 */ public var _infix: String? - /** Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. */ - public var limit: Int? - /** Control the number of words that Typesense considers for typo and prefix searching. */ - public var maxCandidates: Int? /** 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. */ public var maxExtraPrefix: Int? /** 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. */ public var maxExtraSuffix: Int? - /** Maximum number of facet values to be returned. */ - public var maxFacetValues: Int? + /** Filter conditions for refining your open api validator search results. Separate multiple conditions with &&. */ + public var filterBy: String? /** 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*. */ public var maxFilterByCandidates: Int? - /** Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ - public var minLen1typo: Int? - /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ - public var minLen2typo: Int? - /** The ID of the natural language model to use. */ - public var nlModelId: String? - /** Whether to use natural language processing to parse the query. */ - public var nlQuery: Bool? + /** 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` */ + public var sortBy: String? + /** A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. */ + public var facetBy: String? + /** Maximum number of facet values to be returned. */ + public var maxFacetValues: Int? + /** 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\". */ + public var facetQuery: String? /** The number of typographical errors (1 or 2) that would be tolerated. Default: 2 */ public var numTypos: String? - /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ - public var offset: Int? - /** Comma separated list of tags to trigger the curations rules that match the tags. */ - public var overrideTags: String? /** Results from this specific page number would be fetched. */ public var page: Int? /** Number of results to fetch per page. Default: 10 */ public var perPage: Int? + /** Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. */ + public var limit: Int? + /** Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. */ + public var offset: Int? + /** 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. */ + public var groupBy: String? + /** 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 */ + public var groupLimit: Int? + /** 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 */ + public var groupMissingValues: Bool? + /** List of fields from the document to include in the search result */ + public var includeFields: String? + /** List of fields from the document to exclude in the search result */ + public var excludeFields: String? + /** List of fields which should be highlighted fully without snippeting */ + public var highlightFullFields: String? + /** The number of tokens that should surround the highlighted text on each side. Default: 4 */ + public var highlightAffixNumTokens: Int? + /** The start tag used for the highlighted snippets. Default: `` */ + public var highlightStartTag: String? + /** The end tag used for the highlighted snippets. Default: `` */ + public var highlightEndTag: String? + /** Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true */ + public var enableHighlightV1: Bool? = true + /** Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). */ + public var enableAnalytics: Bool? = true + /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ + public var snippetThreshold: Int? + /** List of synonym set names to associate with this search query */ + public var synonymSets: String? + /** 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 */ + public var dropTokensThreshold: Int? + public var dropTokensMode: DropTokensMode? + /** 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 */ + public var typoTokensThreshold: Int? + /** Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. */ + public var enableTyposForAlphaNumericalTokens: 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 */ + public var filterCuratedHits: 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 */ + public var enableSynonyms: Bool? + /** Allow synonym resolution on word prefixes in the query. Default: false */ + public var synonymPrefix: Bool? + /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ + public var synonymNumTypos: Int? /** 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`. */ public var pinnedHits: 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`. */ + public var hiddenHits: String? + /** Comma separated list of tags to trigger the curations rules that match the tags. */ + public var overrideTags: String? + /** A list of custom fields that must be highlighted even if you don't query for them */ + public var highlightFields: 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`. */ + public var splitJoinTokens: String? /** 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 */ public var preSegmentedQuery: Bool? - /** 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. */ - public var _prefix: String? /** Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. */ public var preset: String? + /** 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 */ + public var enableOverrides: Bool? = false /** Set this parameter to true to ensure that an exact match is ranked above the others */ public var prioritizeExactMatch: Bool? = true - /** Make Typesense prioritize documents where the query words appear in more number of fields. */ - public var prioritizeNumMatchingFields: Bool? = true + /** Control the number of words that Typesense considers for typo and prefix searching. */ + public var maxCandidates: Int? /** Make Typesense prioritize documents where the query words appear earlier in the text. */ public var prioritizeTokenPosition: Bool? = false - /** 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. */ - public var q: String? - /** A list of `string` fields that should be queried against. Multiple fields are separated with a comma. */ - public var queryBy: 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. */ - public var queryByWeights: String? - /** Number of times to retry fetching remote embeddings. */ - public var remoteEmbeddingNumTries: Int? - /** Timeout (in milliseconds) for fetching remote embeddings. */ - public var remoteEmbeddingTimeoutMs: Int? + /** Make Typesense prioritize documents where the query words appear in more number of fields. */ + public var prioritizeNumMatchingFields: Bool? = true + /** Make Typesense disable typos for numerical tokens. */ + public var enableTyposForNumericalTokens: Bool? = true + /** 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). */ + public var exhaustiveSearch: Bool? /** 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. */ public var searchCutoffMs: Int? - /** Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 */ - public var snippetThreshold: Int? - /** 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` */ - public var sortBy: 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`. */ - public var splitJoinTokens: String? - /** Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. */ - public var stopwords: String? - /** Allow synonym resolution on typo-corrected words in the query. Default: 0 */ - public var synonymNumTypos: Int? - /** Allow synonym resolution on word prefixes in the query. Default: false */ - public var synonymPrefix: Bool? - /** List of synonym set names to associate with this search query */ - public var synonymSets: 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. */ - public var textMatchType: String? - /** 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 */ - public var typoTokensThreshold: Int? /** Enable server side caching of search query results. By default, caching is disabled. */ public var useCache: Bool? + /** 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. */ + public var cacheTtl: Int? + /** Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ + public var minLen1typo: Int? + /** Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. */ + public var minLen2typo: Int? /** Vector query expression for fetching documents \"closest\" to a given query/document vector. */ public var vectorQuery: String? + /** Timeout (in milliseconds) for fetching remote embeddings. */ + public var remoteEmbeddingTimeoutMs: Int? + /** Number of times to retry fetching remote embeddings. */ + public var remoteEmbeddingNumTries: Int? + /** Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). */ + public var facetStrategy: String? + /** Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. */ + public var stopwords: String? + /** Comma separated string of nested facet fields whose parent object should be returned in facet response. */ + public var facetReturnParent: String? /** The base64 encoded audio file in 16 khz 16-bit WAV format. */ public var voiceQuery: String? + /** Enable conversational search. */ + public var conversation: Bool? + /** The Id of Conversation Model to be used. */ + public var conversationModelId: String? + /** The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. */ + public var conversationId: String? - public init(cacheTtl: Int? = nil, conversation: Bool? = nil, conversationId: String? = nil, conversationModelId: String? = nil, dropTokensMode: DropTokensMode? = nil, dropTokensThreshold: Int? = nil, enableAnalytics: Bool? = true, enableHighlightV1: Bool? = true, enableOverrides: Bool? = false, enableSynonyms: Bool? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, enableTyposForNumericalTokens: Bool? = true, excludeFields: String? = nil, exhaustiveSearch: Bool? = nil, facetBy: String? = nil, facetQuery: String? = nil, facetReturnParent: String? = nil, facetStrategy: String? = nil, filterBy: String? = nil, filterCuratedHits: Bool? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, hiddenHits: String? = nil, highlightAffixNumTokens: Int? = nil, highlightEndTag: String? = nil, highlightFields: String? = nil, highlightFullFields: String? = nil, highlightStartTag: String? = nil, includeFields: String? = nil, _infix: String? = nil, limit: Int? = nil, maxCandidates: Int? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, maxFacetValues: Int? = nil, maxFilterByCandidates: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, nlModelId: String? = nil, nlQuery: Bool? = nil, numTypos: String? = nil, offset: Int? = nil, overrideTags: String? = nil, page: Int? = nil, perPage: Int? = nil, pinnedHits: String? = nil, preSegmentedQuery: Bool? = nil, _prefix: String? = nil, preset: String? = nil, prioritizeExactMatch: Bool? = true, prioritizeNumMatchingFields: Bool? = true, prioritizeTokenPosition: Bool? = false, q: String? = nil, queryBy: String? = nil, queryByWeights: String? = nil, remoteEmbeddingNumTries: Int? = nil, remoteEmbeddingTimeoutMs: Int? = nil, searchCutoffMs: Int? = nil, snippetThreshold: Int? = nil, sortBy: String? = nil, splitJoinTokens: String? = nil, stopwords: String? = nil, synonymNumTypos: Int? = nil, synonymPrefix: Bool? = nil, synonymSets: String? = nil, textMatchType: String? = nil, typoTokensThreshold: Int? = nil, useCache: Bool? = nil, vectorQuery: String? = nil, voiceQuery: String? = nil) { - self.cacheTtl = cacheTtl - self.conversation = conversation - self.conversationId = conversationId - self.conversationModelId = conversationModelId - self.dropTokensMode = dropTokensMode - self.dropTokensThreshold = dropTokensThreshold - self.enableAnalytics = enableAnalytics - self.enableHighlightV1 = enableHighlightV1 - self.enableOverrides = enableOverrides - self.enableSynonyms = enableSynonyms - self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens - self.enableTyposForNumericalTokens = enableTyposForNumericalTokens - self.excludeFields = excludeFields - self.exhaustiveSearch = exhaustiveSearch - self.facetBy = facetBy - self.facetQuery = facetQuery - self.facetReturnParent = facetReturnParent - self.facetStrategy = facetStrategy - self.filterBy = filterBy - self.filterCuratedHits = filterCuratedHits - self.groupBy = groupBy - self.groupLimit = groupLimit - self.groupMissingValues = groupMissingValues - self.hiddenHits = hiddenHits - self.highlightAffixNumTokens = highlightAffixNumTokens - self.highlightEndTag = highlightEndTag - self.highlightFields = highlightFields - self.highlightFullFields = highlightFullFields - self.highlightStartTag = highlightStartTag - self.includeFields = includeFields + public init(q: String? = nil, queryBy: String? = nil, nlQuery: Bool? = nil, nlModelId: String? = nil, queryByWeights: String? = nil, textMatchType: String? = nil, _prefix: String? = nil, _infix: String? = nil, maxExtraPrefix: Int? = nil, maxExtraSuffix: Int? = nil, filterBy: String? = nil, maxFilterByCandidates: Int? = nil, sortBy: String? = nil, facetBy: String? = nil, maxFacetValues: Int? = nil, facetQuery: String? = nil, numTypos: String? = nil, page: Int? = nil, perPage: Int? = nil, limit: Int? = nil, offset: Int? = nil, groupBy: String? = nil, groupLimit: Int? = nil, groupMissingValues: Bool? = nil, includeFields: String? = nil, excludeFields: String? = nil, highlightFullFields: String? = nil, highlightAffixNumTokens: Int? = nil, highlightStartTag: String? = nil, highlightEndTag: String? = nil, enableHighlightV1: Bool? = true, enableAnalytics: Bool? = true, snippetThreshold: Int? = nil, synonymSets: String? = nil, dropTokensThreshold: Int? = nil, dropTokensMode: DropTokensMode? = nil, typoTokensThreshold: Int? = nil, enableTyposForAlphaNumericalTokens: Bool? = nil, filterCuratedHits: Bool? = nil, enableSynonyms: Bool? = nil, synonymPrefix: Bool? = nil, synonymNumTypos: Int? = nil, pinnedHits: String? = nil, hiddenHits: String? = nil, overrideTags: String? = nil, highlightFields: String? = nil, splitJoinTokens: String? = nil, preSegmentedQuery: Bool? = nil, preset: String? = nil, enableOverrides: Bool? = false, prioritizeExactMatch: Bool? = true, maxCandidates: Int? = nil, prioritizeTokenPosition: Bool? = false, prioritizeNumMatchingFields: Bool? = true, enableTyposForNumericalTokens: Bool? = true, exhaustiveSearch: Bool? = nil, searchCutoffMs: Int? = nil, useCache: Bool? = nil, cacheTtl: Int? = nil, minLen1typo: Int? = nil, minLen2typo: Int? = nil, vectorQuery: String? = nil, remoteEmbeddingTimeoutMs: Int? = nil, remoteEmbeddingNumTries: Int? = nil, facetStrategy: String? = nil, stopwords: String? = nil, facetReturnParent: String? = nil, voiceQuery: String? = nil, conversation: Bool? = nil, conversationModelId: String? = nil, conversationId: String? = nil) { + self.q = q + self.queryBy = queryBy + self.nlQuery = nlQuery + self.nlModelId = nlModelId + self.queryByWeights = queryByWeights + self.textMatchType = textMatchType + self._prefix = _prefix self._infix = _infix - self.limit = limit - self.maxCandidates = maxCandidates self.maxExtraPrefix = maxExtraPrefix self.maxExtraSuffix = maxExtraSuffix - self.maxFacetValues = maxFacetValues + self.filterBy = filterBy self.maxFilterByCandidates = maxFilterByCandidates - self.minLen1typo = minLen1typo - self.minLen2typo = minLen2typo - self.nlModelId = nlModelId - self.nlQuery = nlQuery + self.sortBy = sortBy + self.facetBy = facetBy + self.maxFacetValues = maxFacetValues + self.facetQuery = facetQuery self.numTypos = numTypos - self.offset = offset - self.overrideTags = overrideTags self.page = page self.perPage = perPage + self.limit = limit + self.offset = offset + self.groupBy = groupBy + self.groupLimit = groupLimit + self.groupMissingValues = groupMissingValues + self.includeFields = includeFields + self.excludeFields = excludeFields + self.highlightFullFields = highlightFullFields + self.highlightAffixNumTokens = highlightAffixNumTokens + self.highlightStartTag = highlightStartTag + self.highlightEndTag = highlightEndTag + self.enableHighlightV1 = enableHighlightV1 + self.enableAnalytics = enableAnalytics + self.snippetThreshold = snippetThreshold + self.synonymSets = synonymSets + self.dropTokensThreshold = dropTokensThreshold + self.dropTokensMode = dropTokensMode + self.typoTokensThreshold = typoTokensThreshold + self.enableTyposForAlphaNumericalTokens = enableTyposForAlphaNumericalTokens + self.filterCuratedHits = filterCuratedHits + self.enableSynonyms = enableSynonyms + self.synonymPrefix = synonymPrefix + self.synonymNumTypos = synonymNumTypos self.pinnedHits = pinnedHits + self.hiddenHits = hiddenHits + self.overrideTags = overrideTags + self.highlightFields = highlightFields + self.splitJoinTokens = splitJoinTokens self.preSegmentedQuery = preSegmentedQuery - self._prefix = _prefix self.preset = preset + self.enableOverrides = enableOverrides self.prioritizeExactMatch = prioritizeExactMatch - self.prioritizeNumMatchingFields = prioritizeNumMatchingFields + self.maxCandidates = maxCandidates self.prioritizeTokenPosition = prioritizeTokenPosition - self.q = q - self.queryBy = queryBy - self.queryByWeights = queryByWeights - self.remoteEmbeddingNumTries = remoteEmbeddingNumTries - self.remoteEmbeddingTimeoutMs = remoteEmbeddingTimeoutMs + self.prioritizeNumMatchingFields = prioritizeNumMatchingFields + self.enableTyposForNumericalTokens = enableTyposForNumericalTokens + self.exhaustiveSearch = exhaustiveSearch self.searchCutoffMs = searchCutoffMs - self.snippetThreshold = snippetThreshold - self.sortBy = sortBy - self.splitJoinTokens = splitJoinTokens - self.stopwords = stopwords - self.synonymNumTypos = synonymNumTypos - self.synonymPrefix = synonymPrefix - self.synonymSets = synonymSets - self.textMatchType = textMatchType - self.typoTokensThreshold = typoTokensThreshold self.useCache = useCache + self.cacheTtl = cacheTtl + self.minLen1typo = minLen1typo + self.minLen2typo = minLen2typo self.vectorQuery = vectorQuery + self.remoteEmbeddingTimeoutMs = remoteEmbeddingTimeoutMs + self.remoteEmbeddingNumTries = remoteEmbeddingNumTries + self.facetStrategy = facetStrategy + self.stopwords = stopwords + self.facetReturnParent = facetReturnParent self.voiceQuery = voiceQuery + self.conversation = conversation + self.conversationModelId = conversationModelId + self.conversationId = conversationId } public enum CodingKeys: String, CodingKey, CaseIterable { - case cacheTtl = "cache_ttl" - case conversation - case conversationId = "conversation_id" - case conversationModelId = "conversation_model_id" - case dropTokensMode = "drop_tokens_mode" - case dropTokensThreshold = "drop_tokens_threshold" - case enableAnalytics = "enable_analytics" - case enableHighlightV1 = "enable_highlight_v1" - case enableOverrides = "enable_overrides" - case enableSynonyms = "enable_synonyms" - case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" - case enableTyposForNumericalTokens = "enable_typos_for_numerical_tokens" - case excludeFields = "exclude_fields" - case exhaustiveSearch = "exhaustive_search" - case facetBy = "facet_by" - case facetQuery = "facet_query" - case facetReturnParent = "facet_return_parent" - case facetStrategy = "facet_strategy" - case filterBy = "filter_by" - case filterCuratedHits = "filter_curated_hits" - case groupBy = "group_by" - case groupLimit = "group_limit" - case groupMissingValues = "group_missing_values" - case hiddenHits = "hidden_hits" - case highlightAffixNumTokens = "highlight_affix_num_tokens" - case highlightEndTag = "highlight_end_tag" - case highlightFields = "highlight_fields" - case highlightFullFields = "highlight_full_fields" - case highlightStartTag = "highlight_start_tag" - case includeFields = "include_fields" + case q + case queryBy = "query_by" + case nlQuery = "nl_query" + case nlModelId = "nl_model_id" + case queryByWeights = "query_by_weights" + case textMatchType = "text_match_type" + case _prefix = "prefix" case _infix = "infix" - case limit - case maxCandidates = "max_candidates" case maxExtraPrefix = "max_extra_prefix" case maxExtraSuffix = "max_extra_suffix" - case maxFacetValues = "max_facet_values" + case filterBy = "filter_by" case maxFilterByCandidates = "max_filter_by_candidates" - case minLen1typo = "min_len_1typo" - case minLen2typo = "min_len_2typo" - case nlModelId = "nl_model_id" - case nlQuery = "nl_query" + case sortBy = "sort_by" + case facetBy = "facet_by" + case maxFacetValues = "max_facet_values" + case facetQuery = "facet_query" case numTypos = "num_typos" - case offset - case overrideTags = "override_tags" case page case perPage = "per_page" + case limit + case offset + case groupBy = "group_by" + case groupLimit = "group_limit" + case groupMissingValues = "group_missing_values" + case includeFields = "include_fields" + case excludeFields = "exclude_fields" + case highlightFullFields = "highlight_full_fields" + case highlightAffixNumTokens = "highlight_affix_num_tokens" + case highlightStartTag = "highlight_start_tag" + case highlightEndTag = "highlight_end_tag" + case enableHighlightV1 = "enable_highlight_v1" + case enableAnalytics = "enable_analytics" + case snippetThreshold = "snippet_threshold" + case synonymSets = "synonym_sets" + case dropTokensThreshold = "drop_tokens_threshold" + case dropTokensMode = "drop_tokens_mode" + case typoTokensThreshold = "typo_tokens_threshold" + case enableTyposForAlphaNumericalTokens = "enable_typos_for_alpha_numerical_tokens" + case filterCuratedHits = "filter_curated_hits" + case enableSynonyms = "enable_synonyms" + case synonymPrefix = "synonym_prefix" + case synonymNumTypos = "synonym_num_typos" case pinnedHits = "pinned_hits" + case hiddenHits = "hidden_hits" + case overrideTags = "override_tags" + case highlightFields = "highlight_fields" + case splitJoinTokens = "split_join_tokens" case preSegmentedQuery = "pre_segmented_query" - case _prefix = "prefix" case preset + case enableOverrides = "enable_overrides" case prioritizeExactMatch = "prioritize_exact_match" - case prioritizeNumMatchingFields = "prioritize_num_matching_fields" + case maxCandidates = "max_candidates" case prioritizeTokenPosition = "prioritize_token_position" - case q - case queryBy = "query_by" - case queryByWeights = "query_by_weights" - case remoteEmbeddingNumTries = "remote_embedding_num_tries" - case remoteEmbeddingTimeoutMs = "remote_embedding_timeout_ms" + case prioritizeNumMatchingFields = "prioritize_num_matching_fields" + case enableTyposForNumericalTokens = "enable_typos_for_numerical_tokens" + case exhaustiveSearch = "exhaustive_search" case searchCutoffMs = "search_cutoff_ms" - case snippetThreshold = "snippet_threshold" - case sortBy = "sort_by" - case splitJoinTokens = "split_join_tokens" - case stopwords - case synonymNumTypos = "synonym_num_typos" - case synonymPrefix = "synonym_prefix" - case synonymSets = "synonym_sets" - case textMatchType = "text_match_type" - case typoTokensThreshold = "typo_tokens_threshold" case useCache = "use_cache" + case cacheTtl = "cache_ttl" + case minLen1typo = "min_len_1typo" + case minLen2typo = "min_len_2typo" case vectorQuery = "vector_query" + case remoteEmbeddingTimeoutMs = "remote_embedding_timeout_ms" + case remoteEmbeddingNumTries = "remote_embedding_num_tries" + case facetStrategy = "facet_strategy" + case stopwords + case facetReturnParent = "facet_return_parent" case voiceQuery = "voice_query" + case conversation + case conversationModelId = "conversation_model_id" + case conversationId = "conversation_id" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) - try container.encodeIfPresent(conversation, forKey: .conversation) - try container.encodeIfPresent(conversationId, forKey: .conversationId) - try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) - try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) - try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) - try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) - try container.encodeIfPresent(enableHighlightV1, forKey: .enableHighlightV1) - try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) - try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) - try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) - try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) - try container.encodeIfPresent(excludeFields, forKey: .excludeFields) - try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) - try container.encodeIfPresent(facetBy, forKey: .facetBy) - try container.encodeIfPresent(facetQuery, forKey: .facetQuery) - try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) - try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) - try container.encodeIfPresent(filterBy, forKey: .filterBy) - try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) - try container.encodeIfPresent(groupBy, forKey: .groupBy) - try container.encodeIfPresent(groupLimit, forKey: .groupLimit) - try container.encodeIfPresent(groupMissingValues, forKey: .groupMissingValues) - try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) - try container.encodeIfPresent(highlightAffixNumTokens, forKey: .highlightAffixNumTokens) - try container.encodeIfPresent(highlightEndTag, forKey: .highlightEndTag) - try container.encodeIfPresent(highlightFields, forKey: .highlightFields) - try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) - try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) - try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(q, forKey: .q) + try container.encodeIfPresent(queryBy, forKey: .queryBy) + try container.encodeIfPresent(nlQuery, forKey: .nlQuery) + try container.encodeIfPresent(nlModelId, forKey: .nlModelId) + try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) + try container.encodeIfPresent(textMatchType, forKey: .textMatchType) + try container.encodeIfPresent(_prefix, forKey: ._prefix) try container.encodeIfPresent(_infix, forKey: ._infix) - try container.encodeIfPresent(limit, forKey: .limit) - try container.encodeIfPresent(maxCandidates, forKey: .maxCandidates) try container.encodeIfPresent(maxExtraPrefix, forKey: .maxExtraPrefix) try container.encodeIfPresent(maxExtraSuffix, forKey: .maxExtraSuffix) - try container.encodeIfPresent(maxFacetValues, forKey: .maxFacetValues) + try container.encodeIfPresent(filterBy, forKey: .filterBy) try container.encodeIfPresent(maxFilterByCandidates, forKey: .maxFilterByCandidates) - try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) - try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) - try container.encodeIfPresent(nlModelId, forKey: .nlModelId) - try container.encodeIfPresent(nlQuery, forKey: .nlQuery) + try container.encodeIfPresent(sortBy, forKey: .sortBy) + try container.encodeIfPresent(facetBy, forKey: .facetBy) + try container.encodeIfPresent(maxFacetValues, forKey: .maxFacetValues) + try container.encodeIfPresent(facetQuery, forKey: .facetQuery) try container.encodeIfPresent(numTypos, forKey: .numTypos) - try container.encodeIfPresent(offset, forKey: .offset) - try container.encodeIfPresent(overrideTags, forKey: .overrideTags) try container.encodeIfPresent(page, forKey: .page) try container.encodeIfPresent(perPage, forKey: .perPage) + try container.encodeIfPresent(limit, forKey: .limit) + try container.encodeIfPresent(offset, forKey: .offset) + try container.encodeIfPresent(groupBy, forKey: .groupBy) + try container.encodeIfPresent(groupLimit, forKey: .groupLimit) + try container.encodeIfPresent(groupMissingValues, forKey: .groupMissingValues) + try container.encodeIfPresent(includeFields, forKey: .includeFields) + try container.encodeIfPresent(excludeFields, forKey: .excludeFields) + try container.encodeIfPresent(highlightFullFields, forKey: .highlightFullFields) + try container.encodeIfPresent(highlightAffixNumTokens, forKey: .highlightAffixNumTokens) + try container.encodeIfPresent(highlightStartTag, forKey: .highlightStartTag) + try container.encodeIfPresent(highlightEndTag, forKey: .highlightEndTag) + try container.encodeIfPresent(enableHighlightV1, forKey: .enableHighlightV1) + try container.encodeIfPresent(enableAnalytics, forKey: .enableAnalytics) + try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) + try container.encodeIfPresent(synonymSets, forKey: .synonymSets) + try container.encodeIfPresent(dropTokensThreshold, forKey: .dropTokensThreshold) + try container.encodeIfPresent(dropTokensMode, forKey: .dropTokensMode) + try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) + try container.encodeIfPresent(enableTyposForAlphaNumericalTokens, forKey: .enableTyposForAlphaNumericalTokens) + try container.encodeIfPresent(filterCuratedHits, forKey: .filterCuratedHits) + try container.encodeIfPresent(enableSynonyms, forKey: .enableSynonyms) + try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) + try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) try container.encodeIfPresent(pinnedHits, forKey: .pinnedHits) + try container.encodeIfPresent(hiddenHits, forKey: .hiddenHits) + try container.encodeIfPresent(overrideTags, forKey: .overrideTags) + try container.encodeIfPresent(highlightFields, forKey: .highlightFields) + try container.encodeIfPresent(splitJoinTokens, forKey: .splitJoinTokens) try container.encodeIfPresent(preSegmentedQuery, forKey: .preSegmentedQuery) - try container.encodeIfPresent(_prefix, forKey: ._prefix) try container.encodeIfPresent(preset, forKey: .preset) + try container.encodeIfPresent(enableOverrides, forKey: .enableOverrides) try container.encodeIfPresent(prioritizeExactMatch, forKey: .prioritizeExactMatch) - try container.encodeIfPresent(prioritizeNumMatchingFields, forKey: .prioritizeNumMatchingFields) + try container.encodeIfPresent(maxCandidates, forKey: .maxCandidates) try container.encodeIfPresent(prioritizeTokenPosition, forKey: .prioritizeTokenPosition) - try container.encodeIfPresent(q, forKey: .q) - try container.encodeIfPresent(queryBy, forKey: .queryBy) - try container.encodeIfPresent(queryByWeights, forKey: .queryByWeights) - try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) - try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) + try container.encodeIfPresent(prioritizeNumMatchingFields, forKey: .prioritizeNumMatchingFields) + try container.encodeIfPresent(enableTyposForNumericalTokens, forKey: .enableTyposForNumericalTokens) + try container.encodeIfPresent(exhaustiveSearch, forKey: .exhaustiveSearch) try container.encodeIfPresent(searchCutoffMs, forKey: .searchCutoffMs) - try container.encodeIfPresent(snippetThreshold, forKey: .snippetThreshold) - try container.encodeIfPresent(sortBy, forKey: .sortBy) - try container.encodeIfPresent(splitJoinTokens, forKey: .splitJoinTokens) - try container.encodeIfPresent(stopwords, forKey: .stopwords) - try container.encodeIfPresent(synonymNumTypos, forKey: .synonymNumTypos) - try container.encodeIfPresent(synonymPrefix, forKey: .synonymPrefix) - try container.encodeIfPresent(synonymSets, forKey: .synonymSets) - try container.encodeIfPresent(textMatchType, forKey: .textMatchType) - try container.encodeIfPresent(typoTokensThreshold, forKey: .typoTokensThreshold) try container.encodeIfPresent(useCache, forKey: .useCache) + try container.encodeIfPresent(cacheTtl, forKey: .cacheTtl) + try container.encodeIfPresent(minLen1typo, forKey: .minLen1typo) + try container.encodeIfPresent(minLen2typo, forKey: .minLen2typo) try container.encodeIfPresent(vectorQuery, forKey: .vectorQuery) + try container.encodeIfPresent(remoteEmbeddingTimeoutMs, forKey: .remoteEmbeddingTimeoutMs) + try container.encodeIfPresent(remoteEmbeddingNumTries, forKey: .remoteEmbeddingNumTries) + try container.encodeIfPresent(facetStrategy, forKey: .facetStrategy) + try container.encodeIfPresent(stopwords, forKey: .stopwords) + try container.encodeIfPresent(facetReturnParent, forKey: .facetReturnParent) try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) + try container.encodeIfPresent(conversation, forKey: .conversation) + try container.encodeIfPresent(conversationModelId, forKey: .conversationModelId) + try container.encodeIfPresent(conversationId, forKey: .conversationId) } } diff --git a/Sources/Typesense/Models/SearchRequestParams.swift b/Sources/Typesense/Models/SearchRequestParams.swift index 8426050..a6fc112 100644 --- a/Sources/Typesense/Models/SearchRequestParams.swift +++ b/Sources/Typesense/Models/SearchRequestParams.swift @@ -13,21 +13,21 @@ import AnyCodable public struct SearchRequestParams: Codable { public var collectionName: String - public var perPage: Int public var q: String + public var perPage: Int public var voiceQuery: SearchRequestParamsVoiceQuery? - public init(collectionName: String, perPage: Int, q: String, voiceQuery: SearchRequestParamsVoiceQuery? = nil) { + public init(collectionName: String, q: String, perPage: Int, voiceQuery: SearchRequestParamsVoiceQuery? = nil) { self.collectionName = collectionName - self.perPage = perPage self.q = q + self.perPage = perPage self.voiceQuery = voiceQuery } public enum CodingKeys: String, CodingKey, CaseIterable { case collectionName = "collection_name" - case perPage = "per_page" case q + case perPage = "per_page" case voiceQuery = "voice_query" } @@ -36,8 +36,8 @@ public struct SearchRequestParams: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(collectionName, forKey: .collectionName) - try container.encode(perPage, forKey: .perPage) try container.encode(q, forKey: .q) + try container.encode(perPage, forKey: .perPage) try container.encodeIfPresent(voiceQuery, forKey: .voiceQuery) } } diff --git a/Sources/Typesense/Models/SearchResult.swift b/Sources/Typesense/Models/SearchResult.swift index 723e779..835ac86 100644 --- a/Sources/Typesense/Models/SearchResult.swift +++ b/Sources/Typesense/Models/SearchResult.swift @@ -12,76 +12,76 @@ import AnyCodable public struct SearchResult: Codable { - public var conversation: SearchResultConversation? public var facetCounts: [FacetCounts]? /** The number of documents found */ public var found: Int? public var foundDocs: Int? - public var groupedHits: [SearchGroupedHit]? - /** The documents that matched the search query */ - public var hits: [SearchResultHit]? - /** Custom JSON object that can be returned in the search response */ - public var metadata: [String: AnyCodable]? + /** The number of milliseconds the search took */ + public var searchTimeMs: Int? /** The total number of documents in the collection */ public var outOf: Int? + /** Whether the search was cut off */ + public var searchCutoff: Bool? /** The search result page number */ public var page: Int? + public var groupedHits: [SearchGroupedHit]? + /** The documents that matched the search query */ + public var hits: [SearchResultHit]? public var requestParams: SearchRequestParams? - /** Whether the search was cut off */ - public var searchCutoff: Bool? - /** The number of milliseconds the search took */ - public var searchTimeMs: Int? + public var conversation: SearchResultConversation? /** Returned only for union query response. */ public var unionRequestParams: [SearchRequestParams]? + /** Custom JSON object that can be returned in the search response */ + public var metadata: [String: AnyCodable]? - public init(conversation: SearchResultConversation? = nil, facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, metadata: [String: AnyCodable]? = nil, outOf: Int? = nil, page: Int? = nil, requestParams: SearchRequestParams? = nil, searchCutoff: Bool? = nil, searchTimeMs: Int? = nil, unionRequestParams: [SearchRequestParams]? = nil) { - self.conversation = conversation + public init(facetCounts: [FacetCounts]? = nil, found: Int? = nil, foundDocs: Int? = nil, searchTimeMs: Int? = nil, outOf: Int? = nil, searchCutoff: Bool? = nil, page: Int? = nil, groupedHits: [SearchGroupedHit]? = nil, hits: [SearchResultHit]? = nil, requestParams: SearchRequestParams? = nil, conversation: SearchResultConversation? = nil, unionRequestParams: [SearchRequestParams]? = nil, metadata: [String: AnyCodable]? = nil) { self.facetCounts = facetCounts self.found = found self.foundDocs = foundDocs - self.groupedHits = groupedHits - self.hits = hits - self.metadata = metadata + self.searchTimeMs = searchTimeMs self.outOf = outOf + self.searchCutoff = searchCutoff self.page = page + self.groupedHits = groupedHits + self.hits = hits self.requestParams = requestParams - self.searchCutoff = searchCutoff - self.searchTimeMs = searchTimeMs + self.conversation = conversation self.unionRequestParams = unionRequestParams + self.metadata = metadata } public enum CodingKeys: String, CodingKey, CaseIterable { - case conversation case facetCounts = "facet_counts" case found case foundDocs = "found_docs" - case groupedHits = "grouped_hits" - case hits - case metadata + case searchTimeMs = "search_time_ms" case outOf = "out_of" + case searchCutoff = "search_cutoff" case page + case groupedHits = "grouped_hits" + case hits case requestParams = "request_params" - case searchCutoff = "search_cutoff" - case searchTimeMs = "search_time_ms" + case conversation case unionRequestParams = "union_request_params" + case metadata } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(conversation, forKey: .conversation) try container.encodeIfPresent(facetCounts, forKey: .facetCounts) try container.encodeIfPresent(found, forKey: .found) try container.encodeIfPresent(foundDocs, forKey: .foundDocs) - try container.encodeIfPresent(groupedHits, forKey: .groupedHits) - try container.encodeIfPresent(hits, forKey: .hits) - try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encodeIfPresent(searchTimeMs, forKey: .searchTimeMs) try container.encodeIfPresent(outOf, forKey: .outOf) + try container.encodeIfPresent(searchCutoff, forKey: .searchCutoff) try container.encodeIfPresent(page, forKey: .page) + try container.encodeIfPresent(groupedHits, forKey: .groupedHits) + try container.encodeIfPresent(hits, forKey: .hits) try container.encodeIfPresent(requestParams, forKey: .requestParams) - try container.encodeIfPresent(searchCutoff, forKey: .searchCutoff) - try container.encodeIfPresent(searchTimeMs, forKey: .searchTimeMs) + try container.encodeIfPresent(conversation, forKey: .conversation) try container.encodeIfPresent(unionRequestParams, forKey: .unionRequestParams) + try container.encodeIfPresent(metadata, forKey: .metadata) } } diff --git a/Sources/Typesense/Models/SearchResultHit.swift b/Sources/Typesense/Models/SearchResultHit.swift index ca1f1dd..b079a63 100644 --- a/Sources/Typesense/Models/SearchResultHit.swift +++ b/Sources/Typesense/Models/SearchResultHit.swift @@ -12,58 +12,58 @@ import AnyCodable public struct SearchResultHit: Codable { + /** (Deprecated) Contains highlighted portions of the search fields */ + public var highlights: [SearchHighlight]? + /** Highlighted version of the matching document */ + public var highlight: [String: AnyCodable]? /** Can be any key-value pair */ public var document: T? + public var textMatch: Int64? + public var textMatchInfo: SearchResultHitTextMatchInfo? /** Can be any key-value pair */ public var geoDistanceMeters: [String: Int]? - /** Highlighted version of the matching document */ - public var highlight: [String: AnyCodable]? - /** (Deprecated) Contains highlighted portions of the search fields */ - public var highlights: [SearchHighlight]? + /** Distance between the query vector and matching document's vector value */ + public var vectorDistance: Float? public var hybridSearchInfo: SearchResultHitHybridSearchInfo? /** Returned only for union query response. Indicates the index of the query which this document matched to. */ public var searchIndex: Int? - public var textMatch: Int64? - public var textMatchInfo: SearchResultHitTextMatchInfo? - /** Distance between the query vector and matching document's vector value */ - public var vectorDistance: Float? - public init(document: T? = nil, geoDistanceMeters: [String: Int]? = nil, highlight: [String: AnyCodable]? = nil, highlights: [SearchHighlight]? = nil, hybridSearchInfo: SearchResultHitHybridSearchInfo? = nil, searchIndex: Int? = nil, textMatch: Int64? = nil, textMatchInfo: SearchResultHitTextMatchInfo? = nil, vectorDistance: Float? = nil) { - self.document = document - self.geoDistanceMeters = geoDistanceMeters - self.highlight = highlight + public init(highlights: [SearchHighlight]? = nil, highlight: [String: AnyCodable]? = nil, document: T? = nil, textMatch: Int64? = nil, textMatchInfo: SearchResultHitTextMatchInfo? = nil, geoDistanceMeters: [String: Int]? = nil, vectorDistance: Float? = nil, hybridSearchInfo: SearchResultHitHybridSearchInfo? = nil, searchIndex: Int? = nil) { self.highlights = highlights - self.hybridSearchInfo = hybridSearchInfo - self.searchIndex = searchIndex + self.highlight = highlight + self.document = document self.textMatch = textMatch self.textMatchInfo = textMatchInfo + self.geoDistanceMeters = geoDistanceMeters self.vectorDistance = vectorDistance + self.hybridSearchInfo = hybridSearchInfo + self.searchIndex = searchIndex } public enum CodingKeys: String, CodingKey, CaseIterable { - case document - case geoDistanceMeters = "geo_distance_meters" - case highlight case highlights - case hybridSearchInfo = "hybrid_search_info" - case searchIndex = "search_index" + case highlight + case document case textMatch = "text_match" case textMatchInfo = "text_match_info" + case geoDistanceMeters = "geo_distance_meters" case vectorDistance = "vector_distance" + case hybridSearchInfo = "hybrid_search_info" + case searchIndex = "search_index" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(document, forKey: .document) - try container.encodeIfPresent(geoDistanceMeters, forKey: .geoDistanceMeters) - try container.encodeIfPresent(highlight, forKey: .highlight) try container.encodeIfPresent(highlights, forKey: .highlights) - try container.encodeIfPresent(hybridSearchInfo, forKey: .hybridSearchInfo) - try container.encodeIfPresent(searchIndex, forKey: .searchIndex) + try container.encodeIfPresent(highlight, forKey: .highlight) + try container.encodeIfPresent(document, forKey: .document) try container.encodeIfPresent(textMatch, forKey: .textMatch) try container.encodeIfPresent(textMatchInfo, forKey: .textMatchInfo) + try container.encodeIfPresent(geoDistanceMeters, forKey: .geoDistanceMeters) try container.encodeIfPresent(vectorDistance, forKey: .vectorDistance) + try container.encodeIfPresent(hybridSearchInfo, forKey: .hybridSearchInfo) + try container.encodeIfPresent(searchIndex, forKey: .searchIndex) } } diff --git a/Sources/Typesense/Models/SearchSynonym.swift b/Sources/Typesense/Models/SearchSynonym.swift index 2dfd805..f9175b0 100644 --- a/Sources/Typesense/Models/SearchSynonym.swift +++ b/Sources/Typesense/Models/SearchSynonym.swift @@ -12,29 +12,29 @@ import AnyCodable public struct SearchSynonym: Codable { - /** Locale for the synonym, leave blank to use the standard tokenizer. */ - public var locale: String? /** For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. */ public var root: String? - /** By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. */ - public var symbolsToIndex: [String]? /** Array of words that should be considered as synonyms. */ public var synonyms: [String] + /** Locale for the synonym, leave blank to use the standard tokenizer. */ + public var locale: String? + /** By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. */ + public var symbolsToIndex: [String]? public var id: String - public init(synonyms: [String], id: String, locale: String? = nil, root: String? = nil, symbolsToIndex: [String]? = nil) { - self.locale = locale + public init(synonyms: [String], id: String, root: String? = nil, locale: String? = nil, symbolsToIndex: [String]? = nil) { self.root = root - self.symbolsToIndex = symbolsToIndex self.synonyms = synonyms + self.locale = locale + self.symbolsToIndex = symbolsToIndex self.id = id } public enum CodingKeys: String, CodingKey, CaseIterable { - case locale case root - case symbolsToIndex = "symbols_to_index" case synonyms + case locale + case symbolsToIndex = "symbols_to_index" case id } @@ -42,10 +42,10 @@ public struct SearchSynonym: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(locale, forKey: .locale) try container.encodeIfPresent(root, forKey: .root) - try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) try container.encode(synonyms, forKey: .synonyms) + try container.encodeIfPresent(locale, forKey: .locale) + try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) try container.encode(id, forKey: .id) } } diff --git a/Sources/Typesense/Models/SearchSynonymSchema.swift b/Sources/Typesense/Models/SearchSynonymSchema.swift index 709feee..5866eab 100644 --- a/Sources/Typesense/Models/SearchSynonymSchema.swift +++ b/Sources/Typesense/Models/SearchSynonymSchema.swift @@ -12,36 +12,36 @@ import AnyCodable public struct SearchSynonymSchema: Codable { - /** Locale for the synonym, leave blank to use the standard tokenizer. */ - public var locale: String? /** For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. */ public var root: String? - /** By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. */ - public var symbolsToIndex: [String]? /** Array of words that should be considered as synonyms. */ public var synonyms: [String] + /** Locale for the synonym, leave blank to use the standard tokenizer. */ + public var locale: String? + /** By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. */ + public var symbolsToIndex: [String]? - public init(synonyms: [String], locale: String? = nil, root: String? = nil, symbolsToIndex: [String]? = nil) { - self.locale = locale + public init(synonyms: [String], root: String? = nil, locale: String? = nil, symbolsToIndex: [String]? = nil) { self.root = root - self.symbolsToIndex = symbolsToIndex self.synonyms = synonyms + self.locale = locale + self.symbolsToIndex = symbolsToIndex } public enum CodingKeys: String, CodingKey, CaseIterable { - case locale case root - case symbolsToIndex = "symbols_to_index" case synonyms + case locale + case symbolsToIndex = "symbols_to_index" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(locale, forKey: .locale) try container.encodeIfPresent(root, forKey: .root) - try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) try container.encode(synonyms, forKey: .synonyms) + try container.encodeIfPresent(locale, forKey: .locale) + try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) } } diff --git a/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift b/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift index 724bc02..45b4609 100644 --- a/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift +++ b/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift @@ -12,26 +12,26 @@ import AnyCodable public struct StemmingDictionaryWordsInner: Codable { - /** The root form of the word */ - public var root: String /** The word form to be stemmed */ public var word: String + /** The root form of the word */ + public var root: String - public init(root: String, word: String) { - self.root = root + public init(word: String, root: String) { self.word = word + self.root = root } public enum CodingKeys: String, CodingKey, CaseIterable { - case root case word + case root } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(root, forKey: .root) try container.encode(word, forKey: .word) + try container.encode(root, forKey: .root) } } diff --git a/Sources/Typesense/Models/StopwordsSetSchema.swift b/Sources/Typesense/Models/StopwordsSetSchema.swift index b80e390..e117707 100644 --- a/Sources/Typesense/Models/StopwordsSetSchema.swift +++ b/Sources/Typesense/Models/StopwordsSetSchema.swift @@ -13,19 +13,19 @@ import AnyCodable public struct StopwordsSetSchema: Codable { public var id: String - public var locale: String? public var stopwords: [String] + public var locale: String? public init(id: String, stopwords: [String], locale: String? = nil) { self.id = id - self.locale = locale self.stopwords = stopwords + self.locale = locale } public enum CodingKeys: String, CodingKey, CaseIterable { case id - case locale case stopwords + case locale } // Encodable protocol methods @@ -33,7 +33,7 @@ public struct StopwordsSetSchema: Codable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) - try container.encodeIfPresent(locale, forKey: .locale) try container.encode(stopwords, forKey: .stopwords) + try container.encodeIfPresent(locale, forKey: .locale) } } diff --git a/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift b/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift index 8a99a4c..0047722 100644 --- a/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift +++ b/Sources/Typesense/Models/StopwordsSetUpsertSchema.swift @@ -12,24 +12,24 @@ import AnyCodable public struct StopwordsSetUpsertSchema: Codable { - public var locale: String? public var stopwords: [String] + public var locale: String? public init(stopwords: [String], locale: String? = nil) { - self.locale = locale self.stopwords = stopwords + self.locale = locale } public enum CodingKeys: String, CodingKey, CaseIterable { - case locale case stopwords + case locale } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encodeIfPresent(locale, forKey: .locale) try container.encode(stopwords, forKey: .stopwords) + try container.encodeIfPresent(locale, forKey: .locale) } } diff --git a/Sources/Typesense/Models/SynonymItemSchema.swift b/Sources/Typesense/Models/SynonymItemSchema.swift index 4aadd59..13a48e8 100644 --- a/Sources/Typesense/Models/SynonymItemSchema.swift +++ b/Sources/Typesense/Models/SynonymItemSchema.swift @@ -12,41 +12,41 @@ import AnyCodable public struct SynonymItemSchema: Codable { - /** Unique identifier for the synonym item */ - public var id: String - /** Locale for the synonym, leave blank to use the standard tokenizer */ - public var locale: String? + /** Array of words that should be considered as synonyms */ + public var synonyms: [String] /** For 1-way synonyms, indicates the root word that words in the synonyms parameter map to */ public var root: String? + /** Locale for the synonym, leave blank to use the standard tokenizer */ + public var locale: String? /** By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is */ public var symbolsToIndex: [String]? - /** Array of words that should be considered as synonyms */ - public var synonyms: [String] + /** Unique identifier for the synonym item */ + public var id: String - public init(id: String, synonyms: [String], locale: String? = nil, root: String? = nil, symbolsToIndex: [String]? = nil) { - self.id = id - self.locale = locale + public init(synonyms: [String], id: String, root: String? = nil, locale: String? = nil, symbolsToIndex: [String]? = nil) { + self.synonyms = synonyms self.root = root + self.locale = locale self.symbolsToIndex = symbolsToIndex - self.synonyms = synonyms + self.id = id } public enum CodingKeys: String, CodingKey, CaseIterable { - case id - case locale + case synonyms case root + case locale case symbolsToIndex = "symbols_to_index" - case synonyms + case id } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(id, forKey: .id) - try container.encodeIfPresent(locale, forKey: .locale) + try container.encode(synonyms, forKey: .synonyms) try container.encodeIfPresent(root, forKey: .root) + try container.encodeIfPresent(locale, forKey: .locale) try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) - try container.encode(synonyms, forKey: .synonyms) + try container.encode(id, forKey: .id) } } diff --git a/Sources/Typesense/Models/SynonymItemUpsertSchema.swift b/Sources/Typesense/Models/SynonymItemUpsertSchema.swift new file mode 100644 index 0000000..1805f60 --- /dev/null +++ b/Sources/Typesense/Models/SynonymItemUpsertSchema.swift @@ -0,0 +1,47 @@ +// +// SynonymItemUpsertSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SynonymItemUpsertSchema: Codable { + + /** Array of words that should be considered as synonyms */ + public var synonyms: [String] + /** For 1-way synonyms, indicates the root word that words in the synonyms parameter map to */ + public var root: String? + /** Locale for the synonym, leave blank to use the standard tokenizer */ + public var locale: String? + /** By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is */ + public var symbolsToIndex: [String]? + + public init(synonyms: [String], root: String? = nil, locale: String? = nil, symbolsToIndex: [String]? = nil) { + self.synonyms = synonyms + self.root = root + self.locale = locale + self.symbolsToIndex = symbolsToIndex + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case synonyms + case root + case locale + case symbolsToIndex = "symbols_to_index" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(synonyms, forKey: .synonyms) + try container.encodeIfPresent(root, forKey: .root) + try container.encodeIfPresent(locale, forKey: .locale) + try container.encodeIfPresent(symbolsToIndex, forKey: .symbolsToIndex) + } +} diff --git a/Tasks/AddVendorAttributes.swift b/Tasks/AddVendorAttributes.swift index e31d46b..22265d0 100644 --- a/Tasks/AddVendorAttributes.swift +++ b/Tasks/AddVendorAttributes.swift @@ -1,4 +1,6 @@ -func addVendorAttributes(_ doc: inout [String: Any]) throws { +import Yams + +func addVendorAttributes(_ doc: inout Node) throws { print("Adding custom x-* vendor attributes...") let attrs = VendorAttributes(doc: doc) @@ -38,4 +40,4 @@ func addVendorAttributes(_ doc: inout [String: Any]) throws { // Save changes back to the inout parameter doc = attrs.doc -} +} \ No newline at end of file diff --git a/Tasks/PreprocessOpenAPI.swift b/Tasks/PreprocessOpenAPI.swift index 0b3dc8c..752da91 100644 --- a/Tasks/PreprocessOpenAPI.swift +++ b/Tasks/PreprocessOpenAPI.swift @@ -3,16 +3,13 @@ import Yams struct PreprocessOpenAPI { - // Typealias for our Generic JSON/YAML object - typealias Node = [String: Any] - static func process(input: String, output: String) throws { print("Reading OpenAPI spec from \(input)...") let yamlString = try String(contentsOfFile: input, encoding: .utf8) - // Load as a Generic Dictionary - guard var doc = try Yams.load(yaml: yamlString) as? Node else { - throw StringError("Failed to parse YAML as a dictionary") + // Use compose to load as a Node tree (preserves order) + guard var doc = try Yams.compose(yaml: yamlString) else { + throw StringError("Failed to parse YAML as a Node tree") } print("Preprocessing the spec...") @@ -20,26 +17,21 @@ struct PreprocessOpenAPI { // Create Models from URL Parameters try createUrlParamsSchema(&doc, name: "AnalyticsEventsRetrieveParams", path: "/analytics/events", method: "get") - // Add Vendor Attributes - try addVendorAttributes(&doc) - // Unwrap Parameters try unwrapParametersByPath(&doc, path: "/collections/{collectionName}/documents/import", method: "post", paramName: "importDocumentsParameters", newComponentName: "ImportDocumentsParameters") - try unwrapParametersByPath(&doc, path: "/collections/{collectionName}/documents/export", method: "get", paramName: "exportDocumentsParameters", newComponentName: "ExportDocumentsParameters") - try unwrapParametersByPath(&doc, path: "/collections/{collectionName}/documents", method: "patch", paramName: "updateDocumentsParameters", newComponentName: "UpdateDocumentsParameters") - try unwrapParametersByPath(&doc, path: "/collections/{collectionName}/documents", method: "delete", paramName: "deleteDocumentsParameters", newComponentName: "DeleteDocumentsParameters") - try unwrapParametersByPath(&doc, path: "/collections", method: "get", paramName: "getCollectionsParameters", newComponentName: "GetCollectionsParameters") try unwrapSearchParameters(&doc) try unwrapMultiSearchParameters(&doc) + try addVendorAttributes(&doc) print("Writing processed spec to \(output)...") - let outputYaml = try Yams.dump(object: doc) + + let outputYaml = try Yams.serialize(node: doc) try outputYaml.write(toFile: output, atomically: true, encoding: .utf8) print("Successfully created \(output).") } @@ -48,115 +40,116 @@ struct PreprocessOpenAPI { static func unwrapParametersByPath(_ doc: inout Node, path: String, method: String, paramName: String, newComponentName: String?) throws { - // Navigate to Paths -> Path -> Method -> Parameters - guard var paths = doc["paths"] as? Node, - var pathItem = paths[path] as? Node, - var operation = pathItem[method] as? Node, - var parameters = operation["parameters"] as? [Node] else { - // Path might not exist, simply return or log warning + guard var paths = doc["paths"], + var pathItem = paths[path], + var operation = pathItem[method], + let paramsNode = operation["parameters"] else { print("Warning: Could not find parameters for \(method) \(path)") return } - // Find the parameter to unwrap - guard let index = parameters.firstIndex(where: { ($0["name"] as? String) == paramName }), - let paramObject = parameters[index] as Node? else { + var parameters = paramsNode.array() + + guard let index = parameters.firstIndex(where: { $0["name"]?.string == paramName }) else { throw StringError("Parameter '\(paramName)' not found in \(path)") } - // Extract Schema - guard let schema = paramObject["schema"] as? Node, - let properties = schema["properties"] as? Node else { + let paramObject = parameters[index] + + guard let schema = paramObject["schema"], + let propertiesNode = schema["properties"] else { throw StringError("Could not extract properties from '\(paramName)'") } - // Copy to Components (Optional) if let compName = newComponentName { print("- Copying inline schema for '\(paramName)' to components.schemas.\(compName)...") - var components = doc["components"] as? Node ?? [:] - var schemas = components["schemas"] as? Node ?? [:] - schemas[compName] = schema - components["schemas"] = schemas - doc["components"] = components + + if doc["components"] == nil { + doc["components"] = Node([] as [(Node, Node)], .implicit, Node.Mapping.Style.any) + } + if doc["components"]?["schemas"] == nil { + doc["components"]?["schemas"] = Node([] as [(Node, Node)], .implicit, Node.Mapping.Style.any) + } + + doc["components"]?["schemas"]?[compName] = schema } print("- Unwrapping parameter object '\(paramName)'...") - // Remove the object parameter parameters.remove(at: index) - // Add flattened properties - for (key, value) in properties { - let newParam: Node = [ - "name": key, - "in": "query", - "schema": value - ] - parameters.append(newParam) + if case let .mapping(propertiesMapping) = propertiesNode { + for pair in propertiesMapping { + let newParamPairs: [(Node, Node)] = [ + (Node("name"), pair.key), + (Node("in"), Node("query")), + (Node("schema"), pair.value) + ] + + let newParam = Node(newParamPairs, .implicit, Node.Mapping.Style.any) + parameters.append(newParam) + } } - // Save back up the tree - operation["parameters"] = parameters + operation["parameters"] = Node(parameters, .implicit, Node.Sequence.Style.any) + pathItem[method] = operation paths[path] = pathItem doc["paths"] = paths } static func unwrapSearchParameters(_ doc: inout Node) throws { - // Reusing the generic logic to modify the Search path - - guard let components = doc["components"] as? Node, - let schemas = components["schemas"] as? Node, - let searchParams = schemas["SearchParameters"] as? Node, - let properties = searchParams["properties"] as? Node else { + guard let components = doc["components"], + let schemas = components["schemas"], + let searchParams = schemas["SearchParameters"], + let properties = searchParams["properties"] else { throw StringError("Could not find schema for SearchParameters") } - let path = "/collections/{collectionName}/documents/search" - let method = "get" - - try injectPropertiesAsParams(&doc, path: path, method: method, removeParam: "searchParameters", properties: properties) + try injectPropertiesAsParams(&doc, path: "/collections/{collectionName}/documents/search", method: "get", removeParam: "searchParameters", properties: properties) } static func unwrapMultiSearchParameters(_ doc: inout Node) throws { - guard let components = doc["components"] as? Node, - let schemas = components["schemas"] as? Node, - let searchParams = schemas["MultiSearchParameters"] as? Node, - let properties = searchParams["properties"] as? Node else { + guard let components = doc["components"], + let schemas = components["schemas"], + let searchParams = schemas["MultiSearchParameters"], + let properties = searchParams["properties"] else { throw StringError("Could not find schema for MultiSearchParameters") } - let path = "/multi_search" - let method = "post" - - try injectPropertiesAsParams(&doc, path: path, method: method, removeParam: "multiSearchParameters", properties: properties) + try injectPropertiesAsParams(&doc, path: "/multi_search", method: "post", removeParam: "multiSearchParameters", properties: properties) } // Helper for the search/multi-search unwrap static func injectPropertiesAsParams(_ doc: inout Node, path: String, method: String, removeParam: String, properties: Node) throws { print("- Unwrapping \(removeParam)...") - guard var paths = doc["paths"] as? Node, - var pathItem = paths[path] as? Node, - var operation = pathItem[method] as? Node, - var parameters = operation["parameters"] as? [Node] else { + guard var paths = doc["paths"], + var pathItem = paths[path], + var operation = pathItem[method], + let paramsNode = operation["parameters"] else { return } - if let idx = parameters.firstIndex(where: { ($0["name"] as? String) == removeParam }) { + var parameters = paramsNode.array() + + if let idx = parameters.firstIndex(where: { $0["name"]?.string == removeParam }) { parameters.remove(at: idx) } - for (key, value) in properties { - let newParam: Node = [ - "name": key, - "in": "query", - "schema": value - ] - parameters.append(newParam) + if case let .mapping(propertiesMapping) = properties { + for pair in propertiesMapping { + let newParamPairs: [(Node, Node)] = [ + (Node("name"), pair.key), + (Node("in"), Node("query")), + (Node("schema"), pair.value) + ] + let newParam = Node(newParamPairs, .implicit, Node.Mapping.Style.any) + parameters.append(newParam) + } } - operation["parameters"] = parameters + operation["parameters"] = Node(parameters, .implicit, Node.Sequence.Style.any) pathItem[method] = operation paths[path] = pathItem doc["paths"] = paths @@ -166,76 +159,86 @@ struct PreprocessOpenAPI { static func createUrlParamsSchema(_ doc: inout Node, name: String, path: String, method: String) throws { print("- Extracting URL params from \(method.uppercased()) \(path) into schema '\(name)'...") - // Navigate to Paths -> Path -> Method -> Parameters - guard let paths = doc["paths"] as? Node, - let pathItem = paths[path] as? Node, - let operation = pathItem[method] as? Node, - let parameters = operation["parameters"] as? [Node] else { + guard let paths = doc["paths"], + let pathItem = paths[path], + let operation = pathItem[method], + let paramsNode = operation["parameters"] else { print("⚠️ Warning: Path or operation not found: \(method) \(path)") return } - var properties: Node = [:] + let parameters = paramsNode.array() + + var propertiesMap: [(Node, Node)] = [] var requiredFields: [String] = [] - // Iterate over parameters for param in parameters { - // We only care about query parameters - guard let inLoc = param["in"] as? String, inLoc == "query", - let paramName = param["name"] as? String, - let schema = param["schema"] as? Node else { + guard param["in"]?.string == "query", + let paramName = param["name"]?.string, + let schema = param["schema"] else { continue } - // Build the property definition - var propertyDef = schema + // Copy schema properties + var propertyDefPairs: [(Node, Node)] = [] - // Copy description - if let description = param["description"] as? String { - propertyDef["description"] = description + if case let .mapping(mapping) = schema { + for pair in mapping { + propertyDefPairs.append((pair.key, pair.value)) + } + } + + // Add/Update description + if let description = param["description"] { + // Remove existing description if present to avoid duplicate keys in mapping + propertyDefPairs.removeAll(where: { $0.0.string == "description" }) + propertyDefPairs.append((Node("description"), description)) } // Copy custom x-swift-type if it exists on the param level if let customType = param["x-swift-type"] { - propertyDef["x-swift-type"] = customType + propertyDefPairs.append((Node("x-swift-type"), customType)) } - properties[paramName] = propertyDef + let propertyDef = Node(propertyDefPairs, .implicit, Node.Mapping.Style.any) - // Handle Required Status - // OpenAPI Params use "required: true", JSON Schema uses a "required" array - if let isRequired = param["required"] as? Bool, isRequired { + propertiesMap.append((Node(paramName), propertyDef)) + + if param["required"]?.bool == true { requiredFields.append(paramName) } } - if properties.isEmpty { + if propertiesMap.isEmpty { print("⚠️ No query parameters found for \(name). Skipping.") return } - // Construct the new Schema Object - var newSchema: Node = [ - "type": "object", - "properties": properties + let propertiesNode = Node(propertiesMap, .implicit, Node.Mapping.Style.any) + + var schemaMap: [(Node, Node)] = [ + (Node("type"), Node("object")), + (Node("properties"), propertiesNode) ] if !requiredFields.isEmpty { - newSchema["required"] = requiredFields + let requiredNodes = requiredFields.map { Node($0) } + schemaMap.append((Node("required"), Node(requiredNodes, .implicit, Node.Sequence.Style.any))) } - // Inject into components.schemas - var components = doc["components"] as? Node ?? [:] - var schemas = components["schemas"] as? Node ?? [:] + let newSchema = Node(schemaMap, .implicit, Node.Mapping.Style.any) - schemas[name] = newSchema + if doc["components"] == nil { + doc["components"] = Node([] as [(Node, Node)], .implicit, Node.Mapping.Style.any) + } + if doc["components"]?["schemas"] == nil { + doc["components"]?["schemas"] = Node([] as [(Node, Node)], .implicit, Node.Mapping.Style.any) + } - components["schemas"] = schemas - doc["components"] = components + doc["components"]?["schemas"]?[name] = newSchema - print(" ✅ Created schema '\(name)' with \(properties.count) properties.") + print(" ✅ Created schema '\(name)' with \(propertiesMap.count) properties.") } - } struct StringError: Error, CustomStringConvertible { diff --git a/Tasks/VendorAttributes.swift b/Tasks/VendorAttributes.swift index df5be9d..c51cc12 100644 --- a/Tasks/VendorAttributes.swift +++ b/Tasks/VendorAttributes.swift @@ -1,71 +1,62 @@ import Foundation import Yams -/// Helper class to manipulate the nested Dictionary structure class VendorAttributes { - var doc: [String: Any] + var doc: Node - // Quick accessors for Components -> Schemas - var schemas: [String: Any] { - get { - guard let components = doc["components"] as? [String: Any], - let schemas = components["schemas"] as? [String: Any] else { - return [:] - } - return schemas - } - set { - var components = doc["components"] as? [String: Any] ?? [:] - components["schemas"] = newValue - doc["components"] = components - } - } - - init(doc: [String: Any]) { + init(doc: Node) { self.doc = doc } /// Helper to modify a specific schema in place - private func modifySchema(_ name: String, closure: (inout [String: Any]) -> Void) throws { - var currentSchemas = self.schemas + private func modifySchema(_ name: String, closure: (inout Node) -> Void) throws { + guard var components = doc["components"], + var schemas = components["schemas"] else { + return + } - guard var schema = currentSchemas[name] as? [String: Any] else { + guard var schema = schemas[name] else { throw StringError( "Schema not found: \(name)") } closure(&schema) - currentSchemas[name] = schema - self.schemas = currentSchemas + // Write back up the tree + schemas[name] = schema + components["schemas"] = schemas + doc["components"] = components } /// Adds x-swift-generic-parameter to the schema func schemaGenericParameter(_ items: [(String, String)]) throws { for (schemaName, generic) in items { try modifySchema(schemaName) { schema in - schema["x-swift-generic-parameter"] = generic + schema["x-swift-generic-parameter"] = Node(generic) } } } - /// Overrides field types in a schema + /// Overrides field types in a schema "x-swift-type" func schemaFieldTypeOverrides(schema: String, overrides: [(String, String)]) throws { - try modifySchema(schema) { schemaDict in - var properties = schemaDict["properties"] as? [String: Any] ?? [:] + try modifySchema(schema) { schemaNode in + guard var properties = schemaNode["properties"] else { return } for (field, swiftType) in overrides { - if var existingProp = properties[field] as? [String: Any] { + if var existingProp = properties[field] { // Update existing - existingProp["x-swift-type"] = swiftType + existingProp["x-swift-type"] = Node(swiftType) properties[field] = existingProp } else { - // Create new if missing - let newProp: [String: Any] = ["x-swift-type": swiftType] + // Create new + let newPropPairs: [(Node, Node)] = [ + (Node("x-swift-type"), Node(swiftType)) + ] + let newProp = Node(newPropPairs, .implicit, Node.Mapping.Style.any) properties[field] = newProp } } - schemaDict["properties"] = properties + schemaNode["properties"] = properties } } -} +} \ No newline at end of file diff --git a/Tasks/main.swift b/Tasks/main.swift index d585630..835731b 100644 --- a/Tasks/main.swift +++ b/Tasks/main.swift @@ -88,6 +88,22 @@ struct CodeGen: ParsableCommand { try Shell.run("mv", args: [tempModelsPath, finalDestination]) + print("Deleting unused models...") + let unusedModels = [ + "CreateAnalyticsRule200Response", + "CreateAnalyticsRule200ResponseOneOfInner", + "CreateAnalyticsRuleRequest", + "CreateAnalyticsRule200ResponseOneOfInnerOneOf" + ] + + for model in unusedModels { + let modelPath = "\(finalModelsPath)/\(model).swift" + if fileManager.fileExists(atPath: modelPath) { + try fileManager.removeItem(atPath: modelPath) + print(" - Deleted \(model)") + } + } + print("✅ Codegen and file movement finished successfully.") } } diff --git a/openapi.yml b/openapi.yml index e1a279d..3db4b12 100644 --- a/openapi.yml +++ b/openapi.yml @@ -495,14 +495,14 @@ paths: content: application/json: schema: - $ref: "#/components/schemas/SynonymSetRetrieveSchema" + $ref: "#/components/schemas/SynonymSetSchema" "404": description: Synonym set not found content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - + put: tags: - synonyms @@ -650,7 +650,7 @@ paths: content: application/json: schema: - $ref: "#/components/schemas/SynonymItemSchema" + $ref: "#/components/schemas/SynonymItemUpsertSchema" required: true responses: "200": @@ -735,7 +735,7 @@ paths: content: application/json: schema: - $ref: "#/components/schemas/CurationSetRetrieveSchema" + $ref: "#/components/schemas/CurationSetSchema" "404": description: Curation set not found content: @@ -1647,7 +1647,7 @@ paths: {"log-slow-requests-time-ms": 2000} responses: '200': - description: Compacting the on-disk database succeeded. + description: Toggle Slow Request Log database succeeded. content: application/json: schema: @@ -1805,7 +1805,7 @@ paths: - $ref: "#/components/schemas/AnalyticsRule" - type: array items: - anyOf: + oneOf: - $ref: "#/components/schemas/AnalyticsRule" - type: object properties: @@ -3975,8 +3975,7 @@ components: name: type: string type: - type: string - enum: [popular_queries, nohits_queries, counter, log] + $ref: "#/components/schemas/AnalyticsRuleType" collection: type: string event_type: @@ -4001,6 +4000,9 @@ components: type: string weight: type: integer + AnalyticsRuleType: + type: string + enum: [popular_queries, nohits_queries, counter, log] AnalyticsRuleUpdate: type: object description: Fields allowed to update on an analytics rule @@ -4041,7 +4043,7 @@ components: query_counter_events: { type: integer } doc_log_events: { type: integer } doc_counter_events: { type: integer } - + APIStatsResponse: type: object properties: @@ -4364,15 +4366,11 @@ components: type: string description: ID of the deleted NL search model - SynonymItemSchema: + SynonymItemUpsertSchema: type: object required: - - id - synonyms properties: - id: - type: string - description: Unique identifier for the synonym item synonyms: type: array description: Array of words that should be considered as synonyms @@ -4390,6 +4388,17 @@ components: items: type: string + SynonymItemSchema: + allOf: + - type: object + required: + - id + properties: + id: + type: string + description: Unique identifier for the synonym item + - $ref: "#/components/schemas/SynonymItemUpsertSchema" + SynonymSetCreateSchema: type: object required: @@ -4423,8 +4432,6 @@ components: items: $ref: "#/components/schemas/SynonymSetSchema" - SynonymSetRetrieveSchema: - $ref: "#/components/schemas/SynonymSetCreateSchema" SynonymSetDeleteSchema: type: object @@ -4586,9 +4593,6 @@ components: type: string description: document id that should be excluded from the search results. - CurationSetRetrieveSchema: - $ref: '#/components/schemas/CurationSetCreateSchema' - CurationSetDeleteSchema: type: object required: diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml index 6b184c3..ec5150f 100644 --- a/preprocessed_openapi.yml +++ b/preprocessed_openapi.yml @@ -1,1779 +1,2194 @@ -components: - schemas: - APIStatsResponse: - properties: - delete_latency_ms: - format: double - type: number - delete_requests_per_second: - format: double - type: number - import_latency_ms: - format: double - type: number - import_requests_per_second: - format: double - type: number - latency_ms: - type: object - x-go-type: map[string]float64 - overloaded_requests_per_second: - format: double - type: number - pending_write_batches: - format: double - type: number - requests_per_second: - type: object - x-go-type: map[string]float64 - search_latency_ms: - format: double - type: number - search_requests_per_second: - format: double - type: number - total_requests_per_second: - format: double - type: number - write_latency_ms: - format: double - type: number - write_requests_per_second: - format: double - type: number - type: object - AnalyticsEvent: - properties: - data: - description: Event payload - properties: - analytics_tag: - type: string - doc_id: - type: string - doc_ids: - items: - type: string - type: array - q: - type: string - user_id: - type: string - type: object - event_type: - description: Type of event (e.g., click, conversion, query, visit) - type: string - name: - description: Name of the analytics rule this event corresponds to - type: string - required: - - name - - event_type - - data - type: object - AnalyticsEventCreateResponse: - properties: - ok: - type: boolean - required: - - ok - type: object - AnalyticsEventsResponse: - properties: - events: - items: - properties: - collection: - type: string - doc_id: - type: string - doc_ids: - items: - type: string - type: array - event_type: - type: string - name: - type: string - query: - type: string - timestamp: - format: int64 - type: integer - user_id: - type: string - type: object - type: array - required: - - events - type: object - AnalyticsEventsRetrieveParams: - properties: - n: - description: Number of events to return (max 1000) - type: integer - name: - description: Analytics rule name - type: string - user_id: - type: string - required: - - user_id - - name - - n - type: object - AnalyticsRule: - allOf: - - $ref: '#/components/schemas/AnalyticsRuleCreate' - - type: object - AnalyticsRuleCreate: - properties: - collection: - type: string - event_type: - type: string - name: - type: string - params: - properties: - capture_search_requests: - type: boolean - counter_field: - type: string - destination_collection: - type: string - expand_query: - type: boolean - limit: - type: integer - meta_fields: - items: - type: string - type: array - weight: - type: integer - type: object - rule_tag: - type: string - type: - enum: - - popular_queries - - nohits_queries - - counter - - log - type: string - required: - - name - - type - - collection - - event_type - type: object - AnalyticsRuleUpdate: - description: Fields allowed to update on an analytics rule - properties: - name: - type: string - params: - properties: - capture_search_requests: - type: boolean - counter_field: - type: string - destination_collection: - type: string - expand_query: - type: boolean - limit: - type: integer - meta_fields: - items: - type: string - type: array - weight: - type: integer - type: object - rule_tag: - type: string - type: object - AnalyticsStatus: - properties: - doc_counter_events: - type: integer - doc_log_events: - type: integer - log_prefix_queries: - type: integer - nohits_prefix_queries: - type: integer - popular_prefix_queries: - type: integer - query_counter_events: - type: integer - query_log_events: - type: integer - type: object - ApiKey: - allOf: - - $ref: '#/components/schemas/ApiKeySchema' - - properties: - id: - format: int64 - readOnly: true - type: integer - value_prefix: - readOnly: true - type: string - type: object - ApiKeyDeleteResponse: - properties: - id: - description: The id of the API key that was deleted - format: int64 - type: integer - required: - - id - type: object - ApiKeySchema: - properties: - actions: - items: - type: string - type: array - collections: - items: - type: string - type: array - description: - type: string - expires_at: - format: int64 - type: integer - value: - type: string - required: - - actions +openapi: 3.0.3 +info: + title: Typesense API + description: "An open source search engine for building delightful search experiences." + version: '30.0' + license: + name: GPL-3.0 + url: https://opensource.org/licenses/GPL-3.0 +servers: +- url: "{protocol}://{hostname}:{port}" + description: Typesense Server + variables: + protocol: + default: http + description: The protocol of your Typesense server + hostname: + default: localhost + description: The hostname of your Typesense server + port: + default: "8108" + description: The port of your Typesense server +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: 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: curation_sets + description: Manage curation sets +- 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 - - description - type: object - ApiKeysResponse: - properties: - keys: - items: - $ref: '#/components/schemas/ApiKey' - type: array - x-go-type: '[]*ApiKey' - required: - - keys - type: object - ApiResponse: - properties: - message: - type: string - required: - - message - type: object - CollectionAlias: - properties: - collection_name: - description: Name of the collection the alias mapped to - type: string - name: - description: Name of the collection alias - readOnly: true - type: string - required: - - collection_name - - name - type: object - CollectionAliasSchema: - properties: - collection_name: - description: Name of the collection you wish to map the alias to - type: string - required: - - collection_name - type: object - CollectionAliasesResponse: - properties: - aliases: - items: - $ref: '#/components/schemas/CollectionAlias' - type: array - x-go-type: '[]*CollectionAlias' - required: - - aliases - type: object - CollectionResponse: - allOf: - - $ref: '#/components/schemas/CollectionSchema' - - properties: - created_at: - description: Timestamp of when the collection was created (Unix epoch - in seconds) - format: int64 - readOnly: true - type: integer - num_documents: - description: Number of documents in the collection - format: int64 - readOnly: true - type: integer - required: - - num_documents - - created_at - type: object - CollectionSchema: - properties: - default_sorting_field: - default: '' - 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 - type: string - enable_nested_fields: - default: false - 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. - example: true - type: boolean - fields: - description: A list of fields for querying, filtering and faceting - example: - - facet: false - name: num_employees - type: int32 - - facet: false - name: company_name - type: string - - facet: true - name: country - type: string - items: - $ref: '#/components/schemas/Field' - type: array - metadata: - description: 'Optional details about the collection, e.g., when it was created, - who created it etc. - - ' - type: object - name: - description: Name of the collection - example: companies - type: string - symbols_to_index: - default: [] - description: 'List of symbols or special characters to be indexed. - - ' - items: - maxLength: 1 - minLength: 1 - type: string - type: array - synonym_sets: - description: List of synonym set names to associate with this collection - items: - example: synonym_set_1 - type: string - type: array - token_separators: - default: [] - 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: - maxLength: 1 - minLength: 1 - type: string - type: array - voice_query_model: - $ref: '#/components/schemas/VoiceQueryModelCollectionConfig' - required: - - name - - fields - type: object - CollectionUpdateSchema: - properties: - fields: - description: A list of fields for querying, filtering and faceting - example: - - facet: false - name: company_name - type: string - - facet: false - name: num_employees - type: int32 - - facet: true - name: country - type: string - items: - $ref: '#/components/schemas/Field' - type: array - metadata: - description: 'Optional details about the collection, e.g., when it was created, - who created it etc. - - ' - type: object - synonym_sets: - description: List of synonym set names to associate with this collection - items: - example: synonym_set_1 - type: string - type: array - required: - - fields - type: object - ConversationModelCreateSchema: - allOf: - - $ref: '#/components/schemas/ConversationModelUpdateSchema' - - properties: - history_collection: - description: Typesense collection that stores the historical conversations - 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 - model_name: - description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM - type: string - required: - - model_name - - max_bytes - - history_collection - type: object - required: - - model_name - - max_bytes - ConversationModelSchema: - allOf: - - $ref: '#/components/schemas/ConversationModelCreateSchema' - - properties: - id: - description: An explicit id for the model, otherwise the API will return - a response with an auto-generated conversation model id. - type: string - required: - - id - type: object - ConversationModelUpdateSchema: - properties: - account_id: - description: LLM service's account ID (only applicable for Cloudflare) - type: string - api_key: - description: The LLM service's API Key - type: string - history_collection: - description: Typesense collection that stores the historical conversations - type: string - id: - description: An explicit id for the model, otherwise the API will return - a response with an auto-generated conversation model id. - 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 - model_name: - description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM - type: string - system_prompt: - description: The system prompt that contains special instructions to the - LLM - type: string - ttl: - description: 'Time interval in seconds after which the messages would be - deleted. Default: 86400 (24 hours) - - ' - type: integer - vllm_url: - description: URL of vLLM service - type: string - type: object - CurationExclude: - properties: - id: - description: document id that should be excluded from the search results. - type: string - required: - - id - type: object - CurationInclude: - properties: - id: - description: document id that should be included - type: string - position: - description: position number where document should be included in the search - results - type: integer - required: - - id - - position - type: object - CurationItemCreateSchema: - properties: - effective_from_ts: - description: 'A Unix timestamp that indicates the date/time from which the - curation will be active. You can use this to create rules that start applying - from a future point in time. - - ' + 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 + parameters: + - name: exclude_fields + in: query + schema: + description: Comma-separated list of fields from the collection to exclude + from the response + type: string + - name: limit + in: query + schema: + description: > + Number of collections to fetch. Default: returns all collections. type: integer - effective_to_ts: - description: 'A Unix timestamp that indicates the date/time until which - the curation will be active. You can use this to create rules that stop - applying after a period of time. - - ' + - name: offset + in: query + schema: + description: Identifies the starting point to return collections when paginating. type: integer - excludes: - description: List of document `id`s that should be excluded from the search - results. - items: - $ref: '#/components/schemas/CurationExclude' - type: array - filter_by: - description: 'A filter by clause that is applied to any search query that - matches the curation rule. - - ' - type: string - filter_curated_hits: - description: 'When set to true, the filter conditions of the query is applied - to the curated records as well. Default: false. - - ' - type: boolean - id: - description: ID of the curation item + 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 - includes: - description: List of document `id`s that should be included in the search - results with their corresponding `position`s. - items: - $ref: '#/components/schemas/CurationInclude' - type: array - metadata: - 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. - - ' - type: object - remove_matched_tokens: - description: 'Indicates whether search query tokens that exist in the curation''s - rule should be removed from the search query. - - ' - type: boolean - replace_query: - description: 'Replaces the current search query with this value, when the - search query matches the curation rule. - - ' + 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 - rule: - $ref: '#/components/schemas/CurationRule' - sort_by: - description: 'A sort by clause that is applied to any search query that - matches the curation rule. - - ' + 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 - stop_processing: - description: 'When set to true, curation processing will stop at the first - matching rule. When set to false curation processing will continue and - multiple curation actions will be triggered in sequence. Curations are - processed in the lexical sort order of their id field. - - ' - type: boolean - required: - - rule - type: object - CurationItemDeleteSchema: - properties: - id: - description: ID of the deleted curation item + 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 - required: - - id - type: object - CurationItemSchema: - allOf: - - $ref: '#/components/schemas/CurationItemCreateSchema' - - properties: - id: - type: string - required: - - id - type: object - CurationRule: - properties: - filter_by: - description: 'Indicates that the curation should apply when the filter_by - parameter in a search query exactly matches the string specified here - (including backticks, spaces, brackets, etc). - - ' + - name: action + in: query + description: Additional action to perform + schema: type: string - match: - 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 + 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 - query: - description: Indicates what search queries should be curated + - name: filter_by + in: query + schema: type: string - tags: - description: List of tag values to associate with this curation rule. - items: - type: string - type: array - type: object - CurationSetCreateSchema: - properties: - description: - description: Optional description for the curation set + 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 - items: - description: Array of curation items - items: - $ref: '#/components/schemas/CurationItemCreateSchema' - type: array - required: - - items - type: object - CurationSetDeleteSchema: - properties: - name: - description: Name of the deleted curation set + - name: filter_by + in: query + schema: type: string - required: - - name - type: object - CurationSetRetrieveSchema: - $ref: '#/components/schemas/CurationSetCreateSchema' - CurationSetSchema: - allOf: - - $ref: '#/components/schemas/CurationSetCreateSchema' - - properties: - name: - type: string - required: - - name - type: object - DeleteDocumentsParameters: - properties: - batch_size: + 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 - filter_by: - example: 'num_employees:>100 && country: [USA, UK]' - type: string - ignore_not_found: + - name: ignore_not_found + in: query + schema: type: boolean - truncate: + - name: truncate + in: query + schema: description: When true, removes all documents from the collection while preserving the collection and its schema. type: boolean - required: - - filter_by - type: object - DirtyValues: - enum: - - coerce_or_reject - - coerce_or_drop - - drop - - reject - type: string - DropTokensMode: - 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 up to 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 - - ' - enum: - - right_to_left - - left_to_right - - both_sides:3 - type: string - ExportDocumentsParameters: - properties: - exclude_fields: - description: List of fields from the document to exclude in the search result - type: string - filter_by: - description: Filter conditions for refining your search results. Separate - multiple conditions with &&. + 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 - include_fields: - description: List of fields from the document to include in the search result + - 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 - type: object - FacetCounts: - properties: - counts: - items: - properties: - count: - type: integer - highlighted: - type: string - parent: - type: object - value: - type: string - type: object - type: array - field_name: + - 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 - stats: - properties: - avg: - format: double - type: number - max: - format: double - type: number - min: - format: double - type: number - sum: - format: double - type: number - total_values: - type: integer - type: object - type: object - Field: - properties: - drop: - example: true - type: boolean - embed: - properties: - from: - items: - type: string - type: array - model_config: - properties: - access_token: - type: string - api_key: - type: string - client_id: - type: string - client_secret: - type: string - indexing_prefix: - type: string - model_name: - type: string - project_id: - type: string - query_prefix: - type: string - refresh_token: - type: string - url: - type: string - required: - - model_name - type: object - required: - - from - - model_config - type: object - facet: - example: false - type: boolean - index: - default: true - example: true - type: boolean - infix: - default: false - example: true + - name: nl_query + in: query + schema: + description: Whether to use natural language processing to parse the query. type: boolean - locale: - example: el + - 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: - example: company_name + - 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 - num_dim: - example: 256 + - 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 - optional: - example: true - type: boolean - range_index: - description: 'Enables an index optimized for range filtering on numerical - fields (e.g. rating:>3.5). Default: false. - - ' - type: boolean - reference: - description: 'Name of a field in another collection that should be linked - to this collection so that it can be joined during query. - - ' + - 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 your open api validator search + results. Separate multiple conditions with &&. type: string - sort: - example: true - type: boolean - stem: - description: 'Values are stemmed before indexing in-memory. Default: false. - - ' - type: boolean - stem_dictionary: - description: Name of the stemming dictionary to use for this field - example: irregular-plurals + 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 - store: - description: 'When set to false, the field value will not be stored on disk. - Default: true. - - ' - type: boolean - symbols_to_index: - default: [] - description: 'List of symbols or special characters to be indexed. - - ' - items: - maxLength: 1 - minLength: 1 - type: string - type: array - token_separators: - default: [] - 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: - maxLength: 1 - minLength: 1 - type: string - type: array - type: - example: 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 - vec_dist: - description: 'The distance metric to be used for vector search. Default: - `cosine`. You can also use `ip` for inner product. - - ' + - 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 - required: - - name - - type - type: object - GetCollectionsParameters: - properties: - exclude_fields: - description: Comma-separated list of fields from the collection to exclude - from the response + - name: num_typos + in: query + schema: + description: > + The number of typographical errors (1 or 2) that would be tolerated. Default: + 2 type: string - limit: - description: 'Number of collections to fetch. Default: returns all collections. - - ' + - name: page + in: query + schema: + description: Results from this specific page number would be fetched. type: integer - offset: - description: Identifies the starting point to return collections when paginating. + - name: per_page + in: query + schema: + description: "Number of results to fetch per page. Default: 10" type: integer - type: object - HealthStatus: - properties: - ok: + - 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 - required: - - ok - type: object - ImportDocumentsParameters: - properties: - action: - $ref: '#/components/schemas/IndexAction' - batch_size: + - 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 - dirty_values: - $ref: '#/components/schemas/DirtyValues' - remote_embedding_batch_size: + - 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: enable_analytics + in: query + schema: + description: > + Flag for enabling/disabling analytics aggregation for specific search + queries (for e.g. those originating from a test script). + 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 - return_doc: + - name: synonym_sets + in: query + schema: + type: string + description: List of synonym set names to associate with this search query + example: "synonym_set_1,synonym_set_2" + - 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 - return_id: - 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. + description: > + Set this parameter to false to disable typos on alphanumerical query tokens. + Default: true. + - name: filter_curated_hits + in: query + schema: type: boolean - type: object - IndexAction: - enum: - - create - - update - - upsert - - emplace - type: string - MultiSearchCollectionParameters: - allOf: - - $ref: '#/components/schemas/MultiSearchParameters' - - properties: - collection: - description: 'The collection to search in. - - ' - type: string - rerank_hybrid_matches: - default: false - 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. - - ' - type: boolean - x-typesense-api-key: - description: A separate search API key for each search within a multi_search - request - type: string - type: object - MultiSearchParameters: - description: 'Parameters for the multi search API. - - ' - properties: - 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. - - ' + 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 - conversation: - description: 'Enable conversational search. + 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`. - ' - type: boolean - conversation_id: - description: 'The Id of a previous conversation to continue, this tells - Typesense to include prior context when communicating with the LLM. + 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 - conversation_model_id: - description: 'The Id of Conversation Model to be used. - - ' + - name: override_tags + in: query + schema: + description: Comma separated list of tags to trigger the curations rules + that match the tags. type: string - drop_tokens_mode: - $ref: '#/components/schemas/DropTokensMode' - 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 - enable_analytics: - default: true - description: 'Flag for enabling/disabling analytics aggregation for specific - search queries (for e.g. those originating from a test script). + - 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 - enable_overrides: default: false - 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 - - ' + - 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 - enable_synonyms: - 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 - - ' + 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 - enable_typos_for_alpha_numerical_tokens: - description: 'Set this parameter to false to disable typos on alphanumerical - query tokens. Default: true. - - ' + 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 - enable_typos_for_numerical_tokens: default: true - description: 'Make Typesense disable typos for numerical tokens. - - ' + - name: enable_typos_for_numerical_tokens + in: query + schema: + description: > + Make Typesense disable typos for numerical tokens. type: boolean - exclude_fields: - description: List of fields from the document to exclude in the search result - type: string - 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). - - ' + 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 - facet_by: - description: A list of fields that will be used for faceting your results - on. Separate multiple fields with a comma. - type: string - 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". + - 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 - facet_return_parent: - description: 'Comma separated string of nested facet fields whose parent - object should be returned in facet response. - - ' + - 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 - facet_strategy: - description: 'Choose the underlying faceting strategy used. Comma separated - string of allows values: exhaustive, top_values or automatic (default). - - ' + - 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 - filter_by: - description: Filter conditions for refining youropen api validator search - results. Separate multiple conditions with &&. - example: 'num_employees:>100 && country: [USA, UK]' + - 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 - filter_curated_hits: - 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 - - ' - type: boolean - 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. + - name: voice_query + in: query + schema: + description: > + The base64 encoded audio file in 16 khz 16-bit WAV format. 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 - - ' + - name: conversation + in: query + schema: + description: > + Enable conversational search. type: boolean - 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`. - - ' + - name: conversation_model_id + in: query + schema: + description: > + The Id of Conversation Model to be used. 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_end_tag: - description: 'The end tag used for the highlighted snippets. Default: `` - - ' + - 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 - highlight_fields: - description: 'A list of custom fields that must be highlighted even if you - don''t query for them - - ' + 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" + /synonym_sets: + get: + tags: + - synonyms + summary: List all synonym sets + description: Retrieve all synonym sets + operationId: retrieveSynonymSets + responses: + "200": + description: List of all synonym sets + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/SynonymSetSchema" + /synonym_sets/{synonymSetName}: + get: + tags: + - synonyms + summary: Retrieve a synonym set + description: Retrieve a specific synonym set by its name + operationId: retrieveSynonymSet + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to retrieve + required: true + schema: type: string - highlight_full_fields: - description: List of fields which should be highlighted fully without snippeting + responses: + "200": + description: Synonym set fetched + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymSetSchema" + "404": + description: Synonym set not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + put: + tags: + - synonyms + summary: Create or update a synonym set + description: Create or update a synonym set with the given name + operationId: upsertSynonymSet + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to create/update + required: true + schema: type: string - highlight_start_tag: - description: 'The start tag used for the highlighted snippets. Default: - `` - - ' + requestBody: + description: The synonym set to be created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymSetCreateSchema" + required: true + responses: + "200": + description: Synonym set successfully created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymSetSchema" + "400": + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + delete: + tags: + - synonyms + summary: Delete a synonym set + description: Delete a specific synonym set by its name + operationId: deleteSynonymSet + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to delete + required: true + schema: type: string - include_fields: - description: List of fields from the document to include in the search result + responses: + "200": + description: Synonym set successfully deleted + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymSetDeleteSchema" + "404": + description: Synonym set not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /synonym_sets/{synonymSetName}/items: + get: + tags: + - synonyms + summary: List items in a synonym set + description: Retrieve all synonym items in a set + operationId: retrieveSynonymSetItems + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to retrieve items for + required: true + schema: 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 + responses: + "200": + description: List of synonym items + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/SynonymItemSchema" + "404": + description: Synonym set not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /synonym_sets/{synonymSetName}/items/{itemId}: + get: + tags: + - synonyms + summary: Retrieve a synonym set item + description: Retrieve a specific synonym item by its id + operationId: retrieveSynonymSetItem + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set + required: true + schema: type: string - limit: - description: 'Number of hits to fetch. Can be used as an alternative to - the per_page parameter. Default: 10. - - ' - type: integer - 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 - max_facet_values: - description: Maximum number of facet values to be returned. - 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 - num_typos: - description: 'The number of typographical errors (1 or 2) that would be - tolerated. Default: 2 - - ' + - name: itemId + in: path + description: The id of the synonym item to retrieve + required: true + schema: type: string - 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 - override_tags: - description: Comma separated list of tags to trigger the curations rules - that match the tags. + responses: + "200": + description: Synonym item fetched + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymItemSchema" + "404": + description: Synonym item not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + put: + tags: + - synonyms + summary: Create or update a synonym set item + description: Create or update a synonym set item with the given id + operationId: upsertSynonymSetItem + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set + required: true + schema: 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 - 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`. - - ' + - name: itemId + in: path + description: The id of the synonym item to upsert + required: true + schema: type: string - pre_segmented_query: - default: false - 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 - 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. + requestBody: + description: The synonym item to be created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymItemUpsertSchema" + required: true + responses: + "200": + description: Synonym item successfully created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymItemSchema" + "400": + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + delete: + tags: + - synonyms + summary: Delete a synonym set item + description: Delete a specific synonym item by its id + operationId: deleteSynonymSetItem + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set + required: true + schema: type: string - preset: - description: 'Search using a bunch of search parameters by setting this - parameter to the name of the existing Preset. - - ' + - name: itemId + in: path + description: The id of the synonym item to delete + required: true + schema: type: string - prioritize_exact_match: - default: true - description: 'Set this parameter to true to ensure that an exact match is - ranked above the others - - ' - type: boolean - prioritize_num_matching_fields: - default: true - description: 'Make Typesense prioritize documents where the query words - appear in more number of fields. - - ' - type: boolean - prioritize_token_position: - default: false - description: 'Make Typesense prioritize documents where the query words - appear earlier in the text. - - ' - type: boolean - 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. + responses: + "200": + description: Synonym item successfully deleted + content: + application/json: + schema: + $ref: "#/components/schemas/SynonymItemDeleteSchema" + "404": + description: Synonym item not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /curation_sets: + get: + tags: + - curation_sets + summary: List all curation sets + description: Retrieve all curation sets + operationId: retrieveCurationSets + responses: + "200": + description: List of all curation sets + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/CurationSetSchema" + /curation_sets/{curationSetName}: + get: + tags: + - curation_sets + summary: Retrieve a curation set + description: Retrieve a specific curation set by its name + operationId: retrieveCurationSet + parameters: + - name: curationSetName + in: path + description: The name of the curation set to retrieve + required: true + schema: type: string - query_by: - description: A list of `string` fields that should be queried against. Multiple - fields are separated with a comma. + responses: + "200": + description: Curation set fetched + content: + application/json: + schema: + $ref: "#/components/schemas/CurationSetSchema" + "404": + description: Curation set not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + put: + tags: + - curation_sets + summary: Create or update a curation set + description: Create or update a curation set with the given name + operationId: upsertCurationSet + parameters: + - name: curationSetName + in: path + description: The name of the curation set to create/update + required: true + schema: 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. + requestBody: + description: The curation set to be created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/CurationSetCreateSchema" + required: true + responses: + "200": + description: Curation set successfully created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/CurationSetSchema" + "400": + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + delete: + tags: + - curation_sets + summary: Delete a curation set + description: Delete a specific curation set by its name + operationId: deleteCurationSet + parameters: + - name: curationSetName + in: path + description: The name of the curation set to delete + required: true + schema: type: string - remote_embedding_num_tries: - description: 'Number of times to retry fetching remote embeddings. - - ' - type: integer - remote_embedding_timeout_ms: - description: 'Timeout (in milliseconds) for fetching remote embeddings. - - ' - type: integer - 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 - snippet_threshold: - description: 'Field values under this length will be fully highlighted, - instead of showing a snippet of relevant portion. Default: 30 - - ' - 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` + responses: + "200": + description: Curation set successfully deleted + content: + application/json: + schema: + $ref: "#/components/schemas/CurationSetDeleteSchema" + "404": + description: Curation set not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /curation_sets/{curationSetName}/items: + get: + tags: + - curation_sets + summary: List items in a curation set + description: Retrieve all curation items in a set + operationId: retrieveCurationSetItems + parameters: + - name: curationSetName + in: path + description: The name of the curation set to retrieve items for + required: true + schema: 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. - - ' + responses: + "200": + description: List of curation items + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/CurationItemSchema" + "404": + description: Curation set not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /curation_sets/{curationSetName}/items/{itemId}: + get: + tags: + - curation_sets + summary: Retrieve a curation set item + description: Retrieve a specific curation item by its id + operationId: retrieveCurationSetItem + parameters: + - name: curationSetName + in: path + description: The name of the curation set + required: true + schema: type: string - synonym_num_typos: - description: 'Allow synonym resolution on typo-corrected words in the query. - Default: 0 - - ' - type: integer - synonym_prefix: - description: 'Allow synonym resolution on word prefixes in the query. Default: - false - - ' - type: boolean - 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. + - name: itemId + in: path + description: The id of the curation item to retrieve + required: true + schema: type: string - 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 - use_cache: - description: 'Enable server side caching of search query results. By default, - caching is disabled. - - ' - type: boolean - vector_query: - description: 'Vector query expression for fetching documents "closest" to - a given query/document vector. - - ' + responses: + "200": + description: Curation item fetched + content: + application/json: + schema: + $ref: "#/components/schemas/CurationItemSchema" + "404": + description: Curation item not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + put: + tags: + - curation_sets + summary: Create or update a curation set item + description: Create or update a curation set item with the given id + operationId: upsertCurationSetItem + parameters: + - name: curationSetName + in: path + description: The name of the curation set + required: true + schema: type: string - voice_query: - description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. - - ' + - name: itemId + in: path + description: The id of the curation item to upsert + required: true + schema: type: string - type: object - MultiSearchResult: - properties: - conversation: - $ref: '#/components/schemas/SearchResultConversation' - results: - items: - $ref: '#/components/schemas/MultiSearchResultItem' - type: array - x-swift-type: '[MultiSearchResultItem]' - required: - - results - type: object - x-swift-generic-parameter: 'T: Codable' - MultiSearchResultItem: - allOf: - - $ref: '#/components/schemas/SearchResult' - - properties: - code: - description: HTTP error code - format: int64 - type: integer - error: - description: Error description - type: string - type: object - x-swift-generic-parameter: 'T: Codable' - MultiSearchSearchesParameter: - properties: - searches: - items: - $ref: '#/components/schemas/MultiSearchCollectionParameters' - type: array - union: - default: false - description: When true, merges the search results from each search query - into a single ordered set of hits. - type: boolean - required: - - searches - type: object - NLSearchModelBase: - properties: - access_token: - description: Access token for GCP Vertex AI + requestBody: + description: The curation item to be created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/CurationItemCreateSchema" + required: true + responses: + "200": + description: Curation item successfully created/updated + content: + application/json: + schema: + $ref: "#/components/schemas/CurationItemSchema" + "400": + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + delete: + tags: + - curation_sets + summary: Delete a curation set item + description: Delete a specific curation item by its id + operationId: deleteCurationSetItem + parameters: + - name: curationSetName + in: path + description: The name of the curation set + required: true + schema: type: string - account_id: - description: Account ID for Cloudflare-specific models + - name: itemId + in: path + description: The id of the curation item to delete + required: true + schema: type: string - api_key: - description: API key for the NL model service + responses: + "200": + description: Curation item successfully deleted + content: + application/json: + schema: + $ref: "#/components/schemas/CurationItemDeleteSchema" + "404": + description: Curation item 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 - api_url: - description: Custom API URL for the NL model service + - name: filter_by + in: query + schema: + description: Filter conditions for refining your search results. Separate + multiple conditions with &&. type: string - api_version: - description: API version for the NL model service + - name: include_fields + in: query + schema: + description: List of fields from the document to include in the search result type: string - client_id: - description: Client ID for GCP Vertex AI + - name: exclude_fields + in: query + schema: + description: List of fields from the document to exclude in the search result type: string - client_secret: - description: Client secret for GCP Vertex AI + 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 - max_bytes: - description: Maximum number of bytes to process + - name: batch_size + in: query + schema: type: integer - max_output_tokens: - description: Maximum output tokens for GCP Vertex AI + - 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 - model_name: - description: Name of the NL model to use - type: string - project_id: - description: Project ID for GCP Vertex AI - type: string - refresh_token: - description: Refresh token for GCP Vertex AI + - 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: Retrieve 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 - region: - description: Region for GCP Vertex AI + - name: documentId + in: path + description: The Document ID + required: true + schema: type: string - stop_sequences: - description: Stop sequences for the NL model (Google-specific) - items: - type: string - type: array - system_prompt: - description: System prompt for the NL model + 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 - temperature: - description: Temperature parameter for the NL model - type: number - top_k: - description: Top-k parameter for the NL model (Google-specific) - type: integer - top_p: - description: Top-p parameter for the NL model (Google-specific) - type: number - type: object - NLSearchModelCreateSchema: - allOf: - - $ref: '#/components/schemas/NLSearchModelBase' - - properties: - id: - description: Optional ID for the NL search model - type: string - type: object - NLSearchModelDeleteSchema: - properties: - id: - description: ID of the deleted NL search model + - name: documentId + in: path + description: The Document ID + required: true + schema: type: string - required: - - id - type: object - NLSearchModelSchema: - allOf: - - $ref: '#/components/schemas/NLSearchModelCreateSchema' - - properties: - id: - description: ID of the NL search model - type: string - required: - - id - type: object - NLSearchModelUpdateSchema: - $ref: '#/components/schemas/NLSearchModelCreateSchema' - PresetDeleteSchema: - properties: - name: + - 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 - required: - - name - type: object - PresetSchema: - allOf: - - $ref: '#/components/schemas/PresetUpsertSchema' - - properties: - name: - type: string - required: - - name - type: object - PresetUpsertSchema: - properties: - value: - oneOf: - - $ref: '#/components/schemas/SearchParameters' - - $ref: '#/components/schemas/MultiSearchSearchesParameter' - required: - - value - PresetsRetrieveSchema: - properties: - presets: - items: - $ref: '#/components/schemas/PresetSchema' - type: array - x-go-type: '[]*PresetSchema' - required: - - presets - type: object - SchemaChangeStatus: - properties: - altered_docs: - description: Number of documents that have been altered - type: integer - collection: - description: Name of the collection being modified + - name: documentId + in: path + description: The Document ID + required: true + schema: type: string - validated_docs: - description: Number of documents that have been validated - type: integer - type: object - SearchGroupedHit: - properties: - found: - type: integer - group_key: - items: {} - type: array - hits: - description: The documents that matched the search query - items: - $ref: '#/components/schemas/SearchResultHit' - type: array - x-swift-type: '[SearchResultHit]?' - required: - - group_key - - hits - type: object - x-swift-generic-parameter: 'T: Codable' - SearchHighlight: - properties: - field: - example: company_name + 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: + summary: Create a conversation model + description: Create a Conversation Model + operationId: createConversationModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelCreateSchema' + required: true + responses: + '201': + 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 - indices: - 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 - type: array - matched_tokens: - items: - type: object - x-go-type: interface{} - type: array - snippet: - description: Present only for (non-array) string fields - example: Stark Industries + 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 - snippets: - description: Present only for (array) string[] fields - example: - - Stark Industries - - Stark Corp - items: - type: string - type: array - value: - description: Full field value with highlighting, present only for (non-array) - string fields - example: Stark Industries is a major supplier of space equipment. + 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 - values: - description: Full field value with highlighting, present only for (array) - string[] fields - example: - - Stark Industries - - Stark Corp - items: - type: string - type: array - type: object - SearchParameters: - properties: - 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. - - ' + 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 - conversation: - description: 'Enable conversational search. - - ' - type: boolean - 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 - conversation_model_id: - description: 'The Id of Conversation Model to be used. - - ' - type: string - drop_tokens_mode: - $ref: '#/components/schemas/DropTokensMode' - 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 - - ' + 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 - enable_analytics: - default: true - description: 'Flag for enabling/disabling analytics aggregation for specific - search queries (for e.g. those originating from a test script). - - ' - type: boolean - enable_highlight_v1: - default: true - description: 'Flag for enabling/disabling the deprecated, old highlight - structure in the response. Default: true - - ' - type: boolean - enable_overrides: - default: false - 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 - enable_synonyms: - 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 - - ' - type: boolean - enable_typos_for_alpha_numerical_tokens: - description: 'Set this parameter to false to disable typos on alphanumerical - query tokens. Default: true. - - ' - type: boolean - enable_typos_for_numerical_tokens: - default: true - description: 'Make Typesense disable typos for numerical tokens. - - ' - type: boolean - exclude_fields: - description: List of fields from the document to exclude in the search result - type: string - 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 - facet_by: - description: A list of fields that will be used for faceting your results - on. Separate multiple fields with a comma. - type: string - 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 - facet_return_parent: - description: 'Comma separated string of nested facet fields whose parent - object should be returned in facet response. - - ' - type: string - facet_strategy: - description: 'Choose the underlying faceting strategy used. Comma separated - string of allows values: exhaustive, top_values or automatic (default). - - ' + 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 - filter_by: - description: Filter conditions for refining your open api validator search - results. Separate multiple conditions with &&. - example: 'num_employees:>100 && country: [USA, UK]' + 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 - filter_curated_hits: - 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 - - ' - type: boolean - 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. + 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 - 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 - 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`. - - ' + 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 - highlight_affix_num_tokens: - description: 'The number of tokens that should surround the highlighted - text on each side. Default: 4 - - ' - type: integer - highlight_end_tag: - description: 'The end tag used for the highlighted snippets. Default: `` - - ' + 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" + /operations/cache/clear: + post: + tags: + - operations + summary: Clear the cached responses of search requests in the LRU cache. + description: Clear the cached responses of search requests that are sent with + `use_cache` parameter in the LRU cache. + operationId: clearCache + responses: + '200': + description: Clear cache succeeded. + content: + application/json: + schema: + $ref: "#/components/schemas/SuccessStatus" + /operations/db/compact: + post: + tags: + - operations + summary: Compacting the on-disk database + description: Typesense uses RocksDB to store your documents on the disk. If + you do frequent writes or updates, you could benefit from running a compaction + of the underlying RocksDB database. This could reduce the size of the database + and decrease read latency. While the database will not block during this operation, + we recommend running it during off-peak hours. + operationId: compactDb + responses: + '200': + description: Compacting the on-disk database succeeded. + content: + application/json: + schema: + $ref: "#/components/schemas/SuccessStatus" + /config: + post: + tags: + - operations + summary: Toggle Slow Request Log + description: Enable logging of requests that take over a defined threshold of + time. Default is `-1` which disables slow request logging. Slow requests are + logged to the primary log file, with the prefix SLOW REQUEST. + operationId: toggleSlowRequestLog + requestBody: + content: + application/json: + schema: + type: object + properties: + log-slow-requests-time-ms: + type: integer + required: + - log-slow-requests-time-ms + example: | + {"log-slow-requests-time-ms": 2000} + responses: + '200': + description: Toggle Slow Request Log database succeeded. + 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 - highlight_fields: - description: 'A list of custom fields that must be highlighted even if you - don''t query for them - - ' + - 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 - highlight_full_fields: - description: List of fields which should be highlighted fully without snippeting + - 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 - highlight_start_tag: - description: 'The start tag used for the highlighted snippets. Default: - `` - - ' + - 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 - include_fields: - description: List of fields from the document to include in the search result + - 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 - infix: + - 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` @@ -1781,4087 +2196,3423 @@ components: along with regular search `fallback` infix search is performed if regular search does not produce results type: string - limit: - description: 'Number of hits to fetch. Can be used as an alternative to - the per_page parameter. Default: 10. - - ' - type: integer - max_candidates: - description: 'Control the number of words that Typesense considers for typo - and prefix searching. - - ' - type: integer - max_extra_prefix: + - 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 - max_extra_suffix: + - 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 - max_facet_values: - description: Maximum number of facet values to be returned. - type: integer - 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 - 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 - nl_model_id: - description: The ID of the natural language model to use. - type: string - nl_query: - description: Whether to use natural language processing to parse the query. - type: boolean - num_typos: - description: 'The number of typographical errors (1 or 2) that would be - tolerated. Default: 2 - - ' - type: string - 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 - override_tags: - description: Comma separated list of tags to trigger the curations rules - that match the tags. - 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 - 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 - 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 - 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 - preset: - description: 'Search using a bunch of search parameters by setting this - parameter to the name of the existing Preset. - - ' - type: string - prioritize_exact_match: - default: true - description: 'Set this parameter to true to ensure that an exact match is - ranked above the others - - ' - type: boolean - prioritize_num_matching_fields: - default: true - description: 'Make Typesense prioritize documents where the query words - appear in more number of fields. - - ' - type: boolean - prioritize_token_position: - default: false - description: 'Make Typesense prioritize documents where the query words - appear earlier in the text. - - ' - type: boolean - 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. + - name: filter_by + in: query + schema: + description: Filter conditions for refining youropen api validator search + results. Separate multiple conditions with &&. type: string - remote_embedding_num_tries: - description: 'Number of times to retry fetching remote embeddings. - - ' - type: integer - remote_embedding_timeout_ms: - description: 'Timeout (in milliseconds) for fetching remote embeddings. - - ' - type: integer - 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 - snippet_threshold: - description: 'Field values under this length will be fully highlighted, - instead of showing a snippet of relevant portion. Default: 30 - - ' - type: integer - sort_by: + 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` - example: num_employees:desc - 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 - 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 - synonym_num_typos: - description: 'Allow synonym resolution on typo-corrected words in the query. - Default: 0 - - ' - type: integer - synonym_prefix: - description: 'Allow synonym resolution on word prefixes in the query. Default: - false - - ' - type: boolean - synonym_sets: - description: List of synonym set names to associate with this search query - example: synonym_set_1,synonym_set_2 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. + - 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 - 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 - - ' + - name: max_facet_values + in: query + schema: + description: Maximum number of facet values to be returned. type: integer - use_cache: - description: 'Enable server side caching of search query results. By default, - caching is disabled. - - ' - type: boolean - vector_query: - description: 'Vector query expression for fetching documents "closest" to - a given query/document vector. - - ' - type: string - voice_query: - description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. - - ' + - 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 - type: object - SearchRequestParams: - properties: - collection_name: + - name: num_typos + in: query + schema: + description: > + The number of typographical errors (1 or 2) that would be tolerated. Default: + 2 type: string - per_page: + - name: page + in: query + schema: + description: Results from this specific page number would be fetched. type: integer - q: - type: string - voice_query: - properties: - transcribed_query: - type: string - type: object - required: - - collection_name - - q - - per_page - type: object - SearchResult: - properties: - conversation: - $ref: '#/components/schemas/SearchResultConversation' - facet_counts: - items: - $ref: '#/components/schemas/FacetCounts' - type: array - found: - description: The number of documents found + - name: per_page + in: query + schema: + description: "Number of results to fetch per page. Default: 10" type: integer - found_docs: + - 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 - grouped_hits: - items: - $ref: '#/components/schemas/SearchGroupedHit' - type: array - x-swift-type: '[SearchGroupedHit]?' - hits: - description: The documents that matched the search query - items: - $ref: '#/components/schemas/SearchResultHit' - type: array - x-swift-type: '[SearchResultHit]?' - metadata: - additionalProperties: true - description: Custom JSON object that can be returned in the search response - type: object - out_of: - description: The total number of documents in the collection + - 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 - page: - description: The search result page number + - 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 - request_params: - $ref: '#/components/schemas/SearchRequestParams' - search_cutoff: - description: Whether the search was cut off + - 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 - search_time_ms: - description: The number of milliseconds the search took - type: integer - union_request_params: - description: Returned only for union query response. - items: - $ref: '#/components/schemas/SearchRequestParams' - type: array - type: object - x-swift-generic-parameter: 'T: Codable' - SearchResultConversation: - properties: - answer: + - name: include_fields + in: query + schema: + description: List of fields from the document to include in the search result type: string - conversation_history: - items: - type: object - type: array - conversation_id: + - name: exclude_fields + in: query + schema: + description: List of fields from the document to exclude in the search result type: string - query: + - name: highlight_full_fields + in: query + schema: + description: List of fields which should be highlighted fully without snippeting type: string - required: - - answer - - conversation_history - - conversation_id - - query - type: object - SearchResultHit: - example: - document: - company_name: Stark Industries - country: USA - id: '124' - num_employees: 5215 - highlights: - company_name: - field: company_name - snippet: Stark Industries - text_match: 1234556 - properties: - document: - additionalProperties: - type: object - description: Can be any key-value pair - type: object - x-swift-type: T? - geo_distance_meters: - additionalProperties: - type: integer - description: Can be any key-value pair - type: object - highlight: - additionalProperties: true - description: Highlighted version of the matching document - type: object - highlights: - description: (Deprecated) Contains highlighted portions of the search fields - items: - $ref: '#/components/schemas/SearchHighlight' - type: array - hybrid_search_info: - description: Information about hybrid search scoring - properties: - rank_fusion_score: - description: Combined score from rank fusion of text and vector search - format: float - type: number - type: object - search_index: - description: Returned only for union query response. Indicates the index - of the query which this document matched to. - type: integer - text_match: - format: int64 + - 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 - text_match_info: - properties: - best_field_score: - type: string - best_field_weight: - type: integer - fields_matched: - type: integer - num_tokens_dropped: - format: int64 - type: integer - x-go-type: uint64 - score: - type: string - tokens_matched: - type: integer - typo_prefix_score: - type: integer - type: object - vector_distance: - description: Distance between the query vector and matching document's vector - value - format: float - type: number - type: object - x-swift-generic-parameter: 'T: Codable' - SearchSynonym: - allOf: - - $ref: '#/components/schemas/SearchSynonymSchema' - - properties: - id: - readOnly: true - type: string - required: - - id - type: object - SearchSynonymDeleteResponse: - properties: - id: - description: The id of the synonym that was deleted - type: string - required: - - id - type: object - SearchSynonymSchema: - properties: - locale: - description: Locale for the synonym, leave blank to use the standard tokenizer. - type: string - root: - description: For 1-way synonyms, indicates the root word that words in the - `synonyms` parameter map to. + - name: highlight_start_tag + in: query + schema: + description: > + The start tag used for the highlighted snippets. Default: `` type: string - symbols_to_index: - 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 - type: array - synonyms: - description: Array of words that should be considered as synonyms. - items: - type: string - type: array - required: - - synonyms - type: object - SearchSynonymsResponse: - properties: - synonyms: - items: - $ref: '#/components/schemas/SearchSynonym' - type: array - x-go-type: '[]*SearchSynonym' - required: - - synonyms - type: object - StemmingDictionary: - properties: - id: - description: Unique identifier for the dictionary - example: irregular-plurals + - name: highlight_end_tag + in: query + schema: + description: > + The end tag used for the highlighted snippets. Default: `` type: string - words: - description: List of word mappings in the dictionary - items: - properties: - root: - description: The root form of the word - example: person - type: string - word: - description: The word form to be stemmed - example: people - type: string - required: - - word - - root - type: object - type: array - required: - - id - - words - type: object - StopwordsSetRetrieveSchema: - example: '{"stopwords": {"id": "countries", "stopwords": ["Germany", "France", - "Italy"], "locale": "en"}} + - 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: enable_analytics + in: query + schema: + description: > + Flag for enabling/disabling analytics aggregation for specific search + queries (for e.g. those originating from a test script). + type: boolean + 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`. - ' - properties: - stopwords: - $ref: '#/components/schemas/StopwordsSetSchema' - required: - - stopwords - type: object - StopwordsSetSchema: - example: '{"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": - "en"} + 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`. - ' - properties: - id: + 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 - locale: + - name: override_tags + in: query + schema: + description: Comma separated list of tags to trigger the curations rules + that match the tags. type: string - stopwords: - items: - type: string - type: array - required: - - id - - stopwords - type: object - StopwordsSetUpsertSchema: - example: '{"stopwords": ["Germany", "France", "Italy"], "locale": "en"} - - ' - properties: - locale: + - 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 - stopwords: - items: - type: string - type: array - required: - - stopwords - type: object - StopwordsSetsRetrieveAllSchema: - example: '{"stopwords": [{"id": "countries", "stopwords": ["Germany", "France", - "Italy"], "locale": "en"}]} + - 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. - ' - properties: - stopwords: - items: - $ref: '#/components/schemas/StopwordsSetSchema' - type: array - required: - - stopwords - type: object - SuccessStatus: - properties: - success: + Set this parameter to true to do the same type: boolean - required: - - success - type: object - SynonymItemDeleteSchema: - properties: - id: - description: ID of the deleted synonym item + 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 - required: - - id - type: object - SynonymItemSchema: - properties: - id: - description: Unique identifier for the synonym item + - 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 - locale: - description: Locale for the synonym, leave blank to use the standard tokenizer + - 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 - root: - description: For 1-way synonyms, indicates the root word that words in the - synonyms parameter map to + - 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 - symbols_to_index: - 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 - type: array - synonyms: - description: Array of words that should be considered as synonyms - items: - type: string - type: array - required: - - id - - synonyms - type: object - SynonymSetCreateSchema: - properties: - items: - description: Array of synonym items - items: - $ref: '#/components/schemas/SynonymItemSchema' - type: array - required: - - items - type: object - SynonymSetDeleteSchema: - properties: - name: - description: Name of the deleted synonym set + - 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 - required: - - name - type: object - SynonymSetRetrieveSchema: - $ref: '#/components/schemas/SynonymSetCreateSchema' - SynonymSetSchema: - allOf: - - $ref: '#/components/schemas/SynonymSetCreateSchema' - - properties: - name: - description: Name of the synonym set - type: string - required: - - name - type: object - SynonymSetsRetrieveSchema: - properties: - synonym_sets: - description: Array of synonym sets - items: - $ref: '#/components/schemas/SynonymSetSchema' - type: array - required: - - synonym_sets - type: object - UpdateDocumentsParameters: - properties: - filter_by: - example: 'num_employees:>100 && country: [USA, UK]' + - name: voice_query + in: query + schema: + description: > + The base64 encoded audio file in 16 khz 16-bit WAV format. type: string - type: object - VoiceQueryModelCollectionConfig: - description: 'Configuration for the voice query model - - ' - properties: - model_name: - example: ts/whisper/base.en + - 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 - type: object - securitySchemes: - api_key_header: - in: header - name: X-TYPESENSE-API-KEY - type: apiKey -externalDocs: - description: Find out more about Typsesense - url: https://typesense.org -info: - description: An open source search engine for building delightful search experiences. - license: - name: GPL-3.0 - url: https://opensource.org/licenses/GPL-3.0 - title: Typesense API - version: '30.0' -openapi: 3.0.3 -paths: - /aliases: + - 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: Submit a single analytics event. The event must correspond to an + existing analytics rule by name. + operationId: createAnalyticsEvent + requestBody: + description: The analytics event to be created + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEvent' + required: true + responses: + '200': + 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' + get: + tags: + - analytics + summary: Retrieve analytics events + description: Retrieve the most recent events for a user and rule. + operationId: getAnalyticsEvents + parameters: + - name: user_id + in: query + required: true + schema: + type: string + - name: name + in: query + description: Analytics rule name + required: true + schema: + type: string + - name: n + in: query + description: Number of events to return (max 1000) + required: true + schema: + type: integer + responses: + '200': + description: Events fetched + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventsResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /analytics/flush: + post: + tags: + - analytics + summary: Flush in-memory analytics to disk + description: Triggers a flush of analytics data to persistent storage. + operationId: flushAnalytics + responses: + '200': + description: Flush triggered + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventCreateResponse' + /analytics/status: get: - description: List all aliases and the corresponding collections that they map - to. - operationId: getAliases + tags: + - analytics + summary: Get analytics subsystem status + description: Returns sizes of internal analytics buffers and queues. + operationId: getAnalyticsStatus responses: '200': + description: Status fetched content: application/json: schema: - $ref: '#/components/schemas/CollectionAliasesResponse' - description: List of all collection aliases - summary: List all aliases + $ref: '#/components/schemas/AnalyticsStatus' + /analytics/rules: + post: tags: - - collections - /aliases/{aliasName}: - delete: - operationId: deleteAlias - parameters: - - description: The name of the alias to delete - in: path - name: aliasName + - analytics + summary: Create analytics rule(s) + description: Create one or more analytics rules. You can send a single rule + object or an array of rule objects. + operationId: createAnalyticsRule + requestBody: + description: The analytics rule(s) to be created + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/AnalyticsRuleCreate" + - type: array + items: + $ref: "#/components/schemas/AnalyticsRuleCreate" required: true - schema: - type: string responses: '200': + description: Analytics rule(s) successfully created content: application/json: schema: - $ref: '#/components/schemas/CollectionAlias' - description: Collection alias was deleted - '404': + oneOf: + - $ref: "#/components/schemas/AnalyticsRule" + - type: array + items: + oneOf: + - $ref: "#/components/schemas/AnalyticsRule" + - type: object + properties: + error: + type: string + '400': + description: Bad request, see error message for details content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' - description: Alias not found - summary: Delete an alias - tags: - - collections + $ref: "#/components/schemas/ApiResponse" get: - description: Find out which collection an alias points to by fetching it - operationId: getAlias + tags: + - analytics + summary: Retrieve analytics rules + description: Retrieve all analytics rules. Use the optional rule_tag filter + to narrow down results. + operationId: retrieveAnalyticsRules parameters: - - description: The name of the alias to retrieve - in: path - name: aliasName - required: true + - in: query + name: rule_tag schema: type: string + required: false + description: Filter rules by rule_tag responses: '200': + description: Analytics rules fetched content: application/json: schema: - $ref: '#/components/schemas/CollectionAlias' - description: Collection alias fetched - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: The alias was not found - summary: Retrieve an alias - tags: - - collections + type: array + items: + $ref: "#/components/schemas/AnalyticsRule" + /analytics/rules/{ruleName}: put: - 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 + tags: + - analytics + summary: Upserts an analytics rule + description: Upserts an analytics rule with the given name. + operationId: upsertAnalyticsRule parameters: - - description: The name of the alias to create/update - in: path - name: aliasName - required: true + - 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/CollectionAliasSchema' - description: Collection alias to be created/updated + $ref: "#/components/schemas/AnalyticsRuleUpdate" + required: true responses: '200': + description: Analytics rule successfully upserted content: application/json: schema: - $ref: '#/components/schemas/CollectionAlias' - description: The collection alias was created/updated + $ref: "#/components/schemas/AnalyticsRule" '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' description: Bad request, see error message for details - '404': content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' - description: Alias not found - summary: Create or update a collection alias - tags: - - collections - /analytics/events: + $ref: "#/components/schemas/ApiResponse" get: - description: Retrieve the most recent events for a user and rule. - operationId: getAnalyticsEvents + tags: + - analytics + summary: Retrieves an analytics rule + description: Retrieve the details of an analytics rule, given it's name + operationId: retrieveAnalyticsRule parameters: - - in: query - name: user_id - required: true - schema: - type: string - - description: Analytics rule name - in: query - name: name - required: true + - in: path + name: ruleName + description: The name of the analytics rule to retrieve schema: type: string - - description: Number of events to return (max 1000) - in: query - name: n required: true - schema: - type: integer responses: '200': + description: Analytics rule fetched content: application/json: schema: - $ref: '#/components/schemas/AnalyticsEventsResponse' - description: Events fetched - '400': + $ref: "#/components/schemas/AnalyticsRule" + '404': + description: Analytics rule not found content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - summary: Retrieve analytics events + $ref: "#/components/schemas/ApiResponse" + delete: tags: - analytics - post: - description: Submit a single analytics event. The event must correspond to an - existing analytics rule by name. - operationId: createAnalyticsEvent - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/AnalyticsEvent' - description: The analytics event to be created + 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/AnalyticsEventCreateResponse' - description: Analytics event successfully created - '400': + $ref: "#/components/schemas/AnalyticsRule" + '404': + description: Analytics rule not found content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - summary: Create an analytics event + $ref: "#/components/schemas/ApiResponse" + /metrics.json: + get: tags: - - analytics - /analytics/flush: - post: - description: Triggers a flush of analytics data to persistent storage. - operationId: flushAnalytics + - 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: - $ref: '#/components/schemas/AnalyticsEventCreateResponse' - description: Flush triggered - summary: Flush in-memory analytics to disk + type: object + /stats.json: + get: tags: - - analytics - /analytics/rules: + - 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: - description: Retrieve all analytics rules. Use the optional rule_tag filter - to narrow down results. - operationId: retrieveAnalyticsRules - parameters: - - description: Filter rules by rule_tag - in: query - name: rule_tag - required: false - schema: - type: string + 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: - items: - $ref: '#/components/schemas/AnalyticsRule' - type: array - description: Analytics rules fetched - summary: Retrieve analytics rules + $ref: "#/components/schemas/StopwordsSetsRetrieveAllSchema" + /stopwords/{setId}: + put: tags: - - analytics - post: - description: Create one or more analytics rules. You can send a single rule - object or an array of rule objects. - operationId: createAnalyticsRule + - 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: - oneOf: - - $ref: '#/components/schemas/AnalyticsRuleCreate' - - items: - $ref: '#/components/schemas/AnalyticsRuleCreate' - type: array - description: The analytics rule(s) to be created + $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: - oneOf: - - $ref: '#/components/schemas/AnalyticsRule' - - items: - anyOf: - - $ref: '#/components/schemas/AnalyticsRule' - - properties: - error: - type: string - type: object - type: array - description: Analytics rule(s) successfully created - '400': + $ref: "#/components/schemas/StopwordsSetRetrieveSchema" + '404': + description: Stopwords set not found. content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - summary: Create analytics rule(s) - tags: - - analytics - /analytics/rules/{ruleName}: + $ref: "#/components/schemas/ApiResponse" delete: - description: Permanently deletes an analytics rule, given it's name - operationId: deleteAnalyticsRule + tags: + - stopwords + summary: Delete a stopwords set. + description: Permanently deletes a stopwords set, given it's name. + operationId: deleteStopwordsSet parameters: - - description: The name of the analytics rule to delete - in: path - name: ruleName - required: true + - 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: - $ref: '#/components/schemas/AnalyticsRule' - description: Analytics rule deleted + 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' - description: Analytics rule not found - summary: Delete an analytics rule + $ref: "#/components/schemas/ApiResponse" + /presets: + get: tags: - - analytics + - 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: - description: Retrieve the details of an analytics rule, given it's name - operationId: retrieveAnalyticsRule + tags: + - presets + summary: Retrieves a preset. + description: Retrieve the details of a preset, given it's name. + operationId: retrievePreset parameters: - - description: The name of the analytics rule to retrieve - in: path - name: ruleName - required: true + - 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/AnalyticsRule' - description: Analytics rule fetched + $ref: '#/components/schemas/PresetSchema' '404': + description: Preset not found. content: application/json: schema: $ref: '#/components/schemas/ApiResponse' - description: Analytics rule not found - summary: Retrieves an analytics rule - tags: - - analytics put: - description: Upserts an analytics rule with the given name. - operationId: upsertAnalyticsRule + tags: + - presets + summary: Upserts a preset. + description: Create or update an existing preset. + operationId: upsertPreset parameters: - - description: The name of the analytics rule to upsert - in: path - name: ruleName - required: true + - 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/AnalyticsRuleUpdate' - description: The Analytics rule to be upserted + $ref: '#/components/schemas/PresetUpsertSchema' required: true responses: '200': + description: Preset successfully upserted. content: application/json: schema: - $ref: '#/components/schemas/AnalyticsRule' - description: Analytics rule successfully upserted + $ref: '#/components/schemas/PresetSchema' '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' description: Bad request, see error message for details - summary: Upserts an analytics rule - tags: - - analytics - /analytics/status: - get: - description: Returns sizes of internal analytics buffers and queues. - operationId: getAnalyticsStatus - responses: - '200': content: application/json: schema: - $ref: '#/components/schemas/AnalyticsStatus' - description: Status fetched - summary: Get analytics subsystem status + $ref: '#/components/schemas/ApiResponse' + delete: tags: - - analytics - /collections: - get: - 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 + - presets + summary: Delete a preset. + description: Permanently deletes a preset, given it's name. + operationId: deletePreset parameters: - - in: query - name: offset - schema: - description: Identifies the starting point to return collections when paginating. - type: integer - - in: query - name: exclude_fields + - in: path + name: presetId + description: The ID of the preset to delete. schema: - description: Comma-separated list of fields from the collection to exclude - from the response type: string - - in: query - name: limit - schema: - description: 'Number of collections to fetch. Default: returns all collections. - - ' - type: integer - responses: - '200': - content: - application/json: - schema: - items: - $ref: '#/components/schemas/CollectionResponse' - type: array - x-go-type: '[]*CollectionResponse' - description: List of all collections - summary: List all collections - tags: - - collections - post: - 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: - content: - application/json: - schema: - $ref: '#/components/schemas/CollectionSchema' - description: The collection object to be created required: true + example: listing_view responses: - '201': + '200': + description: Preset deleted. content: application/json: schema: - $ref: '#/components/schemas/CollectionResponse' - description: Collection successfully created - '400': + $ref: '#/components/schemas/PresetDeleteSchema' + '404': + description: Preset not found. content: application/json: schema: $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - '409': + /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: - $ref: '#/components/schemas/ApiResponse' - description: Collection already exists - summary: Create a new collection + type: object + properties: + dictionaries: + type: array + items: + type: string + example: + - "irregular-plurals" + - "company-terms" + /stemming/dictionaries/{dictionaryId}: + get: tags: - - collections - /collections/{collectionName}: - delete: - description: Permanently drops a collection. This action cannot be undone. For - large collections, this might have an impact on read latencies. - operationId: deleteCollection + - stemming + summary: Retrieve a stemming dictionary + description: Fetch details of a specific stemming dictionary. + operationId: getStemmingDictionary parameters: - - description: The name of the collection to delete + - name: dictionaryId in: path - name: collectionName + 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/CollectionResponse' - description: Collection deleted + $ref: "#/components/schemas/StemmingDictionary" '404': + description: Dictionary not found content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' - description: Collection not found - summary: Delete a collection + $ref: "#/components/schemas/ApiResponse" + /stemming/dictionaries/import: + post: tags: - - collections - get: - description: Retrieve the details of a collection, given its name. - operationId: getCollection + - stemming + summary: Import a stemming dictionary + description: Upload a JSONL file containing word mappings to create or update + a stemming dictionary. + operationId: importStemmingDictionary parameters: - - description: The name of the collection to retrieve - in: path - name: collectionName + - 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: - $ref: '#/components/schemas/CollectionResponse' - description: Collection fetched - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Collection not found - summary: Retrieve a single collection + type: array + items: + $ref: '#/components/schemas/NLSearchModelSchema' + post: tags: - - collections - patch: - description: Update a collection's schema to modify the fields and their types. - operationId: updateCollection - parameters: - - description: The name of the collection to update - in: path - name: collectionName - required: true - schema: - type: string + - 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/CollectionUpdateSchema' - description: The document object with fields to be updated + $ref: '#/components/schemas/NLSearchModelCreateSchema' required: true responses: - '200': + '201': + description: NL search model successfully created content: application/json: schema: - $ref: '#/components/schemas/CollectionUpdateSchema' - description: The updated partial collection schema + $ref: '#/components/schemas/NLSearchModelSchema' '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' description: Bad request, see error message for details - '404': content: application/json: schema: $ref: '#/components/schemas/ApiResponse' - description: The collection was not found - summary: Update a collection + /nl_search_models/{modelId}: + get: tags: - - collections - /collections/{collectionName}/documents: - delete: - 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 + - nl_search_models + summary: Retrieve a NL search model + description: Retrieve a specific NL search model by its ID. + operationId: retrieveNLSearchModel parameters: - - description: The name of the collection to delete documents from + - name: modelId in: path - name: collectionName + description: The ID of the NL search model to retrieve required: true schema: type: string - - in: query - name: truncate - schema: - description: When true, removes all documents from the collection while - preserving the collection and its schema. - type: boolean - - in: query - name: batch_size - 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 - - in: query - name: filter_by - schema: - example: 'num_employees:>100 && country: [USA, UK]' - type: string - - in: query - name: ignore_not_found - schema: - type: boolean responses: '200': + description: NL search model fetched content: application/json: schema: - properties: - num_deleted: - type: integer - required: - - num_deleted - type: object - description: Documents successfully deleted + $ref: '#/components/schemas/NLSearchModelSchema' '404': + description: NL search model not found content: application/json: schema: $ref: '#/components/schemas/ApiResponse' - description: Collection not found - summary: Delete a bunch of documents + put: tags: - - documents - patch: - 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 + - nl_search_models + summary: Update a NL search model + description: Update an existing NL search model. + operationId: updateNLSearchModel parameters: - - description: The name of the collection to update documents in + - name: modelId in: path - name: collectionName + description: The ID of the NL search model to update required: true schema: type: string - - in: query - name: filter_by - schema: - example: 'num_employees:>100 && country: [USA, UK]' - type: string requestBody: + description: The NL search model fields to update content: application/json: schema: - description: Can be any key-value pair - type: object - x-go-type: interface{} - description: The document fields to be updated + $ref: '#/components/schemas/NLSearchModelUpdateSchema' required: true responses: '200': + description: NL search model successfully updated content: application/json: schema: - properties: - num_updated: - description: The number of documents that have been updated - example: 1 - type: integer - required: - - num_updated - type: object - description: The response contains a single field, `num_updated`, indicating - the number of documents affected. + $ref: '#/components/schemas/NLSearchModelSchema' '400': + description: Bad request, see error message for details content: application/json: schema: $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details '404': + description: NL search model not found content: application/json: schema: $ref: '#/components/schemas/ApiResponse' - description: The collection was not found - summary: Update documents with conditional query + delete: tags: - - documents - post: - description: A document to be indexed in a given collection must conform to - the schema of the collection. - operationId: indexDocument + - nl_search_models + summary: Delete a NL search model + description: Delete a specific NL search model by its ID. + operationId: deleteNLSearchModel parameters: - - description: The name of the collection to add the document to + - name: modelId in: path - name: collectionName + description: The ID of the NL search model to delete required: true schema: type: string - - description: Additional action to perform - in: query - name: action - schema: - $ref: '#/components/schemas/IndexAction' - example: upsert + 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: [] + synonym_sets: + type: array + description: List of synonym set names to associate with this collection + items: + type: string + example: "synonym_set_1" + 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" + metadata: + type: object + description: > + Optional details about the collection, e.g., when it was created, who + created it etc. + 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" + synonym_sets: + type: array + description: List of synonym set names to associate with this collection + items: + type: string + example: "synonym_set_1" + metadata: + type: object + description: > + Optional details about the collection, e.g., when it was created, who + created it etc. + 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: Dealing with Dirty Data - in: query - name: dirty_values - schema: - $ref: '#/components/schemas/DirtyValues' - requestBody: - content: - application/json: - schema: - description: Can be any key-value pair + 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 - x-go-type: interface{} - description: The document object to be indexed - required: true - responses: - '201': - content: - application/json: - schema: - description: Can be any key-value pair - type: object - description: Document successfully created/indexed - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Collection not found - summary: Index a document - tags: - - documents - /collections/{collectionName}/documents/export: - get: - description: Export all documents in a collection in JSON lines format. - operationId: exportDocuments - parameters: - - description: The name of the collection - in: path - name: collectionName - required: true - schema: + 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 - - in: query - name: exclude_fields - schema: - description: List of fields from the document to exclude in the search result + example: "ts/whisper/base.en" + CollectionAliasSchema: + type: object + required: + - collection_name + properties: + collection_name: type: string - - in: query - name: filter_by - schema: - description: Filter conditions for refining your search results. Separate - multiple conditions with &&. + description: Name of the collection you wish to map the alias to + CollectionAlias: + type: object + required: + - collection_name + - name + properties: + name: type: string - - in: query - name: include_fields - schema: - description: List of fields from the document to include in the search result + readOnly: true + description: Name of the collection alias + collection_name: type: string - responses: - '200': - content: - application/octet-stream: - schema: - 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"} - - ' - type: string - description: Exports all the documents in a given collection. - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: The collection was not found - summary: Export all documents in a collection - tags: - - documents - /collections/{collectionName}/documents/import: - post: - 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: - - description: The name of the collection - in: path - name: collectionName - required: true - schema: + 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" + x-swift-type: '[SearchGroupedHit]?' + hits: + type: array + description: The documents that matched the search query + items: + $ref: "#/components/schemas/SearchResultHit" + x-swift-type: '[SearchResultHit]?' + request_params: + $ref: "#/components/schemas/SearchRequestParams" + conversation: + $ref: "#/components/schemas/SearchResultConversation" + union_request_params: + type: array + description: Returned only for union query response. + items: + $ref: "#/components/schemas/SearchRequestParams" + metadata: + type: object + description: Custom JSON object that can be returned in the search response + additionalProperties: true + x-swift-generic-parameter: 'T: Codable' + SearchRequestParams: + 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 + SearchResultConversation: + type: object + required: + - answer + - conversation_history + - conversation_id + - query + properties: + answer: type: string - - in: query - name: action - schema: - $ref: '#/components/schemas/IndexAction' - - in: query - name: remote_embedding_batch_size - schema: + 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 - - in: query - name: dirty_values - schema: - $ref: '#/components/schemas/DirtyValues' - - in: query - name: return_doc - schema: - type: boolean - - in: query - name: return_id - schema: - 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. - type: boolean - - in: query - name: batch_size - schema: + group_key: + type: array + items: {} + hits: + type: array + description: The documents that matched the search query + items: + $ref: "#/components/schemas/SearchResultHit" + x-swift-type: '[SearchResultHit]?' + x-swift-generic-parameter: 'T: Codable' + 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 + additionalProperties: + type: object + x-swift-type: T? + text_match: type: integer - requestBody: - content: - application/octet-stream: - schema: - description: The JSONL file to import + format: int64 + text_match_info: + type: object + properties: + best_field_score: type: string - description: The json array of documents or the JSONL file to import - required: true - responses: - '200': - content: - application/octet-stream: - schema: - example: '{"success": true} - - {"success": false, "error": "Bad JSON.", "document": "[bad doc"} - - ' - type: string - 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. - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: The collection was not found - summary: Import documents into a collection - tags: - - documents - /collections/{collectionName}/documents/search: - get: - description: Search for documents in a collection that match the search criteria. - operationId: searchCollection - parameters: - - description: The name of the collection to search for the document under - in: path - name: collectionName - required: true - schema: + 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 + hybrid_search_info: + type: object + description: Information about hybrid search scoring + properties: + rank_fusion_score: + type: number + format: float + description: Combined score from rank fusion of text and vector search + search_index: + type: integer + description: Returned only for union query response. Indicates the index + of the query which this document matched to. + 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 + x-swift-generic-parameter: 'T: Codable' + SearchHighlight: + type: object + properties: + field: type: string - - in: query - name: synonym_sets - schema: - description: List of synonym set names to associate with this search query - example: synonym_set_1,synonym_set_2 + example: company_name + snippet: type: string - - in: query - name: filter_curated_hits - schema: - 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 - - ' - type: boolean - - in: query - name: highlight_full_fields - schema: - description: List of fields which should be highlighted fully without snippeting + 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 - - in: query - name: include_fields - schema: - description: List of fields from the document to include in the search result + 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{}" + SearchSynonymSchema: + type: object + required: + - synonyms + properties: + root: type: string - - in: query - name: synonym_num_typos - schema: - description: 'Allow synonym resolution on typo-corrected words in the query. - Default: 0 - - ' - type: integer - - in: query - name: pinned_hits - 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`. - - ' + 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 - - in: query - name: facet_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". + 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 - - in: query - name: group_missing_values - 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 - - ' + 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 - - in: query - name: max_extra_prefix - 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 - - in: query - name: per_page - schema: - description: 'Number of results to fetch per page. Default: 10' + SchemaChangeStatus: + type: object + properties: + collection: + type: string + description: Name of the collection being modified + validated_docs: type: integer - - in: query - name: snippet_threshold - schema: - description: 'Field values under this length will be fully highlighted, - instead of showing a snippet of relevant portion. Default: 30 - - ' + description: Number of documents that have been validated + altered_docs: type: integer - - in: query - name: conversation - schema: - description: 'Enable conversational search. - - ' - type: boolean - - in: query - name: nl_query - schema: - description: Whether to use natural language processing to parse the query. + description: Number of documents that have been altered + SuccessStatus: + type: object + required: + - success + properties: + success: type: boolean - - in: query - name: infix - 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 - - in: query - name: highlight_end_tag - schema: - description: 'The end tag used for the highlighted snippets. Default: `` - - ' - type: string - - in: query - name: highlight_fields - schema: - description: 'A list of custom fields that must be highlighted even if you - don''t query for them - - ' + ApiResponse: + type: object + required: + - message + properties: + message: type: string - - in: query - name: vector_query - schema: - description: 'Vector query expression for fetching documents "closest" to - a given query/document vector. - - ' + ApiKeySchema: + type: object + required: + - actions + - collections + - description + properties: + value: type: string - - in: query - name: hidden_hits - 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`. - - ' + description: type: string - - in: query - name: remote_embedding_timeout_ms - schema: - description: 'Timeout (in milliseconds) for fetching remote embeddings. - - ' + actions: + type: array + items: + type: string + collections: + type: array + items: + type: string + expires_at: type: integer - - in: query - name: query_by - schema: + 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" + MultiSearchResult: + type: object + required: + - results + properties: + results: + type: array + items: + $ref: "#/components/schemas/MultiSearchResultItem" + x-swift-type: '[MultiSearchResultItem]' + conversation: + $ref: "#/components/schemas/SearchResultConversation" + x-swift-generic-parameter: 'T: Codable' + MultiSearchResultItem: + allOf: + - $ref: "#/components/schemas/SearchResult" + - type: object + properties: + code: + type: integer + description: HTTP error code + format: int64 + error: + type: string + description: Error description + x-swift-generic-parameter: 'T: Codable' + 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 - - in: query - name: enable_analytics - schema: - default: true - description: 'Flag for enabling/disabling analytics aggregation for specific - search queries (for e.g. those originating from a test script). - - ' - type: boolean - - in: query - name: exhaustive_search - 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 - - in: query - name: enable_synonyms - schema: - 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 - - ' - type: boolean - - in: query - name: enable_highlight_v1 - schema: - default: true - description: 'Flag for enabling/disabling the deprecated, old highlight - structure in the response. Default: true - - ' - type: boolean - - in: query - name: page - schema: - description: Results from this specific page number would be fetched. - type: integer - - in: query - name: enable_typos_for_alpha_numerical_tokens - schema: - description: 'Set this parameter to false to disable typos on alphanumerical - query tokens. Default: true. - - ' + nl_query: + description: Whether to use natural language processing to parse the query. type: boolean - - in: query - name: filter_by - schema: - description: Filter conditions for refining your open api validator search - results. Separate multiple conditions with &&. - example: 'num_employees:>100 && country: [USA, UK]' + nl_model_id: + description: The ID of the natural language model to use. type: string - - in: query - name: prioritize_exact_match - schema: - default: true - description: 'Set this parameter to true to ensure that an exact match is - ranked above the others - - ' - type: boolean - - in: query - name: pre_segmented_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 - - in: query - name: typo_tokens_threshold - 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 - - in: query - name: prioritize_token_position - schema: - default: false - description: 'Make Typesense prioritize documents where the query words - appear earlier in the text. - - ' - type: boolean - - in: query - name: min_len_2typo - 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 - - in: query - name: group_by - 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. + 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 - - in: query - name: max_extra_suffix - schema: + 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 - - in: query - name: q - 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 - - in: query - name: conversation_model_id - schema: - description: 'The Id of Conversation Model to be used. - - ' - type: string - - in: query - name: group_limit - 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 - - in: query - name: max_facet_values - schema: - description: Maximum number of facet values to be returned. - type: integer - - in: query - name: remote_embedding_num_tries - schema: - description: 'Number of times to retry fetching remote embeddings. - - ' + 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 - - in: query - name: facet_return_parent - schema: - description: 'Comma separated string of nested facet fields whose parent - object should be returned in facet response. - - ' - type: string - - in: query - name: enable_overrides - schema: - default: false - 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 - - in: query - name: facet_by - schema: - description: A list of fields that will be used for faceting your results - on. Separate multiple fields with a comma. - type: string - - in: query - name: stopwords - 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 - - in: query - name: exclude_fields - schema: - description: List of fields from the document to exclude in the search result - type: string - - in: query - name: highlight_start_tag - schema: - description: 'The start tag used for the highlighted snippets. Default: - `` - - ' + filter_by: + description: Filter conditions for refining your open api validator search + results. Separate multiple conditions with &&. type: string - - in: query - name: sort_by - schema: + 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 - - in: query - name: use_cache - schema: - description: 'Enable server side caching of search query results. By default, - caching is disabled. - - ' - type: boolean - - in: query - name: min_len_1typo - 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. - - ' + max_facet_values: + description: Maximum number of facet values to be returned. type: integer - - in: query - name: synonym_prefix - schema: - description: 'Allow synonym resolution on word prefixes in the query. Default: - false - - ' - type: boolean - - in: query - name: highlight_affix_num_tokens - schema: - description: 'The number of tokens that should surround the highlighted - text on each side. Default: 4 - - ' + 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 - - in: query - name: search_cutoff_ms - 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. - - ' + per_page: + description: "Number of results to fetch per page. Default: 10" type: integer - - in: query - name: nl_model_id - schema: - description: The ID of the natural language model to use. - type: string - - in: query - name: drop_tokens_mode - schema: - $ref: '#/components/schemas/DropTokensMode' - - in: query - name: num_typos - schema: - description: 'The number of typographical errors (1 or 2) that would be - tolerated. Default: 2 - - ' + 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 - - in: query - name: prioritize_num_matching_fields - schema: - default: true - description: 'Make Typesense prioritize documents where the query words - appear in more number of fields. - - ' + 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 - - in: query - name: voice_query - schema: - description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. - - ' + include_fields: + description: List of fields from the document to include in the search result type: string - - in: query - name: conversation_id - schema: - description: 'The Id of a previous conversation to continue, this tells - Typesense to include prior context when communicating with the LLM. - - ' + exclude_fields: + description: List of fields from the document to exclude in the search result type: string - - in: query - name: max_candidates - schema: - description: 'Control the number of words that Typesense considers for typo - and prefix searching. - - ' - type: integer - - in: query - name: split_join_tokens - 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`. - - ' + highlight_full_fields: + description: List of fields which should be highlighted fully without snippeting type: string - - in: query - name: query_by_weights - 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. + 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 - - in: query - name: prefix - 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. + highlight_end_tag: + description: > + The end tag used for the highlighted snippets. Default: `` type: string - - in: query - name: enable_typos_for_numerical_tokens - schema: + enable_highlight_v1: + description: > + Flag for enabling/disabling the deprecated, old highlight structure in + the response. Default: true + type: boolean default: true - description: 'Make Typesense disable typos for numerical tokens. - - ' + enable_analytics: + description: > + Flag for enabling/disabling analytics aggregation for specific search + queries (for e.g. those originating from a test script). type: boolean - - in: query - name: limit - schema: - description: 'Number of hits to fetch. Can be used as an alternative to - the per_page parameter. Default: 10. - - ' + 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 - - in: query - name: drop_tokens_threshold - 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 - - ' + synonym_sets: + type: string + description: List of synonym set names to associate with this search query + example: "synonym_set_1,synonym_set_2" + 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 - - in: query - name: text_match_type - 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. + 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 - - in: query - name: override_tags - schema: + 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 - - in: query - name: preset - schema: - description: 'Search using a bunch of search parameters by setting this - parameter to the name of the existing Preset. - - ' + highlight_fields: + description: > + A list of custom fields that must be highlighted even if you don't query + for them type: string - - in: query - name: facet_strategy - schema: - description: 'Choose the underlying faceting strategy used. Comma separated - string of allows values: exhaustive, top_values or automatic (default). + 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 - - in: query - name: offset - schema: - description: Identifies the starting point to return hits from a result - set. Can be used as an alternative to the page parameter. + 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 - - in: query - name: max_filter_by_candidates - 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*. + 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 - - in: query - name: cache_ttl - 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. - - ' + 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 - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/SearchResult' - description: Search results - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: The collection or field was not found - summary: Search for documents in a collection - tags: - - documents - /collections/{collectionName}/documents/{documentId}: - delete: - description: Delete an individual document from a collection by using its ID. - operationId: deleteDocument - parameters: - - description: The name of the collection to search for the document under - in: path - name: collectionName - required: true - schema: + 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 - - description: The Document ID - in: path - name: documentId - required: true - schema: + 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 - responses: - '200': - content: - application/json: - schema: - description: Can be any key-value pair - type: object - description: The document referenced by the ID was deleted - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: The document or collection was not found - summary: Delete a document - tags: - - documents - get: - description: Fetch an individual document from a collection by using its ID. - operationId: getDocument - parameters: - - description: The name of the collection to search for the document under - in: path - name: collectionName - required: true - schema: + 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 - - description: The Document ID - in: path - name: documentId - required: true - schema: + facet_return_parent: + description: > + Comma separated string of nested facet fields whose parent object should + be returned in facet response. type: string - responses: - '200': - content: - application/json: - schema: - description: Can be any key-value pair - type: object - description: The document referenced by the ID - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: The document or collection was not found - summary: Retrieve a document - tags: - - documents - patch: - description: Update an individual document from a collection by using its ID. - The update can be partial. - operationId: updateDocument - parameters: - - description: The name of the collection to search for the document under - in: path - name: collectionName - required: true - schema: + voice_query: + description: > + The base64 encoded audio file in 16 khz 16-bit WAV format. type: string - - description: The Document ID - in: path - name: documentId - required: true - schema: + conversation: + description: > + Enable conversational search. + type: boolean + conversation_model_id: + description: > + The Id of Conversation Model to be used. type: string - - description: Dealing with Dirty Data - in: query - name: dirty_values - schema: - $ref: '#/components/schemas/DirtyValues' - requestBody: - content: - application/json: - schema: - description: Can be any key-value pair - type: object - x-go-type: interface{} - description: The document object with fields to be updated - required: true - responses: - '200': - content: - application/json: - schema: - description: Can be any key-value pair - type: object - description: The document referenced by the ID was updated - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: The document or collection was not found - summary: Update a document - tags: - - documents - /config: - post: - description: Enable logging of requests that take over a defined threshold of - time. Default is `-1` which disables slow request logging. Slow requests are - logged to the primary log file, with the prefix SLOW REQUEST. - operationId: toggleSlowRequestLog - requestBody: - content: - application/json: - schema: - example: '{"log-slow-requests-time-ms": 2000} - - ' - properties: - log-slow-requests-time-ms: - type: integer - required: - - log-slow-requests-time-ms - type: object - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/SuccessStatus' - description: Compacting the on-disk database succeeded. - summary: Toggle Slow Request Log - tags: - - operations - /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: - '201': - 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 - summary: Create a conversation model - tags: - - conversations - /conversations/models/{modelId}: - delete: - description: Delete a conversation model - operationId: deleteConversationModel - parameters: - - description: The id of the conversation model to delete - in: path - name: modelId - required: true - schema: + 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 - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/ConversationModelSchema' - description: The conversation model was successfully deleted - summary: Delete a conversation model - tags: - - conversations - get: - description: Retrieve a conversation model - operationId: retrieveConversationModel - parameters: - - description: The id of the conversation model to retrieve - in: path - name: modelId - required: true - schema: + 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 - 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 - parameters: - - description: The id of the conversation model to update - in: path - name: modelId - required: true - schema: + query_by: + description: A list of `string` fields that should be queried against. Multiple + fields are separated with a comma. type: string - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/ConversationModelUpdateSchema' - required: true - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/ConversationModelSchema' - description: The conversation model was successfully updated - summary: Update a conversation model - tags: - - conversations - /curation_sets: - get: - description: Retrieve all curation sets - operationId: retrieveCurationSets - responses: - '200': - content: - application/json: - schema: - items: - $ref: '#/components/schemas/CurationSetSchema' - type: array - description: List of all curation sets - summary: List all curation sets - tags: - - curation_sets - /curation_sets/{curationSetName}: - delete: - description: Delete a specific curation set by its name - operationId: deleteCurationSet - parameters: - - description: The name of the curation set to delete - in: path - name: curationSetName - required: true - schema: + 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 - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/CurationSetDeleteSchema' - description: Curation set successfully deleted - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Curation set not found - summary: Delete a curation set - tags: - - curation_sets - get: - description: Retrieve a specific curation set by its name - operationId: retrieveCurationSet - parameters: - - description: The name of the curation set to retrieve - in: path - name: curationSetName - required: true - schema: + 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 - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/CurationSetRetrieveSchema' - description: Curation set fetched - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Curation set not found - summary: Retrieve a curation set - tags: - - curation_sets - put: - description: Create or update a curation set with the given name - operationId: upsertCurationSet - parameters: - - description: The name of the curation set to create/update - in: path - name: curationSetName - required: true - schema: + 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 - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/CurationSetCreateSchema' - description: The curation set to be created/updated - required: true - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/CurationSetSchema' - description: Curation set successfully created/updated - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - summary: Create or update a curation set - tags: - - curation_sets - /curation_sets/{curationSetName}/items: - get: - description: Retrieve all curation items in a set - operationId: retrieveCurationSetItems - parameters: - - description: The name of the curation set to retrieve items for - in: path - name: curationSetName - required: true - schema: + 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 - responses: - '200': - content: - application/json: - schema: - items: - $ref: '#/components/schemas/CurationItemSchema' - type: array - description: List of curation items - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Curation set not found - summary: List items in a curation set - tags: - - curation_sets - /curation_sets/{curationSetName}/items/{itemId}: - delete: - description: Delete a specific curation item by its id - operationId: deleteCurationSetItem - parameters: - - description: The name of the curation set - in: path - name: curationSetName - required: true - schema: + 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 - - description: The id of the curation item to delete - in: path - name: itemId - required: true - schema: + 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 - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/CurationItemDeleteSchema' - description: Curation item successfully deleted - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Curation item not found - summary: Delete a curation set item - tags: - - curation_sets - get: - description: Retrieve a specific curation item by its id - operationId: retrieveCurationSetItem - parameters: - - description: The name of the curation set - in: path - name: curationSetName - required: true - schema: + facet_by: + description: A list of fields that will be used for faceting your results + on. Separate multiple fields with a comma. type: string - - description: The id of the curation item to retrieve - in: path - name: itemId - required: true - schema: + 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 - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/CurationItemSchema' - description: Curation item fetched - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Curation item not found - summary: Retrieve a curation set item - tags: - - curation_sets - put: - description: Create or update a curation set item with the given id - operationId: upsertCurationSetItem - parameters: - - description: The name of the curation set - in: path - name: curationSetName - required: true - schema: + 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 - - description: The id of the curation item to upsert - in: path - name: itemId - required: true - schema: + 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 - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/CurationItemCreateSchema' - description: The curation item to be created/updated - required: true - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/CurationItemSchema' - description: Curation item successfully created/updated - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - summary: Create or update a curation set item - tags: - - curation_sets - /debug: - get: - description: Print debugging information - operationId: debug - responses: - '200': - content: - application/json: - schema: - properties: - version: - type: string - type: object - description: Debugging information - summary: Print debugging information - tags: - - debug - /health: - get: - description: Checks if Typesense server is ready to accept requests. - operationId: health - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/HealthStatus' - description: Search service is ready for requests. - summary: Checks if Typesense server is ready to accept requests. - tags: - - health - /keys: - get: - operationId: getKeys - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiKeysResponse' - description: List of all keys - summary: Retrieve (metadata about) all keys. - tags: - - keys - post: - 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: - content: - application/json: - schema: - $ref: '#/components/schemas/ApiKeySchema' - description: The object that describes API key scope - responses: - '201': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiKey' - description: Created API key - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - '409': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: API key generation conflict - summary: Create an API Key - tags: - - keys - /keys/{keyId}: - delete: - operationId: deleteKey - parameters: - - description: The ID of the key to delete - in: path - name: keyId - required: true - schema: - format: int64 + 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 - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiKeyDeleteResponse' - description: The key referenced by the ID - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Key not found - summary: Delete an API key given its ID. - tags: - - keys - get: - 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: - - description: The ID of the key to retrieve - in: path - name: keyId - required: true - schema: - format: int64 + 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 - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiKey' - description: The key referenced by the ID - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: The key was not found - summary: Retrieve (metadata about) a key - tags: - - keys - /metrics.json: - get: - description: Retrieve the metrics. - operationId: retrieveMetrics - responses: - '200': - content: - application/json: - schema: - type: object - description: Metrics fetched. - summary: Get current RAM, CPU, Disk & Network usage metrics. - tags: - - operations - /multi_search: - post: - 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. - operationId: multiSearch - parameters: - - in: query - name: filter_curated_hits - schema: - 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 + 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 + enable_analytics: + description: > + Flag for enabling/disabling analytics aggregation for specific search + queries (for e.g. those originating from a test script). + type: boolean + 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 - - in: query - name: highlight_full_fields - schema: - description: List of fields which should be highlighted fully without snippeting + 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 - - in: query - name: synonym_num_typos - schema: - description: 'Allow synonym resolution on typo-corrected words in the query. - Default: 0 - - ' + remote_embedding_timeout_ms: + description: > + Timeout (in milliseconds) for fetching remote embeddings. type: integer - - in: query - name: include_fields - schema: - description: List of fields from the document to include in the search result + 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 - - in: query - name: pinned_hits - 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`. - - ' + 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 - - in: query - name: facet_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". + facet_return_parent: + description: > + Comma separated string of nested facet fields whose parent object should + be returned in facet response. type: string - - in: query - name: group_missing_values - 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 - - ' + voice_query: + description: > + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + conversation: + description: > + Enable conversational search. type: boolean - - in: query - name: max_extra_prefix - 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 - - in: query - name: highlight_fields - schema: - description: 'A list of custom fields that must be highlighted even if you - don''t query for them - - ' + conversation_model_id: + description: > + The Id of Conversation Model to be used. type: string - - in: query - name: per_page - schema: - description: 'Number of results to fetch per page. Default: 10' - type: integer - - in: query - name: snippet_threshold - schema: - description: 'Field values under this length will be fully highlighted, - instead of showing a snippet of relevant portion. Default: 30 - - ' - type: integer - - in: query - name: infix - 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 + 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 - - in: query - name: conversation - schema: - description: 'Enable conversational search. - - ' + MultiSearchSearchesParameter: + type: object + required: + - searches + properties: + union: type: boolean - - in: query - name: highlight_end_tag - schema: - description: 'The end tag used for the highlighted snippets. Default: `` - - ' + default: false + 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 - - in: query - name: vector_query - schema: - description: 'Vector query expression for fetching documents "closest" to - a given query/document vector. - - ' + 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 + AnalyticsEvent: + type: object + required: + - name + - event_type + - data + properties: + name: type: string - - in: query - name: hidden_hits - 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`. - - ' + description: Name of the analytics rule this event corresponds to + event_type: type: string - - in: query - name: remote_embedding_timeout_ms - schema: - description: 'Timeout (in milliseconds) for fetching remote embeddings. - - ' - type: integer - - in: query - name: query_by - schema: - description: A list of `string` fields that should be queried against. Multiple - fields are separated with a comma. + description: Type of event (e.g., click, conversion, query, visit) + data: + type: object + description: Event payload + properties: + user_id: + type: string + doc_id: + type: string + doc_ids: + type: array + items: + type: string + q: + type: string + analytics_tag: + type: string + AnalyticsEventsResponse: + type: object + required: + - events + properties: + events: + type: array + items: + type: object + properties: + name: + type: string + event_type: + type: string + collection: + type: string + timestamp: + type: integer + format: int64 + user_id: + type: string + doc_id: + type: string + doc_ids: + type: array + items: + type: string + query: + type: string + AnalyticsRuleCreate: + type: object + required: + - name + - type + - collection + - event_type + properties: + name: + type: string + type: + $ref: "#/components/schemas/AnalyticsRuleType" + collection: + type: string + event_type: + type: string + rule_tag: + type: string + params: + type: object + properties: + destination_collection: + type: string + limit: + type: integer + capture_search_requests: + type: boolean + meta_fields: + type: array + items: + type: string + expand_query: + type: boolean + counter_field: + type: string + weight: + type: integer + AnalyticsRuleType: + type: string + enum: + - popular_queries + - nohits_queries + - counter + - log + AnalyticsRuleUpdate: + type: object + description: Fields allowed to update on an analytics rule + properties: + name: type: string - - in: query - name: enable_analytics - schema: - default: true - description: 'Flag for enabling/disabling analytics aggregation for specific - search queries (for e.g. those originating from a test script). - - ' - type: boolean - - in: query - name: exhaustive_search - 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 - - in: query - name: enable_synonyms - schema: - 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 - - ' - type: boolean - - in: query - name: page - schema: - description: Results from this specific page number would be fetched. - type: integer - - in: query - name: enable_typos_for_alpha_numerical_tokens - schema: - description: 'Set this parameter to false to disable typos on alphanumerical - query tokens. Default: true. - - ' - type: boolean - - in: query - name: filter_by - schema: - description: Filter conditions for refining youropen api validator search - results. Separate multiple conditions with &&. - example: 'num_employees:>100 && country: [USA, UK]' + rule_tag: type: string - - in: query - name: prioritize_exact_match - schema: - default: true - description: 'Set this parameter to true to ensure that an exact match is - ranked above the others - - ' - type: boolean - - in: query - name: prioritize_token_position - schema: - default: false - description: 'Make Typesense prioritize documents where the query words - appear earlier in the text. - - ' - type: boolean - - in: query - name: typo_tokens_threshold - 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 - - ' + params: + type: object + properties: + destination_collection: + type: string + limit: + type: integer + capture_search_requests: + type: boolean + meta_fields: + type: array + items: + type: string + expand_query: + type: boolean + counter_field: + type: string + weight: + type: integer + AnalyticsRule: + allOf: + - $ref: '#/components/schemas/AnalyticsRuleCreate' + - type: object + AnalyticsStatus: + type: object + properties: + popular_prefix_queries: type: integer - - in: query - name: group_by - 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 - - in: query - name: min_len_2typo - 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. - - ' + nohits_prefix_queries: type: integer - - in: query - name: pre_segmented_query - schema: - default: false - 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 - - in: query - name: max_extra_suffix - 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. + log_prefix_queries: type: integer - - in: query - name: q - 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 - - in: query - name: conversation_model_id - schema: - description: 'The Id of Conversation Model to be used. - - ' - type: string - - in: query - name: group_limit - 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 - - ' + query_log_events: type: integer - - in: query - name: max_facet_values - schema: - description: Maximum number of facet values to be returned. + query_counter_events: type: integer - - in: query - name: enable_overrides - schema: - default: false - 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 - - in: query - name: facet_return_parent - schema: - description: 'Comma separated string of nested facet fields whose parent - object should be returned in facet response. - - ' - type: string - - in: query - name: remote_embedding_num_tries - schema: - description: 'Number of times to retry fetching remote embeddings. - - ' + doc_log_events: type: integer - - in: query - name: facet_by - schema: - description: A list of fields that will be used for faceting your results - on. Separate multiple fields with a comma. + doc_counter_events: + type: integer + 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 - - in: query - name: sort_by - 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` + required: + - stopwords + example: | + {"stopwords": ["Germany", "France", "Italy"], "locale": "en"} + StopwordsSetSchema: + type: object + properties: + id: type: string - - in: query - name: synonym_prefix - schema: - description: 'Allow synonym resolution on word prefixes in the query. Default: - false - - ' - type: boolean - - in: query - name: highlight_start_tag - schema: - description: 'The start tag used for the highlighted snippets. Default: - `` - - ' + stopwords: + type: array + items: + type: string + locale: type: string - - in: query - name: stopwords - 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. - - ' + 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 - - in: query - name: min_len_1typo - 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 - - in: query - name: exclude_fields - schema: - description: List of fields from the document to exclude in the search result + 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 + up to 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 - - in: query - name: use_cache - schema: - description: 'Enable server side caching of search query results. By default, - caching is disabled. - - ' - type: boolean - - in: query - name: highlight_affix_num_tokens - schema: - description: 'The number of tokens that should surround the highlighted - text on each side. Default: 4 - - ' - type: integer - - in: query - name: search_cutoff_ms - 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 - - in: query - name: drop_tokens_mode - schema: - $ref: '#/components/schemas/DropTokensMode' - - in: query - name: num_typos - schema: - description: 'The number of typographical errors (1 or 2) that would be - tolerated. Default: 2 - - ' + 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 - - in: query - name: prioritize_num_matching_fields - schema: - default: true - description: 'Make Typesense prioritize documents where the query words - appear in more number of fields. - - ' - type: boolean - - in: query - name: prefix - 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. + api_key: + description: The LLM service's API Key type: string - - in: query - name: voice_query - schema: - description: 'The base64 encoded audio file in 16 khz 16-bit WAV format. - - ' + history_collection: type: string - - in: query - name: conversation_id - schema: - description: 'The Id of a previous conversation to continue, this tells - Typesense to include prior context when communicating with the LLM. - - ' + description: Typesense collection that stores the historical conversations + account_id: + description: LLM service's account ID (only applicable for Cloudflare) type: string - - in: query - name: query_by_weights - 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. + system_prompt: + description: The system prompt that contains special instructions to the + LLM type: string - - in: query - name: enable_typos_for_numerical_tokens - schema: - default: true - description: 'Make Typesense disable typos for numerical tokens. - - ' - type: boolean - - in: query - name: limit - schema: - description: 'Number of hits to fetch. Can be used as an alternative to - the per_page parameter. Default: 10. - - ' + ttl: type: integer - - in: query - name: drop_tokens_threshold - 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 - - ' + 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 - - in: query - name: text_match_type - 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. + vllm_url: + description: URL of vLLM service type: string - - in: query - name: preset - schema: - description: 'Search using a bunch of search parameters by setting this - parameter to the name of the existing Preset. - - ' + 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 - - in: query - name: override_tags - schema: - description: Comma separated list of tags to trigger the curations rules - that match the tags. + 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 - - in: query - name: facet_strategy - schema: - description: 'Choose the underlying faceting strategy used. Comma separated - string of allows values: exhaustive, top_values or automatic (default). - - ' + description: Name of the NL model to use + api_key: type: string - - in: query - name: offset - 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 - - in: query - name: cache_ttl - 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 - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/MultiSearchSearchesParameter' - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/MultiSearchResult' - description: Search results - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - summary: send multiple search requests in a single HTTP request - tags: - - documents - /nl_search_models: - get: - description: Retrieve all NL search models. - operationId: retrieveAllNLSearchModels - responses: - '200': - content: - application/json: - schema: - items: - $ref: '#/components/schemas/NLSearchModelSchema' - type: array - description: List of all NL search models - summary: List all NL search models - tags: - - nl_search_models - post: - description: Create a new NL search model. - operationId: createNLSearchModel - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/NLSearchModelCreateSchema' - description: The NL search model to be created - required: true - responses: - '201': - content: - application/json: - schema: - $ref: '#/components/schemas/NLSearchModelSchema' - description: NL search model successfully created - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - summary: Create a NL search model - tags: - - nl_search_models - /nl_search_models/{modelId}: - delete: - description: Delete a specific NL search model by its ID. - operationId: deleteNLSearchModel - parameters: - - description: The ID of the NL search model to delete - in: path - name: modelId - required: true - schema: + 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 - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/NLSearchModelDeleteSchema' - description: NL search model successfully deleted - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: NL search model not found - summary: Delete a NL search model - tags: - - nl_search_models - get: - description: Retrieve a specific NL search model by its ID. - operationId: retrieveNLSearchModel - parameters: - - description: The ID of the NL search model to retrieve - in: path - name: modelId - required: true - schema: + 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 - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/NLSearchModelSchema' - description: NL search model fetched - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: NL search model not found - summary: Retrieve a NL search model - tags: - - nl_search_models - put: - description: Update an existing NL search model. - operationId: updateNLSearchModel - parameters: - - description: The ID of the NL search model to update - in: path - name: modelId - required: true - schema: + description: API version for the NL model service + project_id: type: string - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/NLSearchModelUpdateSchema' - description: The NL search model fields to update - required: true - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/NLSearchModelSchema' - description: NL search model successfully updated - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: NL search model not found - summary: Update a NL search model - tags: - - nl_search_models - /operations/cache/clear: - post: - description: Clear the cached responses of search requests that are sent with - `use_cache` parameter in the LRU cache. - operationId: clearCache - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/SuccessStatus' - description: Clear cache succeeded. - summary: Clear the cached responses of search requests in the LRU cache. - tags: - - operations - /operations/db/compact: - post: - description: Typesense uses RocksDB to store your documents on the disk. If - you do frequent writes or updates, you could benefit from running a compaction - of the underlying RocksDB database. This could reduce the size of the database - and decrease read latency. While the database will not block during this operation, - we recommend running it during off-peak hours. - operationId: compactDb - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/SuccessStatus' - description: Compacting the on-disk database succeeded. - summary: Compacting the on-disk database - tags: - - operations - /operations/schema_changes: - get: - 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': - content: - application/json: - schema: - items: - $ref: '#/components/schemas/SchemaChangeStatus' - type: array - description: List of schema changes in progress - summary: Get the status of in-progress schema change operations - tags: - - operations - /operations/snapshot: - post: - 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: - - description: The directory on the server where the snapshot should be saved. - in: query - name: snapshot_path - required: true - schema: + 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 + SynonymItemUpsertSchema: + type: object + required: + - synonyms + properties: + synonyms: + type: array + description: Array of words that should be considered as synonyms + items: + type: string + root: + type: string + description: For 1-way synonyms, indicates the root word that words in the + synonyms parameter map to + 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 + SynonymItemSchema: + allOf: + - type: object + required: + - id + properties: + id: + type: string + description: Unique identifier for the synonym item + - $ref: "#/components/schemas/SynonymItemUpsertSchema" + SynonymSetCreateSchema: + type: object + required: + - items + properties: + items: + type: array + description: Array of synonym items + items: + $ref: "#/components/schemas/SynonymItemSchema" + SynonymSetSchema: + allOf: + - $ref: "#/components/schemas/SynonymSetCreateSchema" + - type: object + required: + - name + properties: + name: + type: string + description: Name of the synonym set + SynonymSetsRetrieveSchema: + type: object + required: + - synonym_sets + properties: + synonym_sets: + type: array + description: Array of synonym sets + items: + $ref: "#/components/schemas/SynonymSetSchema" + SynonymSetDeleteSchema: + type: object + required: + - name + properties: + name: type: string - responses: - '201': - content: - application/json: - schema: - $ref: '#/components/schemas/SuccessStatus' - description: Snapshot is created. - summary: Creates a point-in-time snapshot of a Typesense node's state and data - in the specified directory. - tags: - - operations - /operations/vote: - post: - 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': - content: - application/json: - schema: - $ref: '#/components/schemas/SuccessStatus' - description: Re-election is performed. - summary: Triggers a follower node to initiate the raft voting process, which - triggers leader re-election. - tags: - - operations - /presets: - get: - description: Retrieve the details of all presets - operationId: retrieveAllPresets - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/PresetsRetrieveSchema' - description: Presets fetched. - summary: Retrieves all presets. - tags: - - presets - /presets/{presetId}: - delete: - description: Permanently deletes a preset, given it's name. - operationId: deletePreset - parameters: - - description: The ID of the preset to delete. - example: listing_view - in: path - name: presetId - required: true - schema: + description: Name of the deleted synonym set + SynonymItemDeleteSchema: + type: object + required: + - id + properties: + id: type: string - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/PresetDeleteSchema' - description: Preset deleted. - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Preset not found. - summary: Delete a preset. - tags: - - presets - get: - description: Retrieve the details of a preset, given it's name. - operationId: retrievePreset - parameters: - - description: The ID of the preset to retrieve. - example: listing_view - in: path - name: presetId - required: true - schema: + description: ID of the deleted synonym item + CurationItemCreateSchema: + type: object + required: + - rule + properties: + rule: + $ref: '#/components/schemas/CurationRule' + 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/CurationInclude' + excludes: + type: array + description: List of document `id`s that should be excluded from the search + results. + items: + $ref: '#/components/schemas/CurationExclude' + filter_by: type: string - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/PresetSchema' - description: Preset fetched. - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Preset not found. - summary: Retrieves a preset. - tags: - - presets - put: - description: Create or update an existing preset. - operationId: upsertPreset - parameters: - - description: The name of the preset set to upsert. - example: listing_view - in: path - name: presetId - required: true - schema: + description: > + A filter by clause that is applied to any search query that matches the + curation rule. + remove_matched_tokens: + type: boolean + description: > + Indicates whether search query tokens that exist in the curation'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 - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/PresetUpsertSchema' - description: The stopwords set to upsert. - required: true - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/PresetSchema' - description: Preset successfully upserted. - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - summary: Upserts a preset. - tags: - - presets - /stats.json: - get: - description: Retrieve the stats about API endpoints. - operationId: retrieveAPIStats - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/APIStatsResponse' - description: Stats fetched. - summary: Get stats about API endpoints. - tags: - - operations - /stemming/dictionaries: - get: - description: Retrieve a list of all available stemming dictionaries. - operationId: listStemmingDictionaries - responses: - '200': - content: - application/json: - schema: - properties: - dictionaries: - example: - - irregular-plurals - - company-terms - items: - type: string - type: array - type: object - description: List of all dictionaries - summary: List all stemming dictionaries - tags: - - stemming - /stemming/dictionaries/import: - post: - description: Upload a JSONL file containing word mappings to create or update - a stemming dictionary. - operationId: importStemmingDictionary - parameters: - - description: The ID to assign to the dictionary - example: irregular-plurals - in: query - name: id - required: true - schema: + description: > + A sort by clause that is applied to any search query that matches the + curation rule. + replace_query: type: string - requestBody: - content: - application/json: - schema: - example: '{"word": "people", "root": "person"} - - {"word": "children", "root": "child"} - - ' - type: string - description: The JSONL file containing word mappings - required: true - responses: - '200': - content: - application/octet-stream: - schema: - example: '{"word": "people", "root": "person"} {"word": "children", - "root": "child"} - - ' - type: string - description: Dictionary successfully imported - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - summary: Import a stemming dictionary - tags: - - stemming - /stemming/dictionaries/{dictionaryId}: - get: - description: Fetch details of a specific stemming dictionary. - operationId: getStemmingDictionary - parameters: - - description: The ID of the dictionary to retrieve - example: irregular-plurals - in: path - name: dictionaryId - required: true - schema: + description: > + Replaces the current search query with this value, when the search query + matches the curation 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 curation + will be active. You can use this to create 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 curation + will be active. You can use this to create rules that stop applying after + a period of time. + stop_processing: + type: boolean + description: > + When set to true, curation processing will stop at the first matching + rule. When set to false curation processing will continue and multiple + curation actions will be triggered in sequence. Curations are processed + in the lexical sort order of their id field. + id: + type: string + description: ID of the curation item + CurationItemSchema: + allOf: + - $ref: '#/components/schemas/CurationItemCreateSchema' + - type: object + required: + - id + properties: + id: + type: string + CurationSetCreateSchema: + type: object + required: + - items + properties: + items: + type: array + description: Array of curation items + items: + $ref: '#/components/schemas/CurationItemCreateSchema' + description: type: string - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/StemmingDictionary' - description: Stemming dictionary details - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Dictionary not found - summary: Retrieve a stemming dictionary - tags: - - stemming - /stopwords: - get: - description: Retrieve the details of all stopwords sets - operationId: retrieveStopwordsSets - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/StopwordsSetsRetrieveAllSchema' - description: Stopwords sets fetched. - summary: Retrieves all stopwords sets. - tags: - - stopwords - /stopwords/{setId}: - delete: - description: Permanently deletes a stopwords set, given it's name. - operationId: deleteStopwordsSet - parameters: - - description: The ID of the stopwords set to delete. - example: countries - in: path - name: setId - required: true - schema: + description: Optional description for the curation set + CurationSetSchema: + allOf: + - $ref: '#/components/schemas/CurationSetCreateSchema' + - type: object + required: + - name + properties: + name: + type: string + CurationRule: + type: object + properties: + tags: + type: array + description: List of tag values to associate with this curation rule. + items: + type: string + query: type: string - responses: - '200': - content: - application/json: - schema: - example: '{"id": "countries"} - - ' - properties: - id: - type: string - required: - - id - type: object - description: Stopwords set rule deleted. - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Stopwords set not found. - summary: Delete a stopwords set. - tags: - - stopwords - get: - description: Retrieve the details of a stopwords set, given it's name. - operationId: retrieveStopwordsSet - parameters: - - description: The ID of the stopwords set to retrieve. - example: countries - in: path - name: setId - required: true - schema: + description: Indicates what search queries should be curated + match: type: string - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/StopwordsSetRetrieveSchema' - description: Stopwords set fetched. - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Stopwords set not found. - summary: Retrieves a stopwords set. - tags: - - stopwords - put: - 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: - - description: The ID of the stopwords set to upsert. - example: countries - in: path - name: setId - required: true - schema: + 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 - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/StopwordsSetUpsertSchema' - description: The stopwords set to upsert. - required: true - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/StopwordsSetSchema' - description: Stopwords set successfully upserted. - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details. - summary: Upserts a stopwords set. - tags: - - stopwords - /synonym_sets: - get: - description: Retrieve all synonym sets - operationId: retrieveSynonymSets - responses: - '200': - content: - application/json: - schema: - items: - $ref: '#/components/schemas/SynonymSetSchema' - type: array - description: List of all synonym sets - summary: List all synonym sets - tags: - - synonyms - /synonym_sets/{synonymSetName}: - delete: - description: Delete a specific synonym set by its name - operationId: deleteSynonymSet - parameters: - - description: The name of the synonym set to delete - in: path - name: synonymSetName - required: true - schema: + description: > + Indicates that the curation should apply when the filter_by parameter + in a search query exactly matches the string specified here (including + backticks, spaces, brackets, etc). + CurationInclude: + type: object + required: + - id + - position + properties: + id: type: string - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/SynonymSetDeleteSchema' - description: Synonym set successfully deleted - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Synonym set not found - summary: Delete a synonym set - tags: - - synonyms - get: - description: Retrieve a specific synonym set by its name - operationId: retrieveSynonymSet - parameters: - - description: The name of the synonym set to retrieve - in: path - name: synonymSetName - required: true - schema: + description: document id that should be included + position: + type: integer + description: position number where document should be included in the search + results + CurationExclude: + type: object + required: + - id + properties: + id: type: string - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/SynonymSetRetrieveSchema' - description: Synonym set fetched - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Synonym set not found - summary: Retrieve a synonym set - tags: - - synonyms - put: - description: Create or update a synonym set with the given name - operationId: upsertSynonymSet - parameters: - - description: The name of the synonym set to create/update - in: path - name: synonymSetName - required: true - schema: + description: document id that should be excluded from the search results. + CurationSetDeleteSchema: + type: object + required: + - name + properties: + name: + type: string + description: Name of the deleted curation set + CurationItemDeleteSchema: + type: object + required: + - id + properties: + id: type: string - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/SynonymSetCreateSchema' - description: The synonym set to be created/updated - required: true - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/SynonymSetSchema' - description: Synonym set successfully created/updated - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - summary: Create or update a synonym set - tags: - - synonyms - /synonym_sets/{synonymSetName}/items: - get: - description: Retrieve all synonym items in a set - operationId: retrieveSynonymSetItems - parameters: - - description: The name of the synonym set to retrieve items for - in: path - name: synonymSetName - required: true - schema: + description: ID of the deleted curation item + AnalyticsEventsRetrieveParams: + type: object + properties: + user_id: type: string - responses: - '200': - content: - application/json: - schema: - items: - $ref: '#/components/schemas/SynonymItemSchema' - type: array - description: List of synonym items - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Synonym set not found - summary: List items in a synonym set - tags: - - synonyms - /synonym_sets/{synonymSetName}/items/{itemId}: - delete: - description: Delete a specific synonym item by its id - operationId: deleteSynonymSetItem - parameters: - - description: The name of the synonym set - in: path - name: synonymSetName - required: true - schema: + name: type: string - - description: The id of the synonym item to delete - in: path - name: itemId - required: true - schema: + description: Analytics rule name + n: + type: integer + description: Number of events to return (max 1000) + required: + - user_id + - name + - n + 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 - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/SynonymItemDeleteSchema' - description: Synonym item successfully deleted - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Synonym item not found - summary: Delete a synonym set item - tags: - - synonyms - get: - description: Retrieve a specific synonym item by its id - operationId: retrieveSynonymSetItem - parameters: - - description: The name of the synonym set - in: path - name: synonymSetName - required: true - schema: + include_fields: + description: List of fields from the document to include in the search result type: string - - description: The id of the synonym item to retrieve - in: path - name: itemId - required: true - schema: + exclude_fields: + description: List of fields from the document to exclude in the search result type: string - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/SynonymItemSchema' - description: Synonym item fetched - '404': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Synonym item not found - summary: Retrieve a synonym set item - tags: - - synonyms - put: - description: Create or update a synonym set item with the given id - operationId: upsertSynonymSetItem - parameters: - - description: The name of the synonym set - in: path - name: synonymSetName - required: true - schema: + UpdateDocumentsParameters: + type: object + properties: + filter_by: type: string - - description: The id of the synonym item to upsert - in: path - name: itemId - required: true - schema: + example: "num_employees:>100 && country: [USA, UK]" + DeleteDocumentsParameters: + type: object + required: + - filter_by + properties: + filter_by: type: string - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/SynonymItemSchema' - description: The synonym item to be created/updated - required: true - responses: - '200': - content: - application/json: - schema: - $ref: '#/components/schemas/SynonymItemSchema' - description: Synonym item successfully created/updated - '400': - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: Bad request, see error message for details - summary: Create or update a synonym set item - tags: - - synonyms -security: -- api_key_header: [] -servers: -- description: Typesense Server - url: '{protocol}://{hostname}:{port}' - variables: - hostname: - default: localhost - description: The hostname of your Typesense server - port: - default: '8108' - description: The port of your Typesense server - protocol: - default: http - description: The protocol of your Typesense server -tags: -- description: A collection is defined by a schema - externalDocs: - description: Find out more - url: https://typesense.org/api/#create-collection - name: collections -- 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: documents -- 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: analytics -- 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: keys -- description: Debugging information - name: debug -- description: Manage Typesense cluster - externalDocs: - description: Find out more - url: https://typesense.org/docs/28.0/api/cluster-operations.html - name: operations -- description: Manage stopwords sets - externalDocs: - description: Find out more - url: https://typesense.org/docs/28.0/api/stopwords.html - name: stopwords -- description: Store and reference search parameters - externalDocs: - description: Find out more - url: https://typesense.org/docs/28.0/api/search.html#presets - name: presets -- description: Conversational Search (RAG) - externalDocs: - description: Find out more - url: https://typesense.org/docs/28.0/api/conversational-search-rag.html - name: conversations -- description: Manage synonyms - externalDocs: - description: Find out more - url: https://typesense.org/docs/28.0/api/synonyms.html - name: synonyms -- description: Manage curation sets - name: curation_sets -- description: Manage stemming dictionaries - externalDocs: - description: Find out more - url: https://typesense.org/docs/28.0/api/stemming.html - name: stemming -- description: Manage NL search models - externalDocs: - description: Find out more - url: https://typesense.org/docs/29.0/api/natural-language-search.html - name: nl_search_models + 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 + GetCollectionsParameters: + type: object + properties: + exclude_fields: + description: Comma-separated list of fields from the collection to exclude + from the response + type: string + limit: + description: > + Number of collections to fetch. Default: returns all collections. + type: integer + offset: + description: Identifies the starting point to return collections when paginating. + type: integer + securitySchemes: + api_key_header: + type: apiKey + name: X-TYPESENSE-API-KEY + in: header From 744ebbbb9b74da51505436847829494170828ee0 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Thu, 11 Dec 2025 17:01:39 +0700 Subject: [PATCH 09/21] feat: v30 synonym sets APIs --- Sources/Typesense/Client.swift | 9 + Sources/Typesense/Collection.swift | 4 - Sources/Typesense/SynonymSet.swift | 51 ++++++ Sources/Typesense/SynonymSetItem.swift | 43 +++++ Sources/Typesense/SynonymSetItems.swift | 45 +++++ Sources/Typesense/SynonymSets.swift | 45 +++++ Sources/Typesense/Synonyms.swift | 61 ------- Tests/TypesenseTests/SynonymSetsTests.swift | 176 ++++++++++++++++++++ Tests/TypesenseTests/SynonymTests.swift | 149 ----------------- Tests/TypesenseTests/TestUtils.swift | 38 +++-- 10 files changed, 396 insertions(+), 225 deletions(-) create mode 100644 Sources/Typesense/SynonymSet.swift create mode 100644 Sources/Typesense/SynonymSetItem.swift create mode 100644 Sources/Typesense/SynonymSetItems.swift create mode 100644 Sources/Typesense/SynonymSets.swift delete mode 100644 Sources/Typesense/Synonyms.swift create mode 100644 Tests/TypesenseTests/SynonymSetsTests.swift delete mode 100644 Tests/TypesenseTests/SynonymTests.swift diff --git a/Sources/Typesense/Client.swift b/Sources/Typesense/Client.swift index fcb619e..0a6eb77 100644 --- a/Sources/Typesense/Client.swift +++ b/Sources/Typesense/Client.swift @@ -65,4 +65,13 @@ public struct Client { public func stopword(_ stopwordsSetId: String) -> Stopword { return Stopword(apiCall: apiCall, stopwordsSetId: stopwordsSetId) } + + public func synonymSets() -> SynonymSets { + return SynonymSets(apiCall: apiCall) + } + + public func synonymSet(_ synonymSetName: String) -> SynonymSet { + return SynonymSet(apiCall: apiCall, synonymSetName: synonymSetName) + } + } diff --git a/Sources/Typesense/Collection.swift b/Sources/Typesense/Collection.swift index 756a496..ee245a0 100644 --- a/Sources/Typesense/Collection.swift +++ b/Sources/Typesense/Collection.swift @@ -39,10 +39,6 @@ public struct Collection { return (nil, response) } - public func synonyms() -> Synonyms { - return Synonyms(apiCall: apiCall, collectionName: self.collectionName) - } - private func endpointPath() throws -> String { return "\(Collections.RESOURCEPATH)/\(try collectionName.encodeURL())" } diff --git a/Sources/Typesense/SynonymSet.swift b/Sources/Typesense/SynonymSet.swift new file mode 100644 index 0000000..f5ae929 --- /dev/null +++ b/Sources/Typesense/SynonymSet.swift @@ -0,0 +1,51 @@ +import Foundation +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +public struct SynonymSet { + var apiCall: ApiCall + let synonymSetName: String + + + init(apiCall: ApiCall, synonymSetName: String) { + self.apiCall = apiCall + self.synonymSetName = synonymSetName + } + + public func items() -> SynonymSetItems { + return SynonymSetItems(apiCall: apiCall, synonymSetName: synonymSetName) + } + + public func item(_ name: String) -> SynonymSetItem { + return SynonymSetItem(apiCall: apiCall, synonymSetName: synonymSetName, itemName: name) + } + + + public func retrieve() async throws -> (SynonymSetSchema?, URLResponse?) { + let (data, response) = try await apiCall.get(endPoint: endpointPath(synonymSetName)) + if let result = data { + let synonym = try decoder.decode(SynonymSetSchema.self, from: result) + return (synonym, response) + } + return (nil, nil) + } + + public func delete() async throws -> (SynonymSetDeleteSchema?, URLResponse?) { + let (data, response) = try await apiCall.delete(endPoint: endpointPath(synonymSetName)) + if let result = data { + let synonym = try decoder.decode(SynonymSetDeleteSchema.self, from: result) + return (synonym, response) + } + return (nil, response) + } + + private func endpointPath(_ operation: String? = nil) throws -> String { + let baseEndpoint = SynonymSets.RESOURCE_PATH + if let operation: String = operation { + return "\(baseEndpoint)/\(try operation.encodeURL())" + } else { + return baseEndpoint + } + } +} diff --git a/Sources/Typesense/SynonymSetItem.swift b/Sources/Typesense/SynonymSetItem.swift new file mode 100644 index 0000000..0187ffc --- /dev/null +++ b/Sources/Typesense/SynonymSetItem.swift @@ -0,0 +1,43 @@ +import Foundation +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +public struct SynonymSetItem { + var apiCall: ApiCall + let synonymSetName: String + let itemName: String + + init(apiCall: ApiCall, synonymSetName: String, itemName: String) { + self.apiCall = apiCall + self.synonymSetName = synonymSetName + self.itemName = itemName + } + + public func retrieve() async throws -> (SynonymItemSchema?, URLResponse?) { + let (data, response) = try await apiCall.get(endPoint: endpointPath(itemName)) + if let result = data { + let synonym = try decoder.decode(SynonymItemSchema.self, from: result) + return (synonym, response) + } + return (nil, nil) + } + + public func delete() async throws -> (SynonymItemDeleteSchema?, URLResponse?) { + let (data, response) = try await apiCall.delete(endPoint: endpointPath(itemName)) + if let result = data { + let synonym = try decoder.decode(SynonymItemDeleteSchema.self, from: result) + return (synonym, response) + } + return (nil, response) + } + + private func endpointPath(_ operation: String? = nil) throws -> String { + let baseEndpoint = try "\(SynonymSets.RESOURCE_PATH)/\(synonymSetName.encodeURL())/items" + if let operation: String = operation { + return "\(baseEndpoint)/\(try operation.encodeURL())" + } else { + return baseEndpoint + } + } +} diff --git a/Sources/Typesense/SynonymSetItems.swift b/Sources/Typesense/SynonymSetItems.swift new file mode 100644 index 0000000..f512935 --- /dev/null +++ b/Sources/Typesense/SynonymSetItems.swift @@ -0,0 +1,45 @@ +import Foundation +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +public struct SynonymSetItems { + var apiCall: ApiCall + let synonymSetName: String + + + init(apiCall: ApiCall, synonymSetName: String) { + self.apiCall = apiCall + self.synonymSetName = synonymSetName + } + + public func retrieve() async throws -> ([SynonymItemSchema]?, URLResponse?) { + let (data, response) = try await apiCall.get(endPoint: endpointPath()) + if let result = data { + let synonym = try decoder.decode([SynonymItemSchema].self, from: result) + return (synonym, response) + } + return (nil, response) + } + + public func upsert(_ id: String, _ schema: SynonymItemUpsertSchema) async throws -> (SynonymItemSchema?, URLResponse?) { + let schemaData = try encoder.encode(schema) + + let (data, response) = try await apiCall.put(endPoint: endpointPath(id), body: schemaData) + if let result = data { + let synonym = try decoder.decode(SynonymItemSchema.self, from: result) + return (synonym, response) + } + + return (nil, nil) + } + + private func endpointPath(_ operation: String? = nil) throws -> String { + let baseEndpoint = try "\(SynonymSets.RESOURCE_PATH)/\(synonymSetName.encodeURL())/items" + if let operation: String = operation { + return "\(baseEndpoint)/\(try operation.encodeURL())" + } else { + return baseEndpoint + } + } +} diff --git a/Sources/Typesense/SynonymSets.swift b/Sources/Typesense/SynonymSets.swift new file mode 100644 index 0000000..5975cc3 --- /dev/null +++ b/Sources/Typesense/SynonymSets.swift @@ -0,0 +1,45 @@ +import Foundation +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +public struct SynonymSets { + static let RESOURCE_PATH = "synonym_sets" + var apiCall: ApiCall + + + init(apiCall: ApiCall) { + self.apiCall = apiCall + } + + + public func upsert(_ id: String, _ schema: SynonymSetCreateSchema) async throws -> (SynonymSetSchema?, URLResponse?) { + let schemaData = try encoder.encode(schema) + + let (data, response) = try await apiCall.put(endPoint: endpointPath(id), body: schemaData) + if let result = data { + let synonym = try decoder.decode(SynonymSetSchema.self, from: result) + return (synonym, response) + } + + return (nil, nil) + } + + public func retrieve() async throws -> ([SynonymSetSchema]?, URLResponse?) { + let (data, response) = try await apiCall.get(endPoint: endpointPath()) + if let result = data { + let synonym = try decoder.decode([SynonymSetSchema].self, from: result) + return (synonym, response) + } + return (nil, response) + } + + private func endpointPath(_ operation: String? = nil) throws -> String { + let baseEndpoint = SynonymSets.RESOURCE_PATH + if let operation: String = operation { + return "\(baseEndpoint)/\(try operation.encodeURL())" + } else { + return baseEndpoint + } + } +} diff --git a/Sources/Typesense/Synonyms.swift b/Sources/Typesense/Synonyms.swift deleted file mode 100644 index 022d81c..0000000 --- a/Sources/Typesense/Synonyms.swift +++ /dev/null @@ -1,61 +0,0 @@ -import Foundation -#if canImport(FoundationNetworking) - import FoundationNetworking -#endif - -public struct Synonyms { - var apiCall: ApiCall - var collectionName: String - - init(apiCall: ApiCall, collectionName: String) { - self.apiCall = apiCall - self.collectionName = collectionName - } - - public func upsert(id: String, _ searchSynonym: SearchSynonymSchema) async throws -> (SearchSynonym?, URLResponse?) { - var schemaData: Data? = nil - schemaData = try encoder.encode(searchSynonym) - - if let validSchema = schemaData { - let (data, response) = try await apiCall.put(endPoint: endpointPath(id), body: validSchema) - if let result = data { - let synonym = try decoder.decode(SearchSynonym.self, from: result) - return (synonym, response) - } - - } - return (nil, nil) - } - - public func retrieve(id: String) async throws -> (SearchSynonym?, URLResponse?) { - let (data, response) = try await apiCall.get(endPoint: endpointPath(id)) - if let result = data { - let synonym = try decoder.decode(SearchSynonym.self, from: result) - return (synonym, response) - } - return (nil, nil) - } - - public func retrieve() async throws -> (SearchSynonymsResponse?, URLResponse?) { - let (data, response) = try await apiCall.get(endPoint: endpointPath()) - if let result = data { - let synonym = try decoder.decode(SearchSynonymsResponse.self, from: result) - return (synonym, response) - } - return (nil, nil) - } - - public func delete(id: String) async throws -> (Data?, URLResponse?) { - let (data, response) = try await apiCall.get(endPoint: endpointPath()) - return (data, response) - } - - private func endpointPath(_ operation: String? = nil) throws -> String { - let baseEndpoint = try "\(Collections.RESOURCEPATH)/\(collectionName.encodeURL())/synonyms" - if let operation: String = operation { - return "\(baseEndpoint)/\(try operation.encodeURL())" - } else { - return baseEndpoint - } - } -} diff --git a/Tests/TypesenseTests/SynonymSetsTests.swift b/Tests/TypesenseTests/SynonymSetsTests.swift new file mode 100644 index 0000000..a0cb544 --- /dev/null +++ b/Tests/TypesenseTests/SynonymSetsTests.swift @@ -0,0 +1,176 @@ +import XCTest +@testable import Typesense + +final class SynonymSetsTests: XCTestCase { + + override func setUp() async throws { + try await createSynonymSet() + } + + override func tearDown() async throws { + try await tearDownSynonymSets() + } + + func testSynonymRetrieveOne() async { + do { + let (data,_) = try await utilClient.synonymSet("clothing-synonyms").retrieve() + XCTAssertNotNil(data) + guard let validData = data else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual(validData.name, "clothing-synonyms") + XCTAssertEqual(validData.items[0].synonyms, ["blazer", "coat", "jacket"]) + XCTAssertEqual(validData.items[0].id, "coat-synonyms") + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error.localizedDescription) + XCTAssertTrue(false) + } + } + + func testSynonymRetrieveAll() async { + do { + let (data,_) = try await utilClient.synonymSets().retrieve() + XCTAssertNotNil(data) + guard let validData = data else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual(validData.count, 1) + XCTAssertEqual(validData[0].name, "clothing-synonyms") + XCTAssertEqual(validData[0].items[0].synonyms, ["blazer", "coat", "jacket"]) + XCTAssertEqual(validData[0].items[0].id, "coat-synonyms") + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error.localizedDescription) + XCTAssertTrue(false) + } + } + + func testSynonymSetDelete() async { + do { + let (data,_) = try await utilClient.synonymSet("clothing-synonyms").delete() + XCTAssertNotNil(data) + guard let validData = data else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual(validData.name, "clothing-synonyms") + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error.localizedDescription) + XCTAssertTrue(false) + } + + do{ + let _ = try await client.synonymSet("clothing-synonyms").retrieve() + } catch HTTPError.clientError(let code, _){ + if code != 404 { + XCTAssertTrue(false, "Synonym set should have been deleted") + } + } catch (let error) { + print(error) + XCTAssertTrue(false) + } + } + + func testSynonymSetItemRetrieveOne() async { + do { + let (data,_) = try await utilClient.synonymSet("clothing-synonyms").item("coat-synonyms").retrieve() + XCTAssertNotNil(data) + guard let validData = data else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual(validData.synonyms, ["blazer", "coat", "jacket"]) + XCTAssertEqual(validData.id, "coat-synonyms") + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error.localizedDescription) + XCTAssertTrue(false) + } + } + + func testSynonymSetItemDelete() async { + do { + let (data,_) = try await utilClient.synonymSet("clothing-synonyms").item("coat-synonyms").delete() + XCTAssertNotNil(data) + guard let validData = data else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual(validData.id, "coat-synonyms") + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error.localizedDescription) + XCTAssertTrue(false) + } + do{ + let _ = try await utilClient.synonymSet("clothing-synonyms").item("coat-synonyms").retrieve() + } catch HTTPError.clientError(let code, _){ + if code != 404 { + XCTAssertTrue(false, "Synonym set item should have been deleted") + } + } catch (let error) { + print(error) + XCTAssertTrue(false) + } + } + + func testSynonymSetItemUpsert() async { + do { + let (data,_) = try await utilClient.synonymSet("clothing-synonyms").items().upsert("coat-synonyms-2", SynonymItemUpsertSchema(synonyms: ["none"])) + XCTAssertNotNil(data) + guard let validData = data else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual(validData.synonyms, ["none"]) + XCTAssertEqual(validData.id, "coat-synonyms-2") + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error.localizedDescription) + XCTAssertTrue(false) + } + } + + func testSynonymSetItemRetrieveAll() async { + do { + let (data,_) = try await utilClient.synonymSet("clothing-synonyms").items().retrieve() + XCTAssertNotNil(data) + guard let validData = data else { + throw DataError.dataNotFound + } + print(validData) + XCTAssertEqual(validData.count, 1) + XCTAssertEqual(validData[0].synonyms, ["blazer", "coat", "jacket"]) + XCTAssertEqual(validData[0].id, "coat-synonyms") + } catch HTTPError.serverError(let code, let desc) { + print(desc) + print("The response status code is \(code)") + XCTAssertTrue(false) + } catch (let error) { + print(error.localizedDescription) + XCTAssertTrue(false) + } + } +} diff --git a/Tests/TypesenseTests/SynonymTests.swift b/Tests/TypesenseTests/SynonymTests.swift deleted file mode 100644 index f51dc0e..0000000 --- a/Tests/TypesenseTests/SynonymTests.swift +++ /dev/null @@ -1,149 +0,0 @@ -import XCTest -@testable import Typesense - -final class SynonymTests: XCTestCase { - func testSynonymUpsertMultiWay() async { - let newConfig = Configuration(nodes: [Node(host: "localhost", port: "8108", nodeProtocol: "http")], apiKey: "xyz", logger: Logger(debugMode: true)) - let myClient = Client(config: newConfig) - - do { - - let synonymSchema = SearchSynonymSchema(synonyms: ["blazer", "coat", "jacket"]) - let (_, _) = try await myClient.collections().create(schema: CollectionSchema(fields: [Field(name: "name", type: "string")],name: "products")) //Creating test collection - Products - - let (data, _) = try await myClient.collection(name: "products").synonyms().upsert(id: "coat-synonyms", synonymSchema) - let (_,_) = try await myClient.collection(name: "products").delete() //Deleting test collection - XCTAssertNotNil(data) - guard let validData = data else { - throw DataError.dataNotFound - } - print(validData) - XCTAssertNil(validData.root) - XCTAssertEqual(validData.synonyms, ["blazer", "coat", "jacket"]) - XCTAssertEqual(validData.id, "coat-synonyms") - } catch HTTPError.serverError(let code, let desc) { - print(desc) - print("The response status code is \(code)") - XCTAssertTrue(false) - } catch (let error) { - print(error.localizedDescription) - XCTAssertTrue(false) //To prevent this, check availability of Typesense Server and retry - } - } - - func testSynonymUpsertOneWay() async { - let newConfig = Configuration(nodes: [Node(host: "localhost", port: "8108", nodeProtocol: "http")], apiKey: "xyz", logger: Logger(debugMode: true)) - let myClient = Client(config: newConfig) - - do { - - let synonymSchema = SearchSynonymSchema( synonyms: ["iphone", "android"],root: "smart phone",) - let (_, _) = try await myClient.collections().create(schema: CollectionSchema(fields: [Field(name: "name", type: "string")], name: "products", )) //Creating test collection - Products - - let (data, _) = try await myClient.collection(name: "products").synonyms().upsert(id: "smart-phone-synonyms", synonymSchema) - let (_,_) = try await myClient.collection(name: "products").delete() //Deleting test collection - XCTAssertNotNil(data) - guard let validData = data else { - throw DataError.dataNotFound - } - print(validData) - XCTAssertEqual(validData.root, "smart phone") - XCTAssertEqual(validData.synonyms, ["iphone", "android"]) - XCTAssertEqual(validData.id, "smart-phone-synonyms") - } catch HTTPError.serverError(let code, let desc) { - print(desc) - print("The response status code is \(code)") - XCTAssertTrue(false) - } catch (let error) { - print(error.localizedDescription) - XCTAssertTrue(false) //To prevent this, check availability of Typesense Server and retry - } - } - - func testSynonymRetrieveOne() async { - let newConfig = Configuration(nodes: [Node(host: "localhost", port: "8108", nodeProtocol: "http")], apiKey: "xyz", logger: Logger(debugMode: true)) - let myClient = Client(config: newConfig) - - do { - - let synonymSchema = SearchSynonymSchema(synonyms: ["blazer", "coat", "jacket"]) - let (_, _) = try await myClient.collections().create(schema: CollectionSchema(fields: [Field(name: "name", type: "string")], name: "products",)) //Creating test collection - Products - let (_, _) = try await myClient.collection(name: "products").synonyms().upsert(id: "coat-synonyms", synonymSchema) //Feed in the synonym - let (data,_) = try await myClient.collection(name: "products").synonyms().retrieve(id: "coat-synonyms") - let (_,_) = try await myClient.collection(name: "products").delete() //Deleting test collection - XCTAssertNotNil(data) - guard let validData = data else { - throw DataError.dataNotFound - } - print(validData) - XCTAssertEqual(validData.root, "") - XCTAssertEqual(validData.synonyms, ["blazer", "coat", "jacket"]) - XCTAssertEqual(validData.id, "coat-synonyms") - } catch HTTPError.serverError(let code, let desc) { - print(desc) - print("The response status code is \(code)") - XCTAssertTrue(false) - } catch (let error) { - print(error.localizedDescription) - XCTAssertTrue(false) //To prevent this, check availability of Typesense Server and retry - } - } - - func testSynonymRetrieveAll() async { - let newConfig = Configuration(nodes: [Node(host: "localhost", port: "8108", nodeProtocol: "http")], apiKey: "xyz", logger: Logger(debugMode: true)) - let myClient = Client(config: newConfig) - - do { - - let synonymSchema = SearchSynonymSchema(synonyms: ["blazer", "coat", "jacket"]) - let (_, _) = try await myClient.collections().create(schema: CollectionSchema(fields: [Field(name: "name", type: "string")], name: "products", )) //Creating test collection - Products - let (_, _) = try await myClient.collection(name: "products").synonyms().upsert(id: "coat-synonyms", synonymSchema) //Feed in the synonym - let (data,_) = try await myClient.collection(name: "products").synonyms().retrieve() - let (_,_) = try await myClient.collection(name: "products").delete() //Deleting test collection - XCTAssertNotNil(data) - guard let validData = data else { - throw DataError.dataNotFound - } - print(validData) - XCTAssertEqual(validData.synonyms.count, 1) - XCTAssertEqual(validData.synonyms[0].id, "coat-synonyms") - XCTAssertEqual(validData.synonyms[0].synonyms, ["blazer", "coat", "jacket"]) - } catch HTTPError.serverError(let code, let desc) { - print(desc) - print("The response status code is \(code)") - XCTAssertTrue(false) - } catch (let error) { - print(error.localizedDescription) - XCTAssertTrue(false) //To prevent this, check availability of Typesense Server and retry - } - } - - func testSynonymDelete() async { - let newConfig = Configuration(nodes: [Node(host: "localhost", port: "8108", nodeProtocol: "http")], apiKey: "xyz", logger: Logger(debugMode: true)) - let myClient = Client(config: newConfig) - - do { - - let synonymSchema = SearchSynonymSchema(synonyms: ["blazer", "coat", "jacket"]) - let (_, _) = try await myClient.collections().create(schema: CollectionSchema( - fields: [Field(name: "name", type: "string")], - name: "products", - )) //Creating test collection - Products - let (_, _) = try await myClient.collection(name: "products").synonyms().upsert(id: "coat-synonyms", synonymSchema) //Feed in the synonym - let (data,_) = try await myClient.collection(name: "products").synonyms().delete(id: "coat-synonyms") - let (_,_) = try await myClient.collection(name: "products").delete() //Deleting test collection - XCTAssertNotNil(data) - guard let validData = data else { - throw DataError.dataNotFound - } - print(String(data: validData, encoding: .utf8)!) - } catch HTTPError.serverError(let code, let desc) { - print(desc) - print("The response status code is \(code)") - XCTAssertTrue(false) - } catch (let error) { - print(error.localizedDescription) - XCTAssertTrue(false) //To prevent this, check availability of Typesense Server and retry - } - } -} diff --git a/Tests/TypesenseTests/TestUtils.swift b/Tests/TypesenseTests/TestUtils.swift index da18ff7..a71efb9 100644 --- a/Tests/TypesenseTests/TestUtils.swift +++ b/Tests/TypesenseTests/TestUtils.swift @@ -74,14 +74,23 @@ func tearDownCurationSets() async throws { } } +func tearDownSynonymSets() async throws { + let (data, _) = try await utilClient.synonymSets().retrieve() + guard let validData = data else { + throw DataError.dataNotFound + } + for item in validData { + let _ = try await utilClient.synonymSet(item.name).delete() + } +} + func createCollection() async throws { - let schema = CollectionSchema( fields: [ + let schema = CollectionSchema( name: "companies", fields: [ Field(name: "company_name", type: "string"), Field(name: "num_employees", type: "int32", facet: true), Field(name: "country", type: "string", facet: true), - Field(name: "metadata", type: "object", facet: true, _optional: true) - ], - name: "companies", + Field(name: "metadata", type: "object", _optional: true, facet: true) + ], defaultSortingField: "num_employees", enableNestedFields: true) let _ = try await utilClient.collections().create(schema: schema) @@ -94,13 +103,12 @@ func createDocument() async throws { func createCurationSet() async throws { let schema = CurationSetCreateSchema(items: [ CurationItemCreateSchema( - rule: CurationRule( match: .exact, query: "apple"), - excludes: [CurationExclude(id: "287")], - id: "customize-apple", + rule: CurationRule( query: "apple", match: .exact), includes: [ CurationInclude(id: "422", position: 1), CurationInclude(id: "54", position: 2), - ] + ], excludes: [CurationExclude(id: "287")], + id: "customize-apple" ) ]) let _ = try await client.curationSets().upsert("curate_products", schema) @@ -135,7 +143,7 @@ func createStopwordSet() async throws { } func createAPIKey() async throws -> ApiKey { - let (data, _) = try await utilClient.keys().create( ApiKeySchema(actions: ["*"], collections: ["*"], description: "Test key with all privileges")) + let (data, _) = try await utilClient.keys().create( ApiKeySchema(description: "Test key with all privileges", actions: ["*"], collections: ["*"])) return data! } @@ -144,16 +152,24 @@ func createAlias() async throws { } func createConversationCollection() async throws { - let schema = CollectionSchema(fields: [ + let schema = CollectionSchema(name: "conversation_store", fields: [ Field(name: "conversation_id", type: "string"), Field(name: "model_id", type: "string"), Field(name: "timestamp", type: "int32"), Field(name: "role", type: "string", index: false), Field(name: "message", type: "string", index: false) - ], name: "conversation_store") + ]) let _ = try await utilClient.collections().create(schema: schema) } +func createSynonymSet() async throws { + let synonymSchema = SynonymSetCreateSchema(items: [ + SynonymItemSchema(synonyms: ["blazer", "coat", "jacket"], id:"coat-synonyms", root: "outerwear") + ] + ) + let _ = try await utilClient.synonymSets().upsert("clothing-synonyms", synonymSchema) +} + struct Product: Codable, Equatable { var name: String? var price: Int From 9d6f1c6e421557e4f980b37cd1fd2d8128ebde28 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Thu, 11 Dec 2025 17:02:01 +0700 Subject: [PATCH 10/21] fix incorrect parameter order --- Tests/TypesenseTests/AnalyticsTests.swift | 45 +++++++++---------- Tests/TypesenseTests/ApiKeyTests.swift | 2 +- Tests/TypesenseTests/CollectionTests.swift | 3 +- .../ConversationModelTests.swift | 6 +-- Tests/TypesenseTests/CurationSetTests.swift | 7 ++- Tests/TypesenseTests/CurationSetsTests.swift | 7 ++- Tests/TypesenseTests/DocumentTests.swift | 14 +++--- Tests/TypesenseTests/MultiSearchTests.swift | 22 ++++----- 8 files changed, 50 insertions(+), 56 deletions(-) diff --git a/Tests/TypesenseTests/AnalyticsTests.swift b/Tests/TypesenseTests/AnalyticsTests.swift index aeb4f53..fee5406 100644 --- a/Tests/TypesenseTests/AnalyticsTests.swift +++ b/Tests/TypesenseTests/AnalyticsTests.swift @@ -3,25 +3,25 @@ import XCTest final class AnalyticsTests: XCTestCase { override func setUp() async throws { - let _ = try await utilClient.collections().create(schema: CollectionSchema(fields: [ + let _ = try await utilClient.collections().create(schema: CollectionSchema(name: "product_queries", fields: [ Field(name:"q", type: "string"), Field(name:"count", type: "int32") - ], name: "product_queries")) - let _ = try await utilClient.collections().create(schema: CollectionSchema(fields: [ + ])) + let _ = try await utilClient.collections().create(schema: CollectionSchema(name: "test-products-analytics", fields: [ Field(name:"name", type: "string"), Field(name:"in_stock", type: "int32") - ], name: "test-products-analytics")) + ])) let _ = try await utilClient.analytics().rules().create(AnalyticsRuleCreate( - collection: "test-products-analytics", - eventType: "search", name: "homepage_popular_queries", type: .popularQueries, + collection: "test-products-analytics", + eventType: "search", + ruleTag: "homepage", params: AnalyticsRuleCreateParams( - captureSearchRequests: true, destinationCollection: "product_queries", limit: 100, + captureSearchRequests: true, ), - ruleTag: "homepage", )) } @@ -33,15 +33,15 @@ final class AnalyticsTests: XCTestCase { func testAnalyticsRuleCreate() async { let schema = AnalyticsRuleCreate( - collection: "test-products-analytics", - eventType: "search", name: "test-rule", type: .popularQueries, + collection: "test-products-analytics", + eventType: "search", + ruleTag: "homepage", params: AnalyticsRuleCreateParams( destinationCollection: "product_queries", limit: 100, ), - ruleTag: "homepage", ) do { let (rule, _) = try await utilClient.analytics().rules().create(schema) @@ -61,26 +61,26 @@ final class AnalyticsTests: XCTestCase { func testAnalyticsRuleCreateMany() async { let schema1 = AnalyticsRuleCreate( - collection: "test-products-analytics", - eventType: "search", name: "test_rule_1", type: .popularQueries, + collection: "test-products-analytics", + eventType: "search", + ruleTag: "homepage", params: AnalyticsRuleCreateParams( destinationCollection: "product_queries", limit: 100, ), - ruleTag: "homepage" ) let schema2 = AnalyticsRuleCreate( - collection: "test-products-analytics", - eventType: "search", name: "test_rule_2", type: .popularQueries, + collection: "test-products-analytics", + eventType: "search", + ruleTag: "homepage", params: AnalyticsRuleCreateParams( destinationCollection: "product_queries", limit: 100, ), - ruleTag: "homepage", ) do { let (rules, _) = try await utilClient.analytics().rules().createMany([schema1, schema2]) @@ -148,12 +148,11 @@ final class AnalyticsTests: XCTestCase { func testAnalyticsEventsCreate() async { do { let (res, _) = try await client.analytics().events().create( AnalyticsEvent( + name: "homepage_popular_queries", + eventType: "popular_queries", data: AnalyticsEventData( - q: "nike shoes", - userId: "111112", + userId: "111112", q: "nike shoes", ), - eventType: "popular_queries", - name: "homepage_popular_queries", )) guard let validRes = res else { throw DataError.dataNotFound @@ -165,11 +164,11 @@ final class AnalyticsTests: XCTestCase { XCTAssertTrue(false) } } - + func testAnalyticsEventsRetrieve() async { do { let (res, _) = try await client.analytics().events().retrieve( - AnalyticsEventsRetrieveParams(n:10, name: "homepage_popular_queries", userId: "123")) + AnalyticsEventsRetrieveParams(userId: "123", name: "homepage_popular_queries", n:10)) guard let validRes = res else { throw DataError.dataNotFound } diff --git a/Tests/TypesenseTests/ApiKeyTests.swift b/Tests/TypesenseTests/ApiKeyTests.swift index 1f0e375..95560b5 100644 --- a/Tests/TypesenseTests/ApiKeyTests.swift +++ b/Tests/TypesenseTests/ApiKeyTests.swift @@ -8,7 +8,7 @@ final class ApiKeyTests: XCTestCase { func testKeyCreate() async { do { - let adminKey = ApiKeySchema(actions: ["*"], collections: ["*"], description: "Test key with all privileges", ) + let adminKey = ApiKeySchema(description: "Test key with all privileges", actions: ["*"], collections: ["*"], ) let (data, _) = try await client.keys().create(adminKey) XCTAssertNotNil(data) guard let validData = data else { diff --git a/Tests/TypesenseTests/CollectionTests.swift b/Tests/TypesenseTests/CollectionTests.swift index f1791f6..b7d62ac 100644 --- a/Tests/TypesenseTests/CollectionTests.swift +++ b/Tests/TypesenseTests/CollectionTests.swift @@ -8,12 +8,11 @@ final class CollectionTests: XCTestCase { func testCollectionCreate() async { let schema = CollectionSchema( - fields: [ + name: "companies", fields: [ Field(name: "company_name", type: "string"), Field(name: "num_employees", type: "int32"), Field(name: "country", type: "string", facet: true) ], - name: "companies", defaultSortingField: "num_employees") do { let (collResp, _) = try await client.collections().create(schema: schema) diff --git a/Tests/TypesenseTests/ConversationModelTests.swift b/Tests/TypesenseTests/ConversationModelTests.swift index a35bbde..986f5b7 100644 --- a/Tests/TypesenseTests/ConversationModelTests.swift +++ b/Tests/TypesenseTests/ConversationModelTests.swift @@ -4,11 +4,9 @@ import XCTest final class ConversationModelTests: XCTestCase { func testConversationModelsCreate() async { let schema = ConversationModelCreateSchema( - historyCollection: "conversation_store", + modelName: "test/gpt-3.5-turbo", historyCollection: "conversation_store", maxBytes: 16384, - modelName: "test/gpt-3.5-turbo", - apiKey: "sk", - id: "conv-model-1", + id: "conv-model-1", apiKey: "sk", systemPrompt: "You are an assistant for question-answering.", ttl: 123, ) diff --git a/Tests/TypesenseTests/CurationSetTests.swift b/Tests/TypesenseTests/CurationSetTests.swift index 90d72d8..3c26168 100644 --- a/Tests/TypesenseTests/CurationSetTests.swift +++ b/Tests/TypesenseTests/CurationSetTests.swift @@ -79,13 +79,12 @@ final class CurationSetTests: XCTestCase { func testCurationSetItemsUpsert() async { do { let (result, _) = try await client.curationSet("curate_products").items().upsert("customize-apple-2", CurationItemCreateSchema( - rule: CurationRule( match: .exact, query: "apple"), - excludes: [CurationExclude(id: "287")], - id: "customize-apple", + rule: CurationRule( query: "apple", match: .exact), includes: [ CurationInclude(id: "422", position: 1), CurationInclude(id: "54", position: 2), - ] + ], excludes: [CurationExclude(id: "287")], + id: "customize-apple" )) guard let validData = result else { throw DataError.dataNotFound diff --git a/Tests/TypesenseTests/CurationSetsTests.swift b/Tests/TypesenseTests/CurationSetsTests.swift index 226a017..766bd10 100644 --- a/Tests/TypesenseTests/CurationSetsTests.swift +++ b/Tests/TypesenseTests/CurationSetsTests.swift @@ -9,13 +9,12 @@ final class CurationSetsTests: XCTestCase { func testCurationSetsUpsert() async { let schema = CurationSetCreateSchema(items: [ CurationItemCreateSchema( - rule: CurationRule( match: .exact, query: "apple"), - excludes: [CurationExclude(id: "287")], - id: "customize-apple", + rule: CurationRule( query: "apple", match: .exact), includes: [ CurationInclude(id: "422", position: 1), CurationInclude(id: "54", position: 2), - ] + ], excludes: [CurationExclude(id: "287")], + id: "customize-apple" ) ]) do { diff --git a/Tests/TypesenseTests/DocumentTests.swift b/Tests/TypesenseTests/DocumentTests.swift index c85de91..024b0b3 100644 --- a/Tests/TypesenseTests/DocumentTests.swift +++ b/Tests/TypesenseTests/DocumentTests.swift @@ -172,7 +172,7 @@ final class DocumentTests: XCTestCase { } func testDocumentSearch() async { - let searchParams = SearchParameters(groupBy: "country", groupLimit: 1, page: 0, q: "*", queryBy: "company_name") + let searchParams = SearchParameters(q: "*", queryBy: "company_name", page: 0, groupBy: "country", groupLimit: 1) do { try await createDocument() @@ -197,7 +197,7 @@ final class DocumentTests: XCTestCase { } func testDocumentSearchReturnRawData() async { - let searchParams = SearchParameters(filterBy: "num_employees:>100", q: "stark", queryBy: "company_name", sortBy: "num_employees:desc") + let searchParams = SearchParameters(q: "stark", queryBy: "company_name", filterBy: "num_employees:>100", sortBy: "num_employees:desc") do { try await createDocument() @@ -219,16 +219,16 @@ final class DocumentTests: XCTestCase { } func testDocumentSearchWithPreset() async { - let productSchema = CollectionSchema(fields: [ + let productSchema = CollectionSchema(name: "products", fields: [ Field(name: "name", type: "string"), Field(name: "price", type: "int32"), Field(name: "brand", type: "string"), Field(name: "desc", type: "string"), - ], name: "products") + ]) let preset = PresetUpsertSchema( value: .typeSearchParameters( - SearchParameters(filterBy: "price:=[50..120]", q: "Jor", queryBy: "name") + SearchParameters(q: "Jor", queryBy: "name", filterBy: "price:=[50..120]") ) ) @@ -266,7 +266,7 @@ final class DocumentTests: XCTestCase { } func testDocumentGroupSearch() async { - let searchParams = SearchParameters(groupBy: "num_employees,country,metadata", q: "*", queryBy: "company_name") + let searchParams = SearchParameters(q: "*", queryBy: "company_name", groupBy: "num_employees,country,metadata") do { try await createDocument() @@ -341,7 +341,7 @@ final class DocumentTests: XCTestCase { let jsonL = Data(jsonLString.utf8) let (data, _) = try await client.collection(name: "companies").documents().importBatch(jsonL, options: ImportDocumentsParameters( - action: .upsert, batchSize: 10, dirtyValues: .drop, remoteEmbeddingBatchSize: 10, returnDoc: true, returnId: false + batchSize: 10, returnId: false, remoteEmbeddingBatchSize: 10, returnDoc: true, action: .upsert, dirtyValues: .drop )) XCTAssertNotNil(data) guard let validResp = data else { diff --git a/Tests/TypesenseTests/MultiSearchTests.swift b/Tests/TypesenseTests/MultiSearchTests.swift index 1dc2d58..b5ab7b6 100644 --- a/Tests/TypesenseTests/MultiSearchTests.swift +++ b/Tests/TypesenseTests/MultiSearchTests.swift @@ -3,15 +3,15 @@ import XCTest final class MultiSearchTests: XCTestCase { override func setUp() async throws { - let productSchema = CollectionSchema(fields: [ + let productSchema = CollectionSchema(name: "products", fields: [ Field(name: "name", type: "string"), Field(name: "price", type: "int32"), Field(name: "brand", type: "string"), Field(name: "desc", type: "string"), - ], name: "products") - let brandSchema = CollectionSchema(fields: [ + ]) + let brandSchema = CollectionSchema(name: "brands", fields: [ Field(name: "name", type: "string"), - ], name: "brands") + ]) let _ = try await client.collections().create(schema: productSchema) @@ -52,7 +52,7 @@ final class MultiSearchTests: XCTestCase { func testMultiSearch() async { let searchRequests = [ - MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "Jor", collection: "products"), + MultiSearchCollectionParameters(q: "Jor", filterBy: "price:=[50..120]", collection: "products"), MultiSearchCollectionParameters(q: "Nike", collection: "brands"), ] @@ -108,7 +108,7 @@ final class MultiSearchTests: XCTestCase { func testMultiSearchReturnRawData() async { let searchRequests = [ - MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "shoe", collection: "products"), + MultiSearchCollectionParameters(q: "shoe", filterBy: "price:=[50..120]", collection: "products"), MultiSearchCollectionParameters(q: "Nike", collection: "brands"), ] @@ -150,7 +150,7 @@ final class MultiSearchTests: XCTestCase { let preset = PresetUpsertSchema( value: .typeMultiSearchSearchesParameter(MultiSearchSearchesParameter( searches:[ - MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "shoe", collection: "products"), + MultiSearchCollectionParameters(q: "shoe", filterBy: "price:=[50..120]", collection: "products"), MultiSearchCollectionParameters(q: "Nike", collection: "brands"), ] )) @@ -160,7 +160,7 @@ final class MultiSearchTests: XCTestCase { let brand1 = Brand(name: "Nike") let product1 = Product(name: "Jordan", price: 70, brand: "Nike", desc: "High quality shoe") - let commonParams = MultiSearchParameters(preset: "test-multi-search", queryBy: "name") + let commonParams = MultiSearchParameters(queryBy: "name", preset: "test-multi-search") do { let _ = try await client.presets().upsert(presetName: "test-multi-search", params: preset) @@ -198,7 +198,7 @@ final class MultiSearchTests: XCTestCase { func testMultiSearchUnionReturnRawData() async { let searchRequests = [ - MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "shoe", collection: "products"), + MultiSearchCollectionParameters(q: "shoe", filterBy: "price:=[50..120]", collection: "products"), MultiSearchCollectionParameters(q: "Nike", collection: "brands"), ] @@ -236,7 +236,7 @@ final class MultiSearchTests: XCTestCase { func testMultiSearchUnion() async { let searchRequests = [ - MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "shoe", collection: "products"), + MultiSearchCollectionParameters(q: "shoe", filterBy: "price:=[50..120]", collection: "products"), MultiSearchCollectionParameters(q: "Nike", collection: "brands"), ] @@ -280,7 +280,7 @@ final class MultiSearchTests: XCTestCase { func testMultiSearchPack() async { let searchRequests = [ - MultiSearchCollectionParameters(filterBy: "price:=[50..120]", q: "Jor", collection: "products"), + MultiSearchCollectionParameters(q: "Jor", filterBy: "price:=[50..120]", collection: "products"), MultiSearchCollectionParameters(q: "Nike", collection: "brands"), ] From 2805a10001a04878440256c18911dd76cd8cdf62 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Thu, 11 Dec 2025 17:04:00 +0700 Subject: [PATCH 11/21] ci: upgrade typesense version --- .github/workflows/tests.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index ef65ee7..5a08f5e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -33,10 +33,12 @@ jobs: mkdir $(pwd)/typesense-data docker run -p 8108:8108 \ -d \ - -v$(pwd)/typesense-data:/data typesense/typesense:28.0 \ + -v$(pwd)/typesense-data:/data typesense/typesense:30.0.rca34 \ --data-dir /data \ --api-key=xyz \ - --enable-cors + --enable-cors \ + --enable-search-analytics=true \ + --analytics-dir=/analytics-data shell: bash - name: Set up Xcode From dabbdf28011e13eb247991bab581c38e8912fb44 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Thu, 11 Dec 2025 21:52:34 +0700 Subject: [PATCH 12/21] update README: fix code snippet & instructions on using the new codegen Tasks --- README.md | 54 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 35 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index e3a0d22..952c199 100644 --- a/README.md +++ b/README.md @@ -91,12 +91,12 @@ This returns a `SearchResult` object as the data, which can be further parsed as ```swift let jsonL = Data("{}".utf8) let (data, response) = try await client.collection(name: "companies").documents().importBatch(jsonL, options: ImportDocumentsParameters( - action: .upsert, - batchSize: 10, - dirtyValues: .drop, - remoteEmbeddingBatchSize: 10, - returnDoc: true, - returnId: false + batchSize: 10, + returnId: false, + remoteEmbeddingBatchSize: 10, + returnDoc: true, + action: .upsert, + dirtyValues: .drop )) ``` @@ -105,7 +105,7 @@ let (data, response) = try await client.collection(name: "companies").documents( ```swift let (data, response) = try await client.collection(name: "companies").documents().update( document: ["company_size": "large"], - options: UpdateDocumentsByFilterParameters(filterBy: "num_employees:>1000") + options: UpdateDocumentsParameters(filterBy: "num_employees:>1000") ) ``` @@ -151,7 +151,7 @@ let (data, response) = try await client.aliases().delete(name: "companies") ### Create an API key ```swift -let adminKey = ApiKeySchema(_description: "Test key with all privileges", actions: ["*"], collections: ["*"]) +let adminKey = ApiKeySchema(description: "Test key with all privileges", actions: ["*"], collections: ["*"]) let (data, response) = try await client.keys().create(adminKey) ``` @@ -177,13 +177,13 @@ let (data, response) = try await client.keys().delete(id: 1) ```swift let schema = ConversationModelCreateSchema( - _id: "conv-model-1", modelName: "openai/gpt-3.5-turbo", - apiKey: "OPENAI_API_KEY", historyCollection: "conversation_store", + maxBytes: 16384, + id: "conv-model-1", + apiKey: "OPENAI_API_KEY", systemPrompt: "You are an assistant for question-answering...", ttl: 10000, - maxBytes: 16384 ) let (data, response) = try await client.conversations().models().create(params: schema) ``` @@ -256,8 +256,8 @@ let (data, response) = try await client.collection(name: "books").override("test ```swift let schema = PresetUpsertSchema( - value: PresetValue.singleCollectionSearch(SearchParameters(q: "apple")) - // or: value: PresetValue.multiSearch(MultiSearchSearchesParameter(searches: [MultiSearchCollectionParameters(q: "apple")])) + value: PresetUpsertSchemaValue.typeSearchParameters(SearchParameters(q: "apple")) + // or: value: PresetUpsertSchemaValue.typeMultiSearchSearchesParameter(MultiSearchSearchesParameter(searches: [MultiSearchCollectionParameters(q: "apple")])) ) let (data, response) = try await client.presets().upsert(presetName: "listing_view", params: schema) ``` @@ -274,9 +274,9 @@ let (data, response) = try await client.presets().retrieve() let (data, response) = try await client.preset("listing_view").retrieve() switch data?.value { - case .singleCollectionSearch(let value): + case .typeSearchParameters(let value): print(value) - case .multiSearch(let value): + case .typeMultiSearchSearchesParameter(let value): print(value) } ``` @@ -390,13 +390,29 @@ let (data, response) = try await client.operations().snapshot(path: "/tmp/typese ## Contributing -Issues and pull requests are welcome on GitHub at [Typesense Swift](https://github.com/typesense/typesense-swift). Do note that the Models used in the Swift client are generated by [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator) and are automated to be modified in order to prevent major errors. So please do use the shell script that is provided in the repo to generate the models: +Issues and pull requests are welcome on GitHub at [Typesense Swift](https://github.com/typesense/typesense-swift). Do note that the Models used in the Swift client are generated by [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator). + +When updating or adding new parameters and endpoints, make changes directly in the [Typesense API spec repository](https://github.com/typesense/typesense-api-spec). + +Once your changes are merged, you can update this project as follows: -```shell -sh get-models.sh +```bash +swift run Tasks fetch +swift run Tasks preprocess +swift run Tasks code-gen ``` -The generated Models (inside the Models directory) are to be used inside the Models directory of the source code as well. Models need to be generated as and when the [Typesense-Api-Spec](https://github.com/typesense/typesense-api-spec) is updated. +This will: + +- Download the latest API spec. +- Write it to our local [`openapi.yml`](./openapi.yml). +- Preprocess it into [`preprocessed_openapi.yml`](./preprocessed_openapi.yml). +- Generate and replace the `Sources/Typesense/Models` folder. + +The preprocessing step does two things: + +- Flatten the URL params defined as objects into individual URL parameters (in [`PreprocessOpenAPI.swift`](Tasks/PreprocessOpenAPI.swift)) +- Inject OpenAPI vendor attributes `x-swift-*` (e.g., generic parameters, schema builders) into the spec before code generation (in [`AddVendorAttributes.swift`](Tasks/AddVendorAttributes.swift)) ## TODO: Features From 872c181550d2e049304b8518c25c9451b4e83b44 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Thu, 11 Dec 2025 22:08:44 +0700 Subject: [PATCH 13/21] README: v30 curation sets APIs snippets --- README.md | 74 ++++++++++++++------- Tests/TypesenseTests/CurationSetTests.swift | 13 ++-- 2 files changed, 56 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 952c199..1826de2 100644 --- a/README.md +++ b/README.md @@ -214,42 +214,68 @@ let (data, response) = try await client.conversations().model(modelId: "conv-mod let (data, response) = try await client.conversations().model(modelId: "conv-model-1").delete() ``` -### Create or update an override - -```swift -let schema = SearchOverrideSchema( - rule: SearchOverrideRule(tags: ["test"], query: "apple", match: SearchOverrideRule.Match.exact, filterBy: "employees:=50"), - includes: [SearchOverrideInclude(_id: "include-id", position: 1)], - excludes: [SearchOverrideExclude(_id: "exclude-id")], - filterBy: "test:=true", - removeMatchedTokens: false, - metadata: MetadataType(message: "test-json"), - sortBy: "num_employees:desc", - replaceQuery: "test", - filterCuratedHits: false, - effectiveFromTs: 123, - effectiveToTs: 456, - stopProcessing: false -) -let (data, response) = try await client.collection(name: "books").overrides().upsert(overrideId: "test-id", params: schema) +### Create or update a curation set + +```swift +let schema = CurationSetCreateSchema(items: [ + CurationItemCreateSchema( + rule: CurationRule( query: "apple", match: .exact), + includes: [ + CurationInclude(id: "422", position: 1), + CurationInclude(id: "54", position: 2), + ], excludes: [CurationExclude(id: "287")], + id: "customize-apple" + ) + ]) +let (data, response) = try await client.curationSets().upsert("curate_products", schema) +``` + +### Retrieve all curation sets + +```swift +let (data, response) = try await client.curationSets().retrieve() +``` + +### Retrieve a curation set + +```swift +let (data, response) = try await client.curationSet("curate_products").retrieve() +``` + +### Delete a curation set + +```swift +let (data, response) = try await client.curationSet("curate_products").delete() ``` -### Retrieve all overrides +### Retrieve all curation set items ```swift -let (data, response) = try await client.collection(name: "books").overrides().retrieve(metadataType: Never.self) +let (data, response) = try await client.curationSet("curate_products").items().retrieve() +``` + +### Upsert a curation set item + +```swift +let (data, response) = try await client.curationSet("curate_products").items().upsert("customize-apple-2", CurationItemCreateSchema( + rule: CurationRule( query: "apple", match: .exact), + includes: [ + CurationInclude(id: "422", position: 1), + CurationInclude(id: "54", position: 2), + ], excludes: [CurationExclude(id: "287")], +)) ``` -### Retrieve an override +### Retrieve a curation set item ```swift -let (data, response) = try await client.collection(name: "books").override("test-id").retrieve(metadataType: MetadataType.self) +let (data, response) = try await client.curationSet("curate_products").item("customize-apple").retrieve() ``` -### Delete an override +### Delete a curation set item ```swift -let (data, response) = try await client.collection(name: "books").override("test-id").delete() +let (data, response) = try await client.curationSet("curate_products").item("customize-apple").delete() ``` ### Create or update a preset diff --git a/Tests/TypesenseTests/CurationSetTests.swift b/Tests/TypesenseTests/CurationSetTests.swift index 3c26168..4bc9718 100644 --- a/Tests/TypesenseTests/CurationSetTests.swift +++ b/Tests/TypesenseTests/CurationSetTests.swift @@ -45,7 +45,7 @@ final class CurationSetTests: XCTestCase { print(error) XCTAssertTrue(false) } - + do{ let _ = try await client.curationSet("curate_products").retrieve() } catch HTTPError.clientError(let code, _){ @@ -75,7 +75,7 @@ final class CurationSetTests: XCTestCase { XCTAssertTrue(false) } } - + func testCurationSetItemsUpsert() async { do { let (result, _) = try await client.curationSet("curate_products").items().upsert("customize-apple-2", CurationItemCreateSchema( @@ -84,7 +84,6 @@ final class CurationSetTests: XCTestCase { CurationInclude(id: "422", position: 1), CurationInclude(id: "54", position: 2), ], excludes: [CurationExclude(id: "287")], - id: "customize-apple" )) guard let validData = result else { throw DataError.dataNotFound @@ -100,7 +99,7 @@ final class CurationSetTests: XCTestCase { XCTAssertTrue(false) } } - + func testCurationSetItemRetrieve() async { do { let (result, _) = try await client.curationSet("curate_products").item("customize-apple").retrieve() @@ -118,8 +117,8 @@ final class CurationSetTests: XCTestCase { XCTAssertTrue(false) } } - - func testCurationSetItemDelere() async { + + func testCurationSetItemDelete() async { do { let (result, _) = try await client.curationSet("curate_products").item("customize-apple").delete() guard let validData = result else { @@ -127,7 +126,7 @@ final class CurationSetTests: XCTestCase { } print(validData) XCTAssertEqual("customize-apple", validData.id) - + let (curationSet, _) = try await client.curationSet("curate_products").retrieve() guard let validCurationSet = curationSet else { throw DataError.dataNotFound From 9231863b485c48e94fe01341256013a2a3902209 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Thu, 11 Dec 2025 22:16:05 +0700 Subject: [PATCH 14/21] README: v30 synonym APIs snippets --- README.md | 37 ++++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 1826de2..3a92868 100644 --- a/README.md +++ b/README.md @@ -344,26 +344,53 @@ let (data, response) = try await client.stopword("stopword_set1").delete() ### Create or update a synonym ```swift -let schema = SearchSynonymSchema(synonyms: ["blazer", "coat", "jacket"]) -let (data, response) = try await client.collection(name: "products").synonyms().upsert(id: "coat-synonyms", schema) +let schema = SynonymSetCreateSchema(items: [ + SynonymItemSchema(synonyms: ["blazer", "coat", "jacket"], id:"coat-synonyms", root: "outerwear") +]) +let (data, response) = try await utilClient.synonymSets().upsert("clothing-synonyms", schema) ``` ### Retrieve all synonyms ```swift -let (data, response) = try await client.collection(name: "products").synonyms().retrieve() +let (data, response) = try await client.synonymSets().retrieve() ``` ### Retrieve a synonym ```swift -let (data, response) = try await client.collection(name: "products").synonyms().retrieve(id: "coat-synonyms") +let (data, response) = try await client.synonymSet("clothing-synonyms").retrieve() ``` ### Delete a synonym ```swift -let (data, response) = try await myClient.collection(name: "products").synonyms().delete(id: "coat-synonyms") +let (data, response) = try await client.synonymSet("clothing-synonyms").delete() +``` + +### Upsert a synonym item + +```swift +let schema = SynonymItemUpsertSchema(synonyms: ["blazer", "coat", "jacket"], root: "outerwear") +let (data, response) = try await client.synonymSet("clothing-synonyms").items().upsert("coat-synonyms", schema) +``` + +### Retrieve all synonym items + +```swift +let (data, response) = try await client.synonymSet("clothing-synonyms").items().retrieve() +``` + +### Retrieve a synonym item + +```swift +let (data, response) = try await client.synonymSet("clothing-synonyms").item("coat-synonyms").retrieve() +``` + +### Delete a synonym item + +```swift +let (data, response) = try await client.synonymSet("clothing-synonyms").item("coat-synonyms").delete() ``` ### Retrieve debug information From 2cb1db890f0c72bdd0b08c351715d8523f3d7079 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Thu, 11 Dec 2025 22:16:12 +0700 Subject: [PATCH 15/21] use `client` --- Tests/TypesenseTests/AnalyticsTests.swift | 10 +++---- Tests/TypesenseTests/SynonymSetsTests.swift | 30 ++++++++++----------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Tests/TypesenseTests/AnalyticsTests.swift b/Tests/TypesenseTests/AnalyticsTests.swift index fee5406..b237634 100644 --- a/Tests/TypesenseTests/AnalyticsTests.swift +++ b/Tests/TypesenseTests/AnalyticsTests.swift @@ -3,15 +3,15 @@ import XCTest final class AnalyticsTests: XCTestCase { override func setUp() async throws { - let _ = try await utilClient.collections().create(schema: CollectionSchema(name: "product_queries", fields: [ + let _ = try await client.collections().create(schema: CollectionSchema(name: "product_queries", fields: [ Field(name:"q", type: "string"), Field(name:"count", type: "int32") ])) - let _ = try await utilClient.collections().create(schema: CollectionSchema(name: "test-products-analytics", fields: [ + let _ = try await client.collections().create(schema: CollectionSchema(name: "test-products-analytics", fields: [ Field(name:"name", type: "string"), Field(name:"in_stock", type: "int32") ])) - let _ = try await utilClient.analytics().rules().create(AnalyticsRuleCreate( + let _ = try await client.analytics().rules().create(AnalyticsRuleCreate( name: "homepage_popular_queries", type: .popularQueries, collection: "test-products-analytics", @@ -44,7 +44,7 @@ final class AnalyticsTests: XCTestCase { ), ) do { - let (rule, _) = try await utilClient.analytics().rules().create(schema) + let (rule, _) = try await client.analytics().rules().create(schema) XCTAssertNotNil(rule) guard let validRule = rule else { throw DataError.dataNotFound @@ -83,7 +83,7 @@ final class AnalyticsTests: XCTestCase { ), ) do { - let (rules, _) = try await utilClient.analytics().rules().createMany([schema1, schema2]) + let (rules, _) = try await client.analytics().rules().createMany([schema1, schema2]) XCTAssertNotNil(rules) guard let validRule = rules else { throw DataError.dataNotFound diff --git a/Tests/TypesenseTests/SynonymSetsTests.swift b/Tests/TypesenseTests/SynonymSetsTests.swift index a0cb544..eac1727 100644 --- a/Tests/TypesenseTests/SynonymSetsTests.swift +++ b/Tests/TypesenseTests/SynonymSetsTests.swift @@ -2,18 +2,18 @@ import XCTest @testable import Typesense final class SynonymSetsTests: XCTestCase { - + override func setUp() async throws { try await createSynonymSet() } - + override func tearDown() async throws { try await tearDownSynonymSets() } func testSynonymRetrieveOne() async { do { - let (data,_) = try await utilClient.synonymSet("clothing-synonyms").retrieve() + let (data,_) = try await client.synonymSet("clothing-synonyms").retrieve() XCTAssertNotNil(data) guard let validData = data else { throw DataError.dataNotFound @@ -34,7 +34,7 @@ final class SynonymSetsTests: XCTestCase { func testSynonymRetrieveAll() async { do { - let (data,_) = try await utilClient.synonymSets().retrieve() + let (data,_) = try await client.synonymSets().retrieve() XCTAssertNotNil(data) guard let validData = data else { throw DataError.dataNotFound @@ -53,10 +53,10 @@ final class SynonymSetsTests: XCTestCase { XCTAssertTrue(false) } } - + func testSynonymSetDelete() async { do { - let (data,_) = try await utilClient.synonymSet("clothing-synonyms").delete() + let (data,_) = try await client.synonymSet("clothing-synonyms").delete() XCTAssertNotNil(data) guard let validData = data else { throw DataError.dataNotFound @@ -71,7 +71,7 @@ final class SynonymSetsTests: XCTestCase { print(error.localizedDescription) XCTAssertTrue(false) } - + do{ let _ = try await client.synonymSet("clothing-synonyms").retrieve() } catch HTTPError.clientError(let code, _){ @@ -83,10 +83,10 @@ final class SynonymSetsTests: XCTestCase { XCTAssertTrue(false) } } - + func testSynonymSetItemRetrieveOne() async { do { - let (data,_) = try await utilClient.synonymSet("clothing-synonyms").item("coat-synonyms").retrieve() + let (data,_) = try await client.synonymSet("clothing-synonyms").item("coat-synonyms").retrieve() XCTAssertNotNil(data) guard let validData = data else { throw DataError.dataNotFound @@ -103,10 +103,10 @@ final class SynonymSetsTests: XCTestCase { XCTAssertTrue(false) } } - + func testSynonymSetItemDelete() async { do { - let (data,_) = try await utilClient.synonymSet("clothing-synonyms").item("coat-synonyms").delete() + let (data,_) = try await client.synonymSet("clothing-synonyms").item("coat-synonyms").delete() XCTAssertNotNil(data) guard let validData = data else { throw DataError.dataNotFound @@ -122,7 +122,7 @@ final class SynonymSetsTests: XCTestCase { XCTAssertTrue(false) } do{ - let _ = try await utilClient.synonymSet("clothing-synonyms").item("coat-synonyms").retrieve() + let _ = try await client.synonymSet("clothing-synonyms").item("coat-synonyms").retrieve() } catch HTTPError.clientError(let code, _){ if code != 404 { XCTAssertTrue(false, "Synonym set item should have been deleted") @@ -132,10 +132,10 @@ final class SynonymSetsTests: XCTestCase { XCTAssertTrue(false) } } - + func testSynonymSetItemUpsert() async { do { - let (data,_) = try await utilClient.synonymSet("clothing-synonyms").items().upsert("coat-synonyms-2", SynonymItemUpsertSchema(synonyms: ["none"])) + let (data,_) = try await client.synonymSet("clothing-synonyms").items().upsert("coat-synonyms-2", SynonymItemUpsertSchema(synonyms: ["none"])) XCTAssertNotNil(data) guard let validData = data else { throw DataError.dataNotFound @@ -155,7 +155,7 @@ final class SynonymSetsTests: XCTestCase { func testSynonymSetItemRetrieveAll() async { do { - let (data,_) = try await utilClient.synonymSet("clothing-synonyms").items().retrieve() + let (data,_) = try await client.synonymSet("clothing-synonyms").items().retrieve() XCTAssertNotNil(data) guard let validData = data else { throw DataError.dataNotFound From 33153fb70d51f773f2226886f8e4a67c4ebc6ad9 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Thu, 11 Dec 2025 22:27:50 +0700 Subject: [PATCH 16/21] ci: fix colima error --- .github/workflows/tests.yml | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 5a08f5e..6519e0c 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -19,14 +19,13 @@ jobs: runs-on: macos-latest steps: - uses: actions/checkout@v4 - - name: Install and start dependencies - run: | - brew install docker - brew install qemu - brew install colima - # https://github.com/abiosoft/colima/issues/424#issuecomment-1335912905 - colima delete - colima start --arch x86_64 + - name: Setup Docker on macOS + id: setup-docker + uses: douglascamata/setup-docker-macos-action@v1.0.1 + with: + lima: v1.2.1 + colima: v0.9.1 + colima-network-address: false - name: Run Typesense run: | From 099d4785dad57786df5a5a73e45ef0ae30d75d76 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Thu, 11 Dec 2025 22:39:47 +0700 Subject: [PATCH 17/21] ci: run on macos-15-intel --- .github/workflows/tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 6519e0c..30f477b 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -16,12 +16,12 @@ concurrency: jobs: test: - runs-on: macos-latest + runs-on: macos-15-intel steps: - uses: actions/checkout@v4 - name: Setup Docker on macOS id: setup-docker - uses: douglascamata/setup-docker-macos-action@v1.0.1 + uses: douglascamata/setup-docker-macos-action@v1.0.2 with: lima: v1.2.1 colima: v0.9.1 From 7b82118cc34a7678d02696e67187a5ef93de34ff Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Sun, 14 Dec 2025 11:02:55 +0700 Subject: [PATCH 18/21] revert `client.collections()` to `client.collections` --- README.md | 2 +- Sources/Typesense/Client.swift | 7 +++---- Tests/TypesenseTests/AnalyticsTests.swift | 4 ++-- Tests/TypesenseTests/CollectionTests.swift | 4 ++-- Tests/TypesenseTests/DocumentTests.swift | 2 +- Tests/TypesenseTests/MultiSearchTests.swift | 4 ++-- Tests/TypesenseTests/TestUtils.swift | 6 +++--- 7 files changed, 14 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 3a92868..d04d448 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ You can create a collection by first defining a collection schema: ```swift let myCoolSchema = CollectionSchema(name: "schools", fields: [Field(name: "school_name", type: "string"), Field(name: "num_students", type: "int32"), Field(name: "country", type: "string", facet: true)], defaultSortingField: "num_students") -let (data, response) = try await client.collections().create(schema: myCoolSchema) +let (data, response) = try await client.collections.create(schema: myCoolSchema) ``` Define the structure of your document as per your collection, and index it by inserting/upserting it to the collection: diff --git a/Sources/Typesense/Client.swift b/Sources/Typesense/Client.swift index 0a6eb77..bbb21ce 100644 --- a/Sources/Typesense/Client.swift +++ b/Sources/Typesense/Client.swift @@ -4,16 +4,15 @@ public struct Client { var configuration: Configuration var apiCall: ApiCall + public var collections: Collections { + return Collections(apiCall: apiCall) + } public init(config: Configuration) { self.configuration = config self.apiCall = ApiCall(config: config) } - public func collections() -> Collections { - return Collections(apiCall: apiCall) - } - public func collection(name: String) -> Collection { return Collection(apiCall: apiCall, collectionName: name) } diff --git a/Tests/TypesenseTests/AnalyticsTests.swift b/Tests/TypesenseTests/AnalyticsTests.swift index b237634..97f9f03 100644 --- a/Tests/TypesenseTests/AnalyticsTests.swift +++ b/Tests/TypesenseTests/AnalyticsTests.swift @@ -3,11 +3,11 @@ import XCTest final class AnalyticsTests: XCTestCase { override func setUp() async throws { - let _ = try await client.collections().create(schema: CollectionSchema(name: "product_queries", fields: [ + let _ = try await client.collections.create(schema: CollectionSchema(name: "product_queries", fields: [ Field(name:"q", type: "string"), Field(name:"count", type: "int32") ])) - let _ = try await client.collections().create(schema: CollectionSchema(name: "test-products-analytics", fields: [ + let _ = try await client.collections.create(schema: CollectionSchema(name: "test-products-analytics", fields: [ Field(name:"name", type: "string"), Field(name:"in_stock", type: "int32") ])) diff --git a/Tests/TypesenseTests/CollectionTests.swift b/Tests/TypesenseTests/CollectionTests.swift index b7d62ac..ca6b2d6 100644 --- a/Tests/TypesenseTests/CollectionTests.swift +++ b/Tests/TypesenseTests/CollectionTests.swift @@ -15,7 +15,7 @@ final class CollectionTests: XCTestCase { ], defaultSortingField: "num_employees") do { - let (collResp, _) = try await client.collections().create(schema: schema) + let (collResp, _) = try await client.collections.create(schema: schema) XCTAssertNotNil(collResp) guard let validData = collResp else { throw DataError.dataNotFound @@ -50,7 +50,7 @@ final class CollectionTests: XCTestCase { func testCollectionRetrieveAll() async { do { try await createCollection() - let (collResp, _) = try await client.collections().retrieveAll() + let (collResp, _) = try await client.collections.retrieveAll() XCTAssertNotNil(collResp) guard let validData = collResp else { throw DataError.dataNotFound diff --git a/Tests/TypesenseTests/DocumentTests.swift b/Tests/TypesenseTests/DocumentTests.swift index 024b0b3..00c9f5b 100644 --- a/Tests/TypesenseTests/DocumentTests.swift +++ b/Tests/TypesenseTests/DocumentTests.swift @@ -238,7 +238,7 @@ final class DocumentTests: XCTestCase { do { let _ = try await client.presets().upsert(presetName: "single-collection-search-preset", params: preset) do { - let _ = try await client.collections().create(schema: productSchema) + let _ = try await client.collections.create(schema: productSchema) } catch (let error) { print(error.localizedDescription) XCTAssertTrue(false) diff --git a/Tests/TypesenseTests/MultiSearchTests.swift b/Tests/TypesenseTests/MultiSearchTests.swift index b5ab7b6..a1951f5 100644 --- a/Tests/TypesenseTests/MultiSearchTests.swift +++ b/Tests/TypesenseTests/MultiSearchTests.swift @@ -14,8 +14,8 @@ final class MultiSearchTests: XCTestCase { ]) - let _ = try await client.collections().create(schema: productSchema) - let _ = try await client.collections().create(schema: brandSchema) + let _ = try await client.collections.create(schema: productSchema) + let _ = try await client.collections.create(schema: brandSchema) } override func tearDown() async throws { diff --git a/Tests/TypesenseTests/TestUtils.swift b/Tests/TypesenseTests/TestUtils.swift index a71efb9..9e7c402 100644 --- a/Tests/TypesenseTests/TestUtils.swift +++ b/Tests/TypesenseTests/TestUtils.swift @@ -5,7 +5,7 @@ let client = Client(config: CONFIG) let utilClient = Client(config: Configuration(nodes: NODES, apiKey: "xyz")) func tearDownCollections() async throws { - let (collResp, _) = try await utilClient.collections().retrieveAll() + let (collResp, _) = try await utilClient.collections.retrieveAll() guard let validData = collResp else { throw DataError.dataNotFound } @@ -93,7 +93,7 @@ func createCollection() async throws { ], defaultSortingField: "num_employees", enableNestedFields: true) - let _ = try await utilClient.collections().create(schema: schema) + let _ = try await utilClient.collections.create(schema: schema) } func createDocument() async throws { @@ -159,7 +159,7 @@ func createConversationCollection() async throws { Field(name: "role", type: "string", index: false), Field(name: "message", type: "string", index: false) ]) - let _ = try await utilClient.collections().create(schema: schema) + let _ = try await utilClient.collections.create(schema: schema) } func createSynonymSet() async throws { From b68fe89512f6e716038777b1e6911c9257822dd1 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Tue, 16 Dec 2025 09:38:12 +0700 Subject: [PATCH 19/21] remove openapi.ynl --- .gitignore | 4 +- Sources/Typesense/Models/Field.swift | 7 +- openapi.yml | 4617 -------------------------- preprocessed_openapi.yml | 5 + 4 files changed, 14 insertions(+), 4619 deletions(-) delete mode 100644 openapi.yml diff --git a/.gitignore b/.gitignore index 10032af..6f231b0 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,6 @@ xcuserdata/ DerivedData/ .swiftpm -/typesense-data \ No newline at end of file +/typesense-data + +openapi.yml \ No newline at end of file diff --git a/Sources/Typesense/Models/Field.swift b/Sources/Typesense/Models/Field.swift index cea6c85..a89f024 100644 --- a/Sources/Typesense/Models/Field.swift +++ b/Sources/Typesense/Models/Field.swift @@ -22,6 +22,8 @@ public struct Field: Codable { public var _infix: Bool? = false /** Name of a field in another collection that should be linked to this collection so that it can be joined during query. */ public var reference: String? + /** Allow documents to be indexed successfully even when the referenced document doesn't exist yet. */ + public var asyncReference: Bool? public var numDim: Int? public var drop: Bool? /** When set to false, the field value will not be stored on disk. Default: true. */ @@ -40,7 +42,7 @@ public struct Field: Codable { public var symbolsToIndex: [String]? public var embed: FieldEmbed? - public init(name: String, type: String, _optional: Bool? = nil, facet: Bool? = nil, index: Bool? = true, locale: String? = nil, sort: Bool? = nil, _infix: Bool? = false, reference: String? = nil, numDim: Int? = nil, drop: Bool? = nil, store: Bool? = nil, vecDist: String? = nil, rangeIndex: Bool? = nil, stem: Bool? = nil, stemDictionary: String? = nil, tokenSeparators: [String]? = nil, symbolsToIndex: [String]? = nil, embed: FieldEmbed? = nil) { + public init(name: String, type: String, _optional: Bool? = nil, facet: Bool? = nil, index: Bool? = true, locale: String? = nil, sort: Bool? = nil, _infix: Bool? = false, reference: String? = nil, asyncReference: Bool? = nil, numDim: Int? = nil, drop: Bool? = nil, store: Bool? = nil, vecDist: String? = nil, rangeIndex: Bool? = nil, stem: Bool? = nil, stemDictionary: String? = nil, tokenSeparators: [String]? = nil, symbolsToIndex: [String]? = nil, embed: FieldEmbed? = nil) { self.name = name self.type = type self._optional = _optional @@ -50,6 +52,7 @@ public struct Field: Codable { self.sort = sort self._infix = _infix self.reference = reference + self.asyncReference = asyncReference self.numDim = numDim self.drop = drop self.store = store @@ -72,6 +75,7 @@ public struct Field: Codable { case sort case _infix = "infix" case reference + case asyncReference = "async_reference" case numDim = "num_dim" case drop case store @@ -97,6 +101,7 @@ public struct Field: Codable { try container.encodeIfPresent(sort, forKey: .sort) try container.encodeIfPresent(_infix, forKey: ._infix) try container.encodeIfPresent(reference, forKey: .reference) + try container.encodeIfPresent(asyncReference, forKey: .asyncReference) try container.encodeIfPresent(numDim, forKey: .numDim) try container.encodeIfPresent(drop, forKey: .drop) try container.encodeIfPresent(store, forKey: .store) diff --git a/openapi.yml b/openapi.yml deleted file mode 100644 index 3db4b12..0000000 --- a/openapi.yml +++ /dev/null @@ -1,4617 +0,0 @@ -openapi: 3.0.3 -info: - title: Typesense API - description: "An open source search engine for building delightful search experiences." - version: '30.0' - license: - name: GPL-3.0 - url: https://opensource.org/licenses/GPL-3.0 -servers: - - url: "{protocol}://{hostname}:{port}" - description: Typesense Server - variables: - protocol: - default: http - description: The protocol of your Typesense server - hostname: - default: localhost - description: The hostname of your Typesense server - port: - default: "8108" - description: The port of your Typesense server -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: 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: curation_sets - description: Manage curation sets - - 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 - parameters: - - name: getCollectionsParameters - in: query - schema: - type: object - properties: - exclude_fields: - description: Comma-separated list of fields from the collection to exclude from the response - type: string - limit: - description: > - Number of collections to fetch. - Default: returns all collections. - type: integer - offset: - description: Identifies the starting point to return collections when paginating. - type: integer - 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: updateDocumentsParameters - in: query - schema: - type: object - properties: - filter_by: - 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: deleteDocumentsParameters - in: query - schema: - 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 - 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: searchParameters - required: true - in: query - schema: - $ref: "#/components/schemas/SearchParameters" - 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" - - /synonym_sets: - get: - tags: - - synonyms - summary: List all synonym sets - description: Retrieve all synonym sets - operationId: retrieveSynonymSets - responses: - "200": - description: List of all synonym sets - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/SynonymSetSchema" - - /synonym_sets/{synonymSetName}: - get: - tags: - - synonyms - summary: Retrieve a synonym set - description: Retrieve a specific synonym set by its name - operationId: retrieveSynonymSet - parameters: - - name: synonymSetName - in: path - description: The name of the synonym set to retrieve - required: true - schema: - type: string - responses: - "200": - description: Synonym set fetched - content: - application/json: - schema: - $ref: "#/components/schemas/SynonymSetSchema" - "404": - description: Synonym set not found - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - - put: - tags: - - synonyms - summary: Create or update a synonym set - description: Create or update a synonym set with the given name - operationId: upsertSynonymSet - parameters: - - name: synonymSetName - in: path - description: The name of the synonym set to create/update - required: true - schema: - type: string - requestBody: - description: The synonym set to be created/updated - content: - application/json: - schema: - $ref: "#/components/schemas/SynonymSetCreateSchema" - required: true - responses: - "200": - description: Synonym set successfully created/updated - content: - application/json: - schema: - $ref: "#/components/schemas/SynonymSetSchema" - "400": - description: Bad request, see error message for details - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - delete: - tags: - - synonyms - summary: Delete a synonym set - description: Delete a specific synonym set by its name - operationId: deleteSynonymSet - parameters: - - name: synonymSetName - in: path - description: The name of the synonym set to delete - required: true - schema: - type: string - responses: - "200": - description: Synonym set successfully deleted - content: - application/json: - schema: - $ref: "#/components/schemas/SynonymSetDeleteSchema" - "404": - description: Synonym set not found - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - - /synonym_sets/{synonymSetName}/items: - get: - tags: - - synonyms - summary: List items in a synonym set - description: Retrieve all synonym items in a set - operationId: retrieveSynonymSetItems - parameters: - - name: synonymSetName - in: path - description: The name of the synonym set to retrieve items for - required: true - schema: - type: string - responses: - "200": - description: List of synonym items - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/SynonymItemSchema" - "404": - description: Synonym set not found - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - - /synonym_sets/{synonymSetName}/items/{itemId}: - get: - tags: - - synonyms - summary: Retrieve a synonym set item - description: Retrieve a specific synonym item by its id - operationId: retrieveSynonymSetItem - parameters: - - name: synonymSetName - in: path - description: The name of the synonym set - required: true - schema: - type: string - - name: itemId - in: path - description: The id of the synonym item to retrieve - required: true - schema: - type: string - responses: - "200": - description: Synonym item fetched - content: - application/json: - schema: - $ref: "#/components/schemas/SynonymItemSchema" - "404": - description: Synonym item not found - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - put: - tags: - - synonyms - summary: Create or update a synonym set item - description: Create or update a synonym set item with the given id - operationId: upsertSynonymSetItem - parameters: - - name: synonymSetName - in: path - description: The name of the synonym set - required: true - schema: - type: string - - name: itemId - in: path - description: The id of the synonym item to upsert - required: true - schema: - type: string - requestBody: - description: The synonym item to be created/updated - content: - application/json: - schema: - $ref: "#/components/schemas/SynonymItemUpsertSchema" - required: true - responses: - "200": - description: Synonym item successfully created/updated - content: - application/json: - schema: - $ref: "#/components/schemas/SynonymItemSchema" - "400": - description: Bad request, see error message for details - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - delete: - tags: - - synonyms - summary: Delete a synonym set item - description: Delete a specific synonym item by its id - operationId: deleteSynonymSetItem - parameters: - - name: synonymSetName - in: path - description: The name of the synonym set - required: true - schema: - type: string - - name: itemId - in: path - description: The id of the synonym item to delete - required: true - schema: - type: string - responses: - "200": - description: Synonym item successfully deleted - content: - application/json: - schema: - $ref: "#/components/schemas/SynonymItemDeleteSchema" - "404": - description: Synonym item not found - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - - /curation_sets: - get: - tags: - - curation_sets - summary: List all curation sets - description: Retrieve all curation sets - operationId: retrieveCurationSets - responses: - "200": - description: List of all curation sets - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/CurationSetSchema" - - /curation_sets/{curationSetName}: - get: - tags: - - curation_sets - summary: Retrieve a curation set - description: Retrieve a specific curation set by its name - operationId: retrieveCurationSet - parameters: - - name: curationSetName - in: path - description: The name of the curation set to retrieve - required: true - schema: - type: string - responses: - "200": - description: Curation set fetched - content: - application/json: - schema: - $ref: "#/components/schemas/CurationSetSchema" - "404": - description: Curation set not found - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - put: - tags: - - curation_sets - summary: Create or update a curation set - description: Create or update a curation set with the given name - operationId: upsertCurationSet - parameters: - - name: curationSetName - in: path - description: The name of the curation set to create/update - required: true - schema: - type: string - requestBody: - description: The curation set to be created/updated - content: - application/json: - schema: - $ref: "#/components/schemas/CurationSetCreateSchema" - required: true - responses: - "200": - description: Curation set successfully created/updated - content: - application/json: - schema: - $ref: "#/components/schemas/CurationSetSchema" - "400": - description: Bad request, see error message for details - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - delete: - tags: - - curation_sets - summary: Delete a curation set - description: Delete a specific curation set by its name - operationId: deleteCurationSet - parameters: - - name: curationSetName - in: path - description: The name of the curation set to delete - required: true - schema: - type: string - responses: - "200": - description: Curation set successfully deleted - content: - application/json: - schema: - $ref: "#/components/schemas/CurationSetDeleteSchema" - "404": - description: Curation set not found - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - - /curation_sets/{curationSetName}/items: - get: - tags: - - curation_sets - summary: List items in a curation set - description: Retrieve all curation items in a set - operationId: retrieveCurationSetItems - parameters: - - name: curationSetName - in: path - description: The name of the curation set to retrieve items for - required: true - schema: - type: string - responses: - "200": - description: List of curation items - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/CurationItemSchema" - "404": - description: Curation set not found - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - - /curation_sets/{curationSetName}/items/{itemId}: - get: - tags: - - curation_sets - summary: Retrieve a curation set item - description: Retrieve a specific curation item by its id - operationId: retrieveCurationSetItem - parameters: - - name: curationSetName - in: path - description: The name of the curation set - required: true - schema: - type: string - - name: itemId - in: path - description: The id of the curation item to retrieve - required: true - schema: - type: string - responses: - "200": - description: Curation item fetched - content: - application/json: - schema: - $ref: "#/components/schemas/CurationItemSchema" - "404": - description: Curation item not found - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - put: - tags: - - curation_sets - summary: Create or update a curation set item - description: Create or update a curation set item with the given id - operationId: upsertCurationSetItem - parameters: - - name: curationSetName - in: path - description: The name of the curation set - required: true - schema: - type: string - - name: itemId - in: path - description: The id of the curation item to upsert - required: true - schema: - type: string - requestBody: - description: The curation item to be created/updated - content: - application/json: - schema: - $ref: "#/components/schemas/CurationItemCreateSchema" - required: true - responses: - "200": - description: Curation item successfully created/updated - content: - application/json: - schema: - $ref: "#/components/schemas/CurationItemSchema" - "400": - description: Bad request, see error message for details - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - delete: - tags: - - curation_sets - summary: Delete a curation set item - description: Delete a specific curation item by its id - operationId: deleteCurationSetItem - parameters: - - name: curationSetName - in: path - description: The name of the curation set - required: true - schema: - type: string - - name: itemId - in: path - description: The id of the curation item to delete - required: true - schema: - type: string - responses: - "200": - description: Curation item successfully deleted - content: - application/json: - schema: - $ref: "#/components/schemas/CurationItemDeleteSchema" - "404": - description: Curation item 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: exportDocumentsParameters - in: query - schema: - 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 - - 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 - # Do not change the index position of this param - - name: importDocumentsParameters - in: query - schema: - 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" - 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: Retrieve 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: - summary: Create a conversation model - description: Create a Conversation Model - operationId: createConversationModel - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/ConversationModelCreateSchema' - required: true - responses: - '201': - 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" - /operations/cache/clear: - post: - tags: - - operations - summary: Clear the cached responses of search requests in the LRU cache. - description: - Clear the cached responses of search requests that are sent with `use_cache` parameter in the LRU cache. - operationId: clearCache - responses: - '200': - description: Clear cache succeeded. - content: - application/json: - schema: - $ref: "#/components/schemas/SuccessStatus" - /operations/db/compact: - post: - tags: - - operations - summary: Compacting the on-disk database - description: - Typesense uses RocksDB to store your documents on the disk. If you do frequent writes or updates, you could benefit from running a compaction of the underlying RocksDB database. - This could reduce the size of the database and decrease read latency. While the database will not block during this operation, we recommend running it during off-peak hours. - operationId: compactDb - responses: - '200': - description: Compacting the on-disk database succeeded. - content: - application/json: - schema: - $ref: "#/components/schemas/SuccessStatus" - /config: - post: - tags: - - operations - summary: Toggle Slow Request Log - description: - Enable logging of requests that take over a defined threshold of time. - Default is `-1` which disables slow request logging. - Slow requests are logged to the primary log file, with the prefix SLOW REQUEST. - operationId: toggleSlowRequestLog - requestBody: - content: - application/json: - schema: - type: object - properties: - log-slow-requests-time-ms: - type: integer - required: - - log-slow-requests-time-ms - example: | - {"log-slow-requests-time-ms": 2000} - responses: - '200': - description: Toggle Slow Request Log database succeeded. - 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: multiSearchParameters - required: true - in: query - schema: - $ref: "#/components/schemas/MultiSearchParameters" - 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: Submit a single analytics event. The event must correspond to an existing analytics rule by name. - operationId: createAnalyticsEvent - requestBody: - description: The analytics event to be created - content: - application/json: - schema: - $ref: '#/components/schemas/AnalyticsEvent' - required: true - responses: - '200': - 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' - get: - tags: - - analytics - summary: Retrieve analytics events - description: Retrieve the most recent events for a user and rule. - operationId: getAnalyticsEvents - parameters: - - name: user_id - in: query - required: true - schema: - type: string - - name: name - in: query - description: Analytics rule name - required: true - schema: - type: string - - name: n - in: query - description: Number of events to return (max 1000) - required: true - schema: - type: integer - responses: - '200': - description: Events fetched - content: - application/json: - schema: - $ref: '#/components/schemas/AnalyticsEventsResponse' - '400': - description: Bad request, see error message for details - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - /analytics/flush: - post: - tags: - - analytics - summary: Flush in-memory analytics to disk - description: Triggers a flush of analytics data to persistent storage. - operationId: flushAnalytics - responses: - '200': - description: Flush triggered - content: - application/json: - schema: - $ref: '#/components/schemas/AnalyticsEventCreateResponse' - /analytics/status: - get: - tags: - - analytics - summary: Get analytics subsystem status - description: Returns sizes of internal analytics buffers and queues. - operationId: getAnalyticsStatus - responses: - '200': - description: Status fetched - content: - application/json: - schema: - $ref: '#/components/schemas/AnalyticsStatus' - /analytics/rules: - post: - tags: - - analytics - summary: Create analytics rule(s) - description: Create one or more analytics rules. You can send a single rule object or an array of rule objects. - operationId: createAnalyticsRule - requestBody: - description: The analytics rule(s) to be created - content: - application/json: - schema: - oneOf: - - $ref: "#/components/schemas/AnalyticsRuleCreate" - - type: array - items: - $ref: "#/components/schemas/AnalyticsRuleCreate" - required: true - responses: - '200': - description: Analytics rule(s) successfully created - content: - application/json: - schema: - oneOf: - - $ref: "#/components/schemas/AnalyticsRule" - - type: array - items: - oneOf: - - $ref: "#/components/schemas/AnalyticsRule" - - type: object - properties: - error: - type: string - '400': - description: Bad request, see error message for details - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - get: - tags: - - analytics - summary: Retrieve analytics rules - description: Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. - operationId: retrieveAnalyticsRules - parameters: - - in: query - name: rule_tag - schema: - type: string - required: false - description: Filter rules by rule_tag - responses: - '200': - description: Analytics rules fetched - content: - application/json: - schema: - type: array - items: - $ref: "#/components/schemas/AnalyticsRule" - /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/AnalyticsRuleUpdate" - required: true - responses: - '200': - description: Analytics rule successfully upserted - content: - application/json: - schema: - $ref: "#/components/schemas/AnalyticsRule" - '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/AnalyticsRule" - '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/AnalyticsRule" - '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 # Go with the first field name listed above to produce sane defaults - 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 # characters only - # Could `enum` be used instead, given it's symbols/special *characters*, e.g.: - # enum: ["@", "!", ".", "/", ","] - minLength: 1 - maxLength: 1 - default: [] - synonym_sets: - type: array - description: List of synonym set names to associate with this collection - items: - type: string - example: "synonym_set_1" - 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 # characters only - # Could `enum` be used instead, given it's symbols/special *characters*, e.g.: - # enum: ["@", "!", ".", "/", ","] - minLength: 1 - maxLength: 1 - default: [] - voice_query_model: - $ref: "#/components/schemas/VoiceQueryModelCollectionConfig" - metadata: - type: object - description: > - Optional details about the collection, e.g., when it was created, who created it etc. - 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" - synonym_sets: - type: array - description: List of synonym set names to associate with this collection - items: - type: string - example: "synonym_set_1" - metadata: - type: object - description: > - Optional details about the collection, e.g., when it was created, who created it etc. - 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 - # 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: - - 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: - $ref: "#/components/schemas/SearchRequestParams" - conversation: - $ref: "#/components/schemas/SearchResultConversation" - union_request_params: - type: array - description: Returned only for union query response. - items: - $ref: "#/components/schemas/SearchRequestParams" - metadata: - type: object - description: Custom JSON object that can be returned in the search response - additionalProperties: true - SearchRequestParams: - 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 - 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 - additionalProperties: - type: object - 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 - hybrid_search_info: - type: object - description: Information about hybrid search scoring - properties: - rank_fusion_score: - type: number - format: float - description: Combined score from rank fusion of text and vector search - search_index: - type: integer - description: Returned only for union query response. Indicates the index of the query which this document matched to. - 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{}" - 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" - 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 your open 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 - - enable_analytics: - description: > - Flag for enabling/disabling analytics aggregation for specific search - queries (for e.g. those originating from a test script). - 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 - - synonym_sets: - type: string - description: List of synonym set names to associate with this search query - example: "synonym_set_1,synonym_set_2" - - 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 - - enable_analytics: - description: > - Flag for enabling/disabling analytics aggregation for specific search - queries (for e.g. those originating from a test script). - type: boolean - 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 - default: false - 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 - AnalyticsEvent: - type: object - required: - - name - - event_type - - data - properties: - name: - type: string - description: Name of the analytics rule this event corresponds to - event_type: - type: string - description: Type of event (e.g., click, conversion, query, visit) - data: - type: object - description: Event payload - properties: - user_id: - type: string - doc_id: - type: string - doc_ids: - type: array - items: - type: string - q: - type: string - analytics_tag: - type: string - AnalyticsEventsResponse: - type: object - required: - - events - properties: - events: - type: array - items: - type: object - properties: - name: { type: string } - event_type: { type: string } - collection: { type: string } - timestamp: { type: integer, format: int64 } - user_id: { type: string } - doc_id: { type: string } - doc_ids: - type: array - items: { type: string } - query: { type: string } - AnalyticsRuleCreate: - type: object - required: - - name - - type - - collection - - event_type - properties: - name: - type: string - type: - $ref: "#/components/schemas/AnalyticsRuleType" - collection: - type: string - event_type: - type: string - rule_tag: - type: string - params: - type: object - properties: - destination_collection: - type: string - limit: - type: integer - capture_search_requests: - type: boolean - meta_fields: - type: array - items: { type: string } - expand_query: - type: boolean - counter_field: - type: string - weight: - type: integer - AnalyticsRuleType: - type: string - enum: [popular_queries, nohits_queries, counter, log] - AnalyticsRuleUpdate: - type: object - description: Fields allowed to update on an analytics rule - properties: - name: - type: string - rule_tag: - type: string - params: - type: object - properties: - destination_collection: - type: string - limit: - type: integer - capture_search_requests: - type: boolean - meta_fields: - type: array - items: { type: string } - expand_query: - type: boolean - counter_field: - type: string - weight: - type: integer - AnalyticsRule: - allOf: - - $ref: '#/components/schemas/AnalyticsRuleCreate' - - type: object - AnalyticsStatus: - type: object - properties: - popular_prefix_queries: { type: integer } - nohits_prefix_queries: { type: integer } - log_prefix_queries: { type: integer } - query_log_events: { type: integer } - query_counter_events: { type: integer } - doc_log_events: { type: integer } - doc_counter_events: { type: integer } - - 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 - 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 up to 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 - - SynonymItemUpsertSchema: - type: object - required: - - synonyms - properties: - synonyms: - type: array - description: Array of words that should be considered as synonyms - items: - type: string - root: - type: string - description: For 1-way synonyms, indicates the root word that words in the synonyms parameter map to - 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 - - SynonymItemSchema: - allOf: - - type: object - required: - - id - properties: - id: - type: string - description: Unique identifier for the synonym item - - $ref: "#/components/schemas/SynonymItemUpsertSchema" - - SynonymSetCreateSchema: - type: object - required: - - items - properties: - items: - type: array - description: Array of synonym items - items: - $ref: "#/components/schemas/SynonymItemSchema" - - SynonymSetSchema: - allOf: - - $ref: "#/components/schemas/SynonymSetCreateSchema" - - type: object - required: - - name - properties: - name: - type: string - description: Name of the synonym set - - SynonymSetsRetrieveSchema: - type: object - required: - - synonym_sets - properties: - synonym_sets: - type: array - description: Array of synonym sets - items: - $ref: "#/components/schemas/SynonymSetSchema" - - - SynonymSetDeleteSchema: - type: object - required: - - name - properties: - name: - type: string - description: Name of the deleted synonym set - - SynonymItemDeleteSchema: - type: object - required: - - id - properties: - id: - type: string - description: ID of the deleted synonym item - - CurationItemCreateSchema: - type: object - required: - - rule - properties: - rule: - $ref: '#/components/schemas/CurationRule' - 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/CurationInclude' - excludes: - type: array - description: List of document `id`s that should be excluded from the search results. - items: - $ref: '#/components/schemas/CurationExclude' - filter_by: - type: string - description: > - A filter by clause that is applied to any search query that matches the curation rule. - remove_matched_tokens: - type: boolean - description: > - Indicates whether search query tokens that exist in the curation'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 curation rule. - replace_query: - type: string - description: > - Replaces the current search query with this value, when the search query matches the curation 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 curation will be active. You can use this to create 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 curation will be active. You can use this to create rules that stop applying after a period of time. - stop_processing: - type: boolean - description: > - When set to true, curation processing will stop at the first matching rule. When set to false curation processing will continue and multiple curation actions will be triggered in sequence. - Curations are processed in the lexical sort order of their id field. - id: - type: string - description: ID of the curation item - - - CurationItemSchema: - allOf: - - $ref: '#/components/schemas/CurationItemCreateSchema' - - type: object - required: - - id - properties: - id: - type: string - - CurationSetCreateSchema: - type: object - required: - - items - properties: - items: - type: array - description: Array of curation items - items: - $ref: '#/components/schemas/CurationItemCreateSchema' - description: - type: string - description: Optional description for the curation set - - CurationSetSchema: - allOf: - - $ref: '#/components/schemas/CurationSetCreateSchema' - - type: object - required: - - name - properties: - name: - type: string - - CurationRule: - type: object - properties: - tags: - type: array - description: List of tag values to associate with this curation rule. - items: - type: string - query: - type: string - description: Indicates what search queries should be curated - 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 curation should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). - - CurationInclude: - 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 - - CurationExclude: - type: object - required: - - id - properties: - id: - type: string - description: document id that should be excluded from the search results. - - CurationSetDeleteSchema: - type: object - required: - - name - properties: - name: - type: string - description: Name of the deleted curation set - CurationItemDeleteSchema: - type: object - required: - - id - properties: - id: - type: string - description: ID of the deleted curation item - - securitySchemes: - api_key_header: - type: apiKey - name: X-TYPESENSE-API-KEY - in: header diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml index ec5150f..2a16ef0 100644 --- a/preprocessed_openapi.yml +++ b/preprocessed_openapi.yml @@ -3503,6 +3503,11 @@ components: description: > Name of a field in another collection that should be linked to this collection so that it can be joined during query. + async_reference: + type: boolean + description: > + Allow documents to be indexed successfully even when the referenced document + doesn't exist yet. num_dim: type: integer example: 256 From 9d9c3d7dd7fd7dda044ef424dfd5f09b11a71ac3 Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Tue, 16 Dec 2025 09:41:54 +0700 Subject: [PATCH 20/21] Update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d04d448..4060783 100644 --- a/README.md +++ b/README.md @@ -458,7 +458,7 @@ swift run Tasks code-gen This will: - Download the latest API spec. -- Write it to our local [`openapi.yml`](./openapi.yml). +- Write it to our local `openapi.yml`. - Preprocess it into [`preprocessed_openapi.yml`](./preprocessed_openapi.yml). - Generate and replace the `Sources/Typesense/Models` folder. From 2aa38157749103d93a5c515d1bc2c7a181dc325e Mon Sep 17 00:00:00 2001 From: Hayden Hung Hoang Date: Tue, 16 Dec 2025 12:25:19 +0700 Subject: [PATCH 21/21] rerun github actions --- compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compose.yml b/compose.yml index f12a436..48ac23c 100644 --- a/compose.yml +++ b/compose.yml @@ -1,6 +1,6 @@ services: typesense: - image: typesense/typesense:30.0.rca33 + image: typesense/typesense:30.0.rca34 restart: on-failure ports: - '8108:8108'