diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index ef65ee7..30f477b 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -16,27 +16,28 @@ concurrency: jobs: test: - runs-on: macos-latest + runs-on: macos-15-intel 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.2 + with: + lima: v1.2.1 + colima: v0.9.1 + colima-network-address: false - name: Run Typesense run: | 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 diff --git a/.gitignore b/.gitignore index e284f64..6f231b0 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,7 @@ xcuserdata/ DerivedData/ .swiftpm + +/typesense-data + +openapi.yml \ No newline at end of file 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/README.md b/README.md index 6fe5918..4060783 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) ``` @@ -214,50 +214,76 @@ 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 +### Create or update a curation set ```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) +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 overrides +### Retrieve all curation sets ```swift -let (data, response) = try await client.collection(name: "books").overrides().retrieve(metadataType: Never.self) +let (data, response) = try await client.curationSets().retrieve() ``` -### Retrieve an override +### Retrieve a curation set ```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").retrieve() ``` -### Delete an override +### Delete a curation set ```swift -let (data, response) = try await client.collection(name: "books").override("test-id").delete() +let (data, response) = try await client.curationSet("curate_products").delete() +``` + +### Retrieve all curation set items + +```swift +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 a curation set item + +```swift +let (data, response) = try await client.curationSet("curate_products").item("customize-apple").retrieve() +``` + +### Delete a curation set item + +```swift +let (data, response) = try await client.curationSet("curate_products").item("customize-apple").delete() ``` ### Create or update a preset ```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 +300,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) } ``` @@ -318,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 @@ -390,13 +443,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 [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). -```shell -sh get-models.sh +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: + +```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`. +- 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 diff --git a/Sources/Typesense/Analytics.swift b/Sources/Typesense/Analytics.swift index a14f507..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 @@ -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..0cca3bd 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,13 +11,25 @@ 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) } 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/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..1d42a57 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.post(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 -> ([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([AnalyticsRuleCreateManyResponseItem].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/Client.swift b/Sources/Typesense/Client.swift index 93191e7..bbb21ce 100644 --- a/Sources/Typesense/Client.swift +++ b/Sources/Typesense/Client.swift @@ -4,12 +4,13 @@ public struct Client { var configuration: Configuration var apiCall: ApiCall - public var collections: Collections + public var collections: Collections { + return Collections(apiCall: apiCall) + } public init(config: Configuration) { self.configuration = config self.apiCall = ApiCall(config: config) - self.collections = Collections(apiCall: apiCall) } public func collection(name: String) -> Collection { @@ -20,6 +21,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) } @@ -55,4 +64,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 95eef68..ee245a0 100644 --- a/Sources/Typesense/Collection.swift +++ b/Sources/Typesense/Collection.swift @@ -39,18 +39,6 @@ public struct Collection { return (nil, response) } - public func synonyms() -> Synonyms { - 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/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/APIStatsResponse.swift b/Sources/Typesense/Models/APIStatsResponse.swift new file mode 100644 index 0000000..b4d9605 --- /dev/null +++ b/Sources/Typesense/Models/APIStatsResponse.swift @@ -0,0 +1,79 @@ +// +// 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..9c9acfd --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsEvent.swift @@ -0,0 +1,41 @@ +// +// 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..f91d369 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,14 @@ 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..dc60eca --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsEventData.swift @@ -0,0 +1,48 @@ +// +// 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..a8477ed --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsEventsResponse.swift @@ -0,0 +1,31 @@ +// +// 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..5d1b2f9 --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsEventsResponseEventsInner.swift @@ -0,0 +1,59 @@ +// +// 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/AnalyticsEventsRetrieveParams.swift b/Sources/Typesense/Models/AnalyticsEventsRetrieveParams.swift new file mode 100644 index 0000000..d56e657 --- /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 { + + public var userId: String + /** Analytics rule name */ + public var name: String + /** Number of events to return (max 1000) */ + public var n: Int + + public init(userId: String, name: String, n: Int) { + self.userId = userId + self.name = name + self.n = n + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + 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(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 new file mode 100644 index 0000000..75708a8 --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsRule.swift @@ -0,0 +1,51 @@ +// +// AnalyticsRule.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AnalyticsRule: Codable { + + public var name: String + public var type: AnalyticsRuleType + public var collection: String + public var eventType: String + public var ruleTag: String? + public var params: AnalyticsRuleCreateParams? + + 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.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..63d237d --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsRuleCreate.swift @@ -0,0 +1,51 @@ +// +// AnalyticsRuleCreate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AnalyticsRuleCreate: Codable { + + public var name: String + public var type: AnalyticsRuleType + public var collection: String + public var eventType: String + public var ruleTag: String? + public var params: AnalyticsRuleCreateParams? + + 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.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..624c005 --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsRuleCreateParams.swift @@ -0,0 +1,55 @@ +// +// 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/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 new file mode 100644 index 0000000..2f08ccb --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsRuleUpdate.swift @@ -0,0 +1,40 @@ +// +// 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..996644e --- /dev/null +++ b/Sources/Typesense/Models/AnalyticsStatus.swift @@ -0,0 +1,55 @@ +// +// 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..6e3bf18 100644 --- a/Sources/Typesense/Models/ApiKey.swift +++ b/Sources/Typesense/Models/ApiKey.swift @@ -1,42 +1,55 @@ // // 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(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.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..84dbb36 --- /dev/null +++ b/Sources/Typesense/Models/ApiKeyDeleteResponse.swift @@ -0,0 +1,32 @@ +// +// 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..3419388 100644 --- a/Sources/Typesense/Models/ApiKeySchema.swift +++ b/Sources/Typesense/Models/ApiKeySchema.swift @@ -1,36 +1,47 @@ // // 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(description: String, actions: [String], collections: [String], value: String? = nil, 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..8e5c400 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,14 @@ 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..e68a60c 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,14 @@ 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..bf78fed 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,16 @@ 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..6a99eff 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,14 @@ 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..b8dd182 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,14 @@ 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..1e2cbbd 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,65 @@ 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], 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.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..2534521 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,55 @@ 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..8dc6d6b 100644 --- a/Sources/Typesense/Models/CollectionUpdateSchema.swift +++ b/Sources/Typesense/Models/CollectionUpdateSchema.swift @@ -1,22 +1,42 @@ // // 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..2f29948 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(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.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,18 @@ 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..d92f166 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, historyCollection: String, maxBytes: Int, apiKey: String? = nil, accountId: String? = nil, systemPrompt: String? = nil, ttl: Int? = nil, 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,18 @@ 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..f3da479 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,18 @@ 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/CurationExclude.swift b/Sources/Typesense/Models/CurationExclude.swift new file mode 100644 index 0000000..24bd770 --- /dev/null +++ b/Sources/Typesense/Models/CurationExclude.swift @@ -0,0 +1,32 @@ +// +// 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..03f10a3 --- /dev/null +++ b/Sources/Typesense/Models/CurationInclude.swift @@ -0,0 +1,37 @@ +// +// 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..70d77c9 --- /dev/null +++ b/Sources/Typesense/Models/CurationItemCreateSchema.swift @@ -0,0 +1,91 @@ +// +// 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..1bc3fb5 --- /dev/null +++ b/Sources/Typesense/Models/CurationItemDeleteSchema.swift @@ -0,0 +1,32 @@ +// +// 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..fa02dd4 --- /dev/null +++ b/Sources/Typesense/Models/CurationItemSchema.swift @@ -0,0 +1,90 @@ +// +// 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, 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.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..f77b495 --- /dev/null +++ b/Sources/Typesense/Models/CurationRule.swift @@ -0,0 +1,51 @@ +// +// 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..e8c6fc6 --- /dev/null +++ b/Sources/Typesense/Models/CurationSetCreateSchema.swift @@ -0,0 +1,37 @@ +// +// 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..aca1326 --- /dev/null +++ b/Sources/Typesense/Models/CurationSetDeleteSchema.swift @@ -0,0 +1,32 @@ +// +// 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..f67b4d0 --- /dev/null +++ b/Sources/Typesense/Models/CurationSetSchema.swift @@ -0,0 +1,41 @@ +// +// 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], name: String, description: String? = nil) { + 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..d7284b1 --- /dev/null +++ b/Sources/Typesense/Models/Debug200Response.swift @@ -0,0 +1,31 @@ +// +// 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..00e00a1 --- /dev/null +++ b/Sources/Typesense/Models/DeleteDocuments200Response.swift @@ -0,0 +1,31 @@ +// +// 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/DeleteDocumentsParameters.swift b/Sources/Typesense/Models/DeleteDocumentsParameters.swift index ed22c2a..8c6ed01 100644 --- a/Sources/Typesense/Models/DeleteDocumentsParameters.swift +++ b/Sources/Typesense/Models/DeleteDocumentsParameters.swift @@ -1,13 +1,14 @@ // // DeleteDocumentsParameters.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 DeleteDocumentsParameters: Codable { @@ -15,17 +16,30 @@ public struct DeleteDocumentsParameters: Codable { /** 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) { + 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 { + 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/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..2cb1c6e --- /dev/null +++ b/Sources/Typesense/Models/DeleteStopwordsSet200Response.swift @@ -0,0 +1,31 @@ +// +// 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/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/ExportDocumentsParameters.swift b/Sources/Typesense/Models/ExportDocumentsParameters.swift index a4d2a27..8725d70 100644 --- a/Sources/Typesense/Models/ExportDocumentsParameters.swift +++ b/Sources/Typesense/Models/ExportDocumentsParameters.swift @@ -1,17 +1,18 @@ // // ExportDocumentsParameters.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 ExportDocumentsParameters: Codable { - /** Filter conditions for refining your search results. Separate multiple conditions with &&. */ + /** 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? @@ -24,10 +25,18 @@ public struct ExportDocumentsParameters: Codable { self.excludeFields = excludeFields } - public enum CodingKeys: String, CodingKey { + 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/FacetCounts.swift b/Sources/Typesense/Models/FacetCounts.swift index 4471f35..a754e2a 100644 --- a/Sources/Typesense/Models/FacetCounts.swift +++ b/Sources/Typesense/Models/FacetCounts.swift @@ -1,30 +1,39 @@ // // 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..b07d31a --- /dev/null +++ b/Sources/Typesense/Models/FacetCountsCountsInner.swift @@ -0,0 +1,43 @@ +// +// 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..b78151f 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,14 @@ 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..a89f024 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,33 @@ 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? + /** 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? - /** 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, 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 @@ -36,13 +52,20 @@ 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 + 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" @@ -52,10 +75,42 @@ public struct Field: Codable { case sort case _infix = "infix" case reference + case asyncReference = "async_reference" 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(asyncReference, forKey: .asyncReference) + 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..93295ab 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,16 @@ 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..a0fd5ee 100644 --- a/Sources/Typesense/Models/FieldEmbedModelConfig.swift +++ b/Sources/Typesense/Models/FieldEmbedModelConfig.swift @@ -1,39 +1,67 @@ // // 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/GetCollectionsParameters.swift b/Sources/Typesense/Models/GetCollectionsParameters.swift new file mode 100644 index 0000000..5ad74d9 --- /dev/null +++ b/Sources/Typesense/Models/GetCollectionsParameters.swift @@ -0,0 +1,42 @@ +// +// GetCollectionsParameters.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct GetCollectionsParameters: 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..171f145 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,14 @@ 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/ImportDocumentsParameters.swift b/Sources/Typesense/Models/ImportDocumentsParameters.swift index f925975..96e6127 100644 --- a/Sources/Typesense/Models/ImportDocumentsParameters.swift +++ b/Sources/Typesense/Models/ImportDocumentsParameters.swift @@ -1,39 +1,52 @@ // // ImportDocumentsParameters.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 ImportDocumentsParameters: Codable { - public var action: IndexAction? public var batchSize: Int? - 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 var remoteEmbeddingBatchSize: Int? public var returnDoc: Bool? - public var returnId: 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 { - case action + public enum CodingKeys: String, CodingKey, CaseIterable { 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(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/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..08c1cf7 --- /dev/null +++ b/Sources/Typesense/Models/ListStemmingDictionaries200Response.swift @@ -0,0 +1,31 @@ +// +// 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..8ae335a 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,84 @@ 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..94747f7 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,75 @@ 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..b9452b7 100644 --- a/Sources/Typesense/Models/MultiSearchResult.swift +++ b/Sources/Typesense/Models/MultiSearchResult.swift @@ -1,23 +1,35 @@ // // 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..cce397b --- /dev/null +++ b/Sources/Typesense/Models/MultiSearchResultItem.swift @@ -0,0 +1,97 @@ +// +// 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..e4dc3d9 100644 --- a/Sources/Typesense/Models/MultiSearchSearchesParameter.swift +++ b/Sources/Typesense/Models/MultiSearchSearchesParameter.swift @@ -1,16 +1,36 @@ // // 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(searches: [MultiSearchCollectionParameters], union: Bool? = false) { + 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..084446d --- /dev/null +++ b/Sources/Typesense/Models/NLSearchModelBase.swift @@ -0,0 +1,117 @@ +// +// 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..f36c105 --- /dev/null +++ b/Sources/Typesense/Models/NLSearchModelCreateSchema.swift @@ -0,0 +1,122 @@ +// +// 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..7e10ecd --- /dev/null +++ b/Sources/Typesense/Models/NLSearchModelDeleteSchema.swift @@ -0,0 +1,32 @@ +// +// 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..26c15b0 --- /dev/null +++ b/Sources/Typesense/Models/NLSearchModelSchema.swift @@ -0,0 +1,122 @@ +// +// 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(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.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..d09eb27 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,14 @@ 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..3048b73 100644 --- a/Sources/Typesense/Models/PresetSchema.swift +++ b/Sources/Typesense/Models/PresetSchema.swift @@ -1,15 +1,35 @@ -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..0c6fd9a 100644 --- a/Sources/Typesense/Models/PresetUpsertSchema.swift +++ b/Sources/Typesense/Models/PresetUpsertSchema.swift @@ -1,14 +1,31 @@ -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..3730fa6 --- /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 { + 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..9a69023 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,14 @@ 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..89d5bbe --- /dev/null +++ b/Sources/Typesense/Models/SchemaChangeStatus.swift @@ -0,0 +1,42 @@ +// +// 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..07974a7 100644 --- a/Sources/Typesense/Models/SearchGroupedHit.swift +++ b/Sources/Typesense/Models/SearchGroupedHit.swift @@ -1,30 +1,40 @@ // // 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] /** 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(groupKey: [AnyCodable], hits: [SearchResultHit]?, found: Int? = nil) { self.found = found self.groupKey = groupKey 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..1d3cfda 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,16 @@ 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..d556845 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,80 @@ 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..a6fc112 --- /dev/null +++ b/Sources/Typesense/Models/SearchRequestParams.swift @@ -0,0 +1,43 @@ +// +// 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..b10322b --- /dev/null +++ b/Sources/Typesense/Models/SearchRequestParamsVoiceQuery.swift @@ -0,0 +1,31 @@ +// +// 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..835ac86 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,26 @@ 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..c96db1a 100644 --- a/Sources/Typesense/Models/SearchResultConversation.swift +++ b/Sources/Typesense/Models/SearchResultConversation.swift @@ -1,33 +1,43 @@ // // 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..b079a63 100644 --- a/Sources/Typesense/Models/SearchResultHit.swift +++ b/Sources/Typesense/Models/SearchResultHit.swift @@ -1,49 +1,69 @@ // // 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]? + /** 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 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: 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.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..04f8d32 --- /dev/null +++ b/Sources/Typesense/Models/SearchResultHitHybridSearchInfo.swift @@ -0,0 +1,33 @@ +// +// 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..9ecf7a3 --- /dev/null +++ b/Sources/Typesense/Models/SearchResultHitTextMatchInfo.swift @@ -0,0 +1,55 @@ +// +// 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..f9175b0 100644 --- a/Sources/Typesense/Models/SearchSynonym.swift +++ b/Sources/Typesense/Models/SearchSynonym.swift @@ -1,40 +1,51 @@ // // 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(synonyms: [String], id: String, root: String? = nil, locale: String? = nil, symbolsToIndex: [String]? = nil) { 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..52a76ee --- /dev/null +++ b/Sources/Typesense/Models/SearchSynonymDeleteResponse.swift @@ -0,0 +1,32 @@ +// +// 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..5866eab 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] @@ -20,18 +21,27 @@ public struct SearchSynonymSchema: Codable { /** 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(root: String? = nil, synonyms: [String], locale: String? = nil, symbolsToIndex: [String]? = nil) { + public init(synonyms: [String], root: String? = nil, locale: String? = nil, symbolsToIndex: [String]? = nil) { self.root = root self.synonyms = synonyms self.locale = locale 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..16bc477 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,14 @@ 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..69a896d --- /dev/null +++ b/Sources/Typesense/Models/StemmingDictionary.swift @@ -0,0 +1,37 @@ +// +// 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..45b4609 --- /dev/null +++ b/Sources/Typesense/Models/StemmingDictionaryWordsInner.swift @@ -0,0 +1,37 @@ +// +// 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..34c0ed9 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,14 @@ 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..e117707 100644 --- a/Sources/Typesense/Models/StopwordsSetSchema.swift +++ b/Sources/Typesense/Models/StopwordsSetSchema.swift @@ -1,30 +1,39 @@ // // 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..0047722 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,16 @@ 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..43d7bc8 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,14 @@ 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..15a126f 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,14 @@ 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..89132d9 --- /dev/null +++ b/Sources/Typesense/Models/SynonymItemDeleteSchema.swift @@ -0,0 +1,32 @@ +// +// 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..13a48e8 --- /dev/null +++ b/Sources/Typesense/Models/SynonymItemSchema.swift @@ -0,0 +1,52 @@ +// +// SynonymItemSchema.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SynonymItemSchema: 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]? + /** Unique identifier for the synonym item */ + public var id: String + + 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.id = id + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case synonyms + case root + 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.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(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/Sources/Typesense/Models/SynonymSetCreateSchema.swift b/Sources/Typesense/Models/SynonymSetCreateSchema.swift new file mode 100644 index 0000000..739de82 --- /dev/null +++ b/Sources/Typesense/Models/SynonymSetCreateSchema.swift @@ -0,0 +1,32 @@ +// +// 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..c2c1e89 --- /dev/null +++ b/Sources/Typesense/Models/SynonymSetDeleteSchema.swift @@ -0,0 +1,32 @@ +// +// 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..82859d3 --- /dev/null +++ b/Sources/Typesense/Models/SynonymSetSchema.swift @@ -0,0 +1,37 @@ +// +// 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..20171d7 --- /dev/null +++ b/Sources/Typesense/Models/SynonymSetsRetrieveSchema.swift @@ -0,0 +1,32 @@ +// +// 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..3071831 --- /dev/null +++ b/Sources/Typesense/Models/ToggleSlowRequestLogRequest.swift @@ -0,0 +1,31 @@ +// +// 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..f451120 --- /dev/null +++ b/Sources/Typesense/Models/UpdateDocuments200Response.swift @@ -0,0 +1,32 @@ +// +// 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/UpdateDocumentsParameters.swift b/Sources/Typesense/Models/UpdateDocumentsParameters.swift new file mode 100644 index 0000000..75f8422 --- /dev/null +++ b/Sources/Typesense/Models/UpdateDocumentsParameters.swift @@ -0,0 +1,31 @@ +// +// UpdateDocumentsParameters.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct UpdateDocumentsParameters: 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..a8d6dd9 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,14 @@ 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/Sources/Typesense/MultiSearch.swift b/Sources/Typesense/MultiSearch.swift index a502fec..cead0b0 100644 --- a/Sources/Typesense/MultiSearch.swift +++ b/Sources/Typesense/MultiSearch.swift @@ -18,232 +18,62 @@ public struct MultiSearch { 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/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 deleted file mode 100644 index 9551615..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 722064c..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/Sources/Typesense/Shared/AnalyticsRuleCreateManyResponse.swift b/Sources/Typesense/Shared/AnalyticsRuleCreateManyResponse.swift new file mode 100644 index 0000000..fb64661 --- /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 AnalyticsRuleCreateManyResponseItem")) + } + } +} + +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/Sources/Typesense/Models/DocumentIndexParameters.swift b/Sources/Typesense/Shared/DocumentIndexParameters.swift similarity index 92% rename from Sources/Typesense/Models/DocumentIndexParameters.swift rename to Sources/Typesense/Shared/DocumentIndexParameters.swift index 49bda1b..7d71e89 100644 --- a/Sources/Typesense/Models/DocumentIndexParameters.swift +++ b/Sources/Typesense/Shared/DocumentIndexParameters.swift @@ -1,7 +1,3 @@ -import Foundation - - - public struct DocumentIndexParameters: Codable { public var dirtyValues: DirtyValues? @@ -14,4 +10,4 @@ public struct DocumentIndexParameters: Codable { 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/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/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/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/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..22265d0 --- /dev/null +++ b/Tasks/AddVendorAttributes.swift @@ -0,0 +1,43 @@ +import Yams + +func addVendorAttributes(_ doc: inout Node) throws { + print("Adding custom x-* vendor attributes...") + let attrs = VendorAttributes(doc: doc) + + // Generic Parameters + // Setting "x-swift-generic-parameter" + try attrs.schemaGenericParameter([ + ("SearchResult", "T: Codable"), + ("SearchGroupedHit", "T: Codable"), + ("SearchResultHit", "T: Codable"), + ("MultiSearchResult", "T: Codable"), + ("MultiSearchResultItem", "T: Codable"), + ]) + + // Field Type Overrides "x-swift-type" + 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 +} \ No newline at end of file diff --git a/Tasks/PreprocessOpenAPI.swift b/Tasks/PreprocessOpenAPI.swift new file mode 100644 index 0000000..752da91 --- /dev/null +++ b/Tasks/PreprocessOpenAPI.swift @@ -0,0 +1,248 @@ +import Foundation +import Yams + +struct PreprocessOpenAPI { + + static func process(input: String, output: String) throws { + print("Reading OpenAPI spec from \(input)...") + let yamlString = try String(contentsOfFile: input, encoding: .utf8) + + // 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...") + + // Create Models from URL Parameters + try createUrlParamsSchema(&doc, name: "AnalyticsEventsRetrieveParams", path: "/analytics/events", method: "get") + + // 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.serialize(node: 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 { + + 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 + } + + var parameters = paramsNode.array() + + guard let index = parameters.firstIndex(where: { $0["name"]?.string == paramName }) else { + throw StringError("Parameter '\(paramName)' not found in \(path)") + } + + let paramObject = parameters[index] + + guard let schema = paramObject["schema"], + let propertiesNode = schema["properties"] else { + throw StringError("Could not extract properties from '\(paramName)'") + } + + if let compName = newComponentName { + print("- Copying inline schema for '\(paramName)' to components.schemas.\(compName)...") + + 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)'...") + + parameters.remove(at: index) + + 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) + } + } + + 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 { + 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") + } + + 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"], + let schemas = components["schemas"], + let searchParams = schemas["MultiSearchParameters"], + let properties = searchParams["properties"] else { + throw StringError("Could not find schema for MultiSearchParameters") + } + + 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"], + var pathItem = paths[path], + var operation = pathItem[method], + let paramsNode = operation["parameters"] else { + return + } + + var parameters = paramsNode.array() + + if let idx = parameters.firstIndex(where: { $0["name"]?.string == removeParam }) { + parameters.remove(at: idx) + } + + 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"] = Node(parameters, .implicit, Node.Sequence.Style.any) + pathItem[method] = operation + paths[path] = pathItem + 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)'...") + + 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 + } + + let parameters = paramsNode.array() + + var propertiesMap: [(Node, Node)] = [] + var requiredFields: [String] = [] + + for param in parameters { + guard param["in"]?.string == "query", + let paramName = param["name"]?.string, + let schema = param["schema"] else { + continue + } + + // Copy schema properties + var propertyDefPairs: [(Node, Node)] = [] + + 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"] { + propertyDefPairs.append((Node("x-swift-type"), customType)) + } + + let propertyDef = Node(propertyDefPairs, .implicit, Node.Mapping.Style.any) + + propertiesMap.append((Node(paramName), propertyDef)) + + if param["required"]?.bool == true { + requiredFields.append(paramName) + } + } + + if propertiesMap.isEmpty { + print("⚠️ No query parameters found for \(name). Skipping.") + return + } + + let propertiesNode = Node(propertiesMap, .implicit, Node.Mapping.Style.any) + + var schemaMap: [(Node, Node)] = [ + (Node("type"), Node("object")), + (Node("properties"), propertiesNode) + ] + + if !requiredFields.isEmpty { + let requiredNodes = requiredFields.map { Node($0) } + schemaMap.append((Node("required"), Node(requiredNodes, .implicit, Node.Sequence.Style.any))) + } + + let newSchema = Node(schemaMap, .implicit, Node.Mapping.Style.any) + + 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"]?[name] = newSchema + + print(" ✅ Created schema '\(name)' with \(propertiesMap.count) properties.") + } +} + +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..c51cc12 --- /dev/null +++ b/Tasks/VendorAttributes.swift @@ -0,0 +1,62 @@ +import Foundation +import Yams + +class VendorAttributes { + var doc: Node + + init(doc: Node) { + self.doc = doc + } + + /// Helper to modify a specific schema in place + private func modifySchema(_ name: String, closure: (inout Node) -> Void) throws { + guard var components = doc["components"], + var schemas = components["schemas"] else { + return + } + + guard var schema = schemas[name] else { + throw StringError( "Schema not found: \(name)") + } + + closure(&schema) + + // 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"] = Node(generic) + } + } + } + + /// Overrides field types in a schema "x-swift-type" + func schemaFieldTypeOverrides(schema: String, overrides: [(String, String)]) throws { + try modifySchema(schema) { schemaNode in + guard var properties = schemaNode["properties"] else { return } + + for (field, swiftType) in overrides { + if var existingProp = properties[field] { + // Update existing + existingProp["x-swift-type"] = Node(swiftType) + properties[field] = existingProp + } else { + // Create new + let newPropPairs: [(Node, Node)] = [ + (Node("x-swift-type"), Node(swiftType)) + ] + let newProp = Node(newPropPairs, .implicit, Node.Mapping.Style.any) + properties[field] = newProp + } + } + + schemaNode["properties"] = properties + } + } +} \ No newline at end of file diff --git a/Tasks/main.swift b/Tasks/main.swift new file mode 100644 index 0000000..835731b --- /dev/null +++ b/Tasks/main.swift @@ -0,0 +1,156 @@ +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", + "-t", "/local/openapi-generator-template", + "-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("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.") + } +} + +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..97f9f03 100644 --- a/Tests/TypesenseTests/AnalyticsTests.swift +++ b/Tests/TypesenseTests/AnalyticsTests.swift @@ -3,8 +3,27 @@ import XCTest final class AnalyticsTests: XCTestCase { override func setUp() async throws { - try await createCollection() - try await createAnalyticRule() + 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: [ + Field(name:"name", type: "string"), + Field(name:"in_stock", type: "int32") + ])) + let _ = try await client.analytics().rules().create(AnalyticsRuleCreate( + name: "homepage_popular_queries", + type: .popularQueries, + collection: "test-products-analytics", + eventType: "search", + ruleTag: "homepage", + params: AnalyticsRuleCreateParams( + destinationCollection: "product_queries", + limit: 100, + captureSearchRequests: true, + ), + + )) } override func tearDown() async throws { @@ -13,33 +32,83 @@ 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: "test-products-analytics", + 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 client.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: "test-products-analytics", + eventType: "search", + ruleTag: "homepage", + params: AnalyticsRuleCreateParams( + destinationCollection: "product_queries", + limit: 100, + ), + ) + let schema2 = AnalyticsRuleCreate( + name: "test_rule_2", + type: .popularQueries, + collection: "test-products-analytics", + eventType: "search", + ruleTag: "homepage", + params: AnalyticsRuleCreateParams( + destinationCollection: "product_queries", + limit: 100, + ), + ) + do { + let (rules, _) = try await client.analytics().rules().createMany([schema1, schema2]) + XCTAssertNotNil(rules) + guard let validRule = rules else { + throw DataError.dataNotFound + } + print(validRule) + 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) + XCTAssertTrue(false) + } + } + 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 +119,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 +132,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 +147,12 @@ 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: "homepage_popular_queries", + eventType: "popular_queries", + data: AnalyticsEventData( + userId: "111112", q: "nike shoes", + ), )) guard let validRes = res else { throw DataError.dataNotFound @@ -93,8 +160,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(userId: "123", name: "homepage_popular_queries", n:10)) + 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/ApiKeyTests.swift b/Tests/TypesenseTests/ApiKeyTests.swift index ed0bf61..95560b5 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/CollectionTests.swift b/Tests/TypesenseTests/CollectionTests.swift index 27fbdab..ca6b2d6 100644 --- a/Tests/TypesenseTests/CollectionTests.swift +++ b/Tests/TypesenseTests/CollectionTests.swift @@ -7,7 +7,13 @@ 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( + 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") do { let (collResp, _) = try await client.collections.create(schema: schema) XCTAssertNotNil(collResp) diff --git a/Tests/TypesenseTests/ConversationModelTests.swift b/Tests/TypesenseTests/ConversationModelTests.swift index 19c3308..986f5b7 100644 --- a/Tests/TypesenseTests/ConversationModelTests.swift +++ b/Tests/TypesenseTests/ConversationModelTests.swift @@ -4,13 +4,11 @@ import XCTest final class ConversationModelTests: XCTestCase { func testConversationModelsCreate() async { let schema = ConversationModelCreateSchema( - _id: "conv-model-1", - modelName: "test/gpt-3.5-turbo", - apiKey: "sk", - historyCollection: "conversation_store", + modelName: "test/gpt-3.5-turbo", historyCollection: "conversation_store", + maxBytes: 16384, + id: "conv-model-1", apiKey: "sk", systemPrompt: "You are an assistant for question-answering.", ttl: 123, - maxBytes: 16384 ) do { try await createConversationCollection() diff --git a/Tests/TypesenseTests/CurationSetTests.swift b/Tests/TypesenseTests/CurationSetTests.swift new file mode 100644 index 0000000..4bc9718 --- /dev/null +++ b/Tests/TypesenseTests/CurationSetTests.swift @@ -0,0 +1,145 @@ +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( query: "apple", match: .exact), + includes: [ + CurationInclude(id: "422", position: 1), + CurationInclude(id: "54", position: 2), + ], excludes: [CurationExclude(id: "287")], + )) + 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 testCurationSetItemDelete() 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..766bd10 --- /dev/null +++ b/Tests/TypesenseTests/CurationSetsTests.swift @@ -0,0 +1,57 @@ +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( query: "apple", match: .exact), + includes: [ + CurationInclude(id: "422", position: 1), + CurationInclude(id: "54", position: 2), + ], excludes: [CurationExclude(id: "287")], + id: "customize-apple" + ) + ]) + 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/DocumentTests.swift b/Tests/TypesenseTests/DocumentTests.swift index 7c4cf75..00c9f5b 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 @@ -227,7 +227,7 @@ final class DocumentTests: XCTestCase { ]) let preset = PresetUpsertSchema( - value: .singleCollectionSearch( + value: .typeSearchParameters( SearchParameters(q: "Jor", queryBy: "name", filterBy: "price:=[50..120]") ) ) @@ -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 4ad92cd..a1951f5 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(name: "products", fields: [ Field(name: "name", type: "string"), Field(name: "price", type: "int32"), Field(name: "brand", type: "string"), Field(name: "desc", type: "string"), ]) - let brandSchema = CollectionSchema(name: "brands", fields: [ Field(name: "name", type: "string"), ]) + + 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(q: "shoe", filterBy: "price:=[50..120]", collection: "products"), + MultiSearchCollectionParameters(q: "Jor", filterBy: "price:=[50..120]", 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(name: "products", fields: [ - Field(name: "name", type: "string"), - Field(name: "price", type: "int32"), - Field(name: "brand", type: "string"), - Field(name: "desc", type: "string"), - ]) - - let brandSchema = CollectionSchema(name: "brands", fields: [ - Field(name: "name", type: "string"), - ]) let searchRequests = [ MultiSearchCollectionParameters(q: "shoe", filterBy: "price:=[50..120]", 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,19 +146,9 @@ final class MultiSearchTests: XCTestCase { } func testMultiSearchWithPreset() async { - 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"), - ]) - - let brandSchema = CollectionSchema(name: "brands", fields: [ - Field(name: "name", type: "string"), - ]) let preset = PresetUpsertSchema( - value: .multiSearch(MultiSearchSearchesParameter( + value: .typeMultiSearchSearchesParameter(MultiSearchSearchesParameter( searches:[ MultiSearchCollectionParameters(q: "shoe", filterBy: "price:=[50..120]", collection: "products"), MultiSearchCollectionParameters(q: "Nike", collection: "brands"), @@ -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(q: "shoe", filterBy: "price:=[50..120]", 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(q: "shoe", filterBy: "price:=[50..120]", 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(q: "Jor", filterBy: "price:=[50..120]", 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/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 deleted file mode 100644 index d24dee9..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 f73018a..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/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/SynonymSetsTests.swift b/Tests/TypesenseTests/SynonymSetsTests.swift new file mode 100644 index 0000000..eac1727 --- /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 client.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 client.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 client.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 client.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 client.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 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") + } + } catch (let error) { + print(error) + XCTAssertTrue(false) + } + } + + func testSynonymSetItemUpsert() async { + do { + 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 + } + 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 client.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 32e8ce5..0000000 --- a/Tests/TypesenseTests/SynonymTests.swift +++ /dev/null @@ -1,146 +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(name: "products", fields: [Field(name: "name", type: "string")])) //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(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 (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(name: "products", fields: [Field(name: "name", type: "string")])) //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(name: "products", fields: [Field(name: "name", type: "string")])) //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(name: "products", fields: [Field(name: "name", type: "string")])) //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 96c5e40..9e7c402 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!) } } @@ -64,13 +64,35 @@ 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 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(name: "companies", 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", _optional: true, facet: true) - ], defaultSortingField: "num_employees", enableNestedFields: true) + ], + defaultSortingField: "num_employees", + enableNestedFields: true) let _ = try await utilClient.collections.create(schema: schema) } @@ -78,19 +100,25 @@ 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( 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) } 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 +127,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")])) ) ) } @@ -114,21 +142,8 @@ 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 - ) - ) - ) -} - 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! } @@ -147,9 +162,17 @@ func createConversationCollection() async throws { 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? + var price: Int var brand: String? var desc: String? @@ -169,4 +192,4 @@ struct Company: Codable { var num_employees: Int var country: String var metadata: [String: Bool]? -} \ No newline at end of file +} diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..48ac23c --- /dev/null +++ b/compose.yml @@ -0,0 +1,9 @@ +services: + typesense: + image: typesense/typesense:30.0.rca34 + 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/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-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..51664c0 --- /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{{#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}} +{{#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({{#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}} + } +{{/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}} +} \ No newline at end of file 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 new file mode 100644 index 0000000..2a16ef0 --- /dev/null +++ b/preprocessed_openapi.yml @@ -0,0 +1,5623 @@ +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: 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 + - name: offset + in: query + schema: + 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: filter_by + in: query + schema: + type: string + example: "num_employees:>100 && country: [USA, UK]" + responses: + '200': + description: The response contains a single field, `num_updated`, indicating + the number of documents affected. + content: + application/json: + schema: + type: object + required: + - num_updated + properties: + num_updated: + type: integer + description: The number of documents that have been updated + example: 1 + '400': + description: 'Bad request, see error message for details' + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: The collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + requestBody: + description: The document fields to be updated + content: + application/json: + schema: + type: object + description: Can be any key-value pair + x-go-type: "interface{}" + required: true + delete: + tags: + - documents + summary: Delete a bunch of documents + description: Delete a bunch of documents that match a specific filter condition. + Use the `batch_size` parameter to control the number of documents that should + deleted at a time. A larger value will speed up deletions, but will impact + performance of other operations running on the server. + operationId: deleteDocuments + parameters: + - name: collectionName + in: path + description: The name of the collection to delete documents from + required: true + schema: + type: string + - name: filter_by + in: query + schema: + type: string + example: "num_employees:>100 && country: [USA, UK]" + - name: batch_size + in: query + schema: + description: Batch size parameter controls the number of documents that + should be deleted at a time. A larger value will speed up deletions, but + will impact performance of other operations running on the server. + type: integer + - name: ignore_not_found + in: query + schema: + type: boolean + - name: truncate + in: query + schema: + description: When true, removes all documents from the collection while + preserving the collection and its schema. + type: boolean + responses: + '200': + description: Documents successfully deleted + content: + application/json: + schema: + type: object + required: + - num_deleted + properties: + num_deleted: + type: integer + '404': + description: Collection not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /collections/{collectionName}/documents/search: + get: + tags: + - documents + summary: Search for documents in a collection + description: Search for documents in a collection that match the search criteria. + operationId: searchCollection + parameters: + - name: collectionName + in: path + description: The name of the collection to search for the document under + required: true + schema: + type: string + - name: q + in: query + schema: + description: The query text to search for in the collection. Use * as the + search string to return all documents. This is typically useful when used + in conjunction with filter_by. + type: string + - name: query_by + in: query + schema: + description: A list of `string` fields that should be queried against. Multiple + fields are separated with a comma. + type: string + - name: nl_query + in: query + schema: + description: Whether to use natural language processing to parse the query. + type: boolean + - name: nl_model_id + in: query + schema: + description: The ID of the natural language model to use. + type: string + - name: query_by_weights + in: query + schema: + description: The relative weight to give each `query_by` field when ranking + results. This can be used to boost fields in priority, when looking for + matches. Multiple fields are separated with a comma. + type: string + - name: text_match_type + in: query + schema: + description: In a multi-field matching context, this parameter determines + how the representative text match score of a record is calculated. Possible + values are max_score (default) or max_weight. + type: string + - name: prefix + in: query + schema: + description: Boolean field to indicate that the last word in the query should + be treated as a prefix, and not as a whole word. This is used for building + autocomplete and instant search interfaces. Defaults to true. + type: string + - name: infix + in: query + schema: + description: If infix index is enabled for this field, infix searching can + be done on a per-field basis by sending a comma separated string parameter + called infix to the search query. This parameter can have 3 values; `off` + infix search is disabled, which is default `always` infix search is performed + along with regular search `fallback` infix search is performed if regular + search does not produce results + type: string + - name: max_extra_prefix + in: query + schema: + description: There are also 2 parameters that allow you to control the extent + of infix searching max_extra_prefix and max_extra_suffix which specify + the maximum number of symbols before or after the query that can be present + in the token. For example query "K2100" has 2 extra symbols in "6PK2100". + By default, any number of prefixes/suffixes can be present for a match. + type: integer + - name: max_extra_suffix + in: query + schema: + description: There are also 2 parameters that allow you to control the extent + of infix searching max_extra_prefix and max_extra_suffix which specify + the maximum number of symbols before or after the query that can be present + in the token. For example query "K2100" has 2 extra symbols in "6PK2100". + By default, any number of prefixes/suffixes can be present for a match. + type: integer + - name: filter_by + in: query + schema: + description: Filter conditions for refining your open api validator search + results. Separate multiple conditions with &&. + type: string + example: "num_employees:>100 && country: [USA, UK]" + - name: max_filter_by_candidates + in: query + schema: + description: Controls the number of similar words that Typesense considers + during fuzzy search on filter_by values. Useful for controlling prefix + matches like company_name:Acm*. + type: integer + - name: sort_by + in: query + schema: + description: A list of numerical fields and their corresponding sort orders + that will be used for ordering your results. Up to 3 sort fields can be + specified. The text similarity score is exposed as a special `_text_match` + field that you can use in the list of sorting fields. If no `sort_by` + parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` + type: string + example: num_employees:desc + - name: facet_by + in: query + schema: + description: A list of fields that will be used for faceting your results + on. Separate multiple fields with a comma. + type: string + - name: max_facet_values + in: query + schema: + description: Maximum number of facet values to be returned. + type: integer + - name: facet_query + in: query + schema: + description: Facet values that are returned can now be filtered via this + parameter. The matching facet text is also highlighted. For example, when + faceting by `category`, you can set `facet_query=category:shoe` to return + only facet values that contain the prefix "shoe". + type: string + - name: num_typos + in: query + schema: + description: > + The number of typographical errors (1 or 2) that would be tolerated. Default: + 2 + type: string + - name: page + in: query + schema: + description: Results from this specific page number would be fetched. + type: integer + - name: per_page + in: query + schema: + description: "Number of results to fetch per page. Default: 10" + type: integer + - name: limit + in: query + schema: + description: > + Number of hits to fetch. Can be used as an alternative to the per_page + parameter. Default: 10. + type: integer + - name: offset + in: query + schema: + description: Identifies the starting point to return hits from a result + set. Can be used as an alternative to the page parameter. + type: integer + - name: group_by + in: query + schema: + description: You can aggregate search results into groups or buckets by + specify one or more `group_by` fields. Separate multiple fields with a + comma. To group on a particular field, it must be a faceted field. + type: string + - name: group_limit + in: query + schema: + description: > + Maximum number of hits to be returned for every group. If the `group_limit` + is set as `K` then only the top K hits in each group are returned in the + response. Default: 3 + type: integer + - name: group_missing_values + in: query + schema: + description: > + Setting this parameter to true will place all documents that have a null + value in the group_by field, into a single group. Setting this parameter + to false, will cause each document with a null value in the group_by field + to not be grouped with other documents. Default: true + type: boolean + - name: include_fields + in: query + schema: + description: List of fields from the document to include in the search result + type: string + - name: exclude_fields + in: query + schema: + description: List of fields from the document to exclude in the search result + type: string + - name: highlight_full_fields + in: query + schema: + description: List of fields which should be highlighted fully without snippeting + type: string + - name: highlight_affix_num_tokens + in: query + schema: + description: > + The number of tokens that should surround the highlighted text on each + side. Default: 4 + type: integer + - name: highlight_start_tag + in: query + schema: + description: > + The start tag used for the highlighted snippets. Default: `` + type: string + - name: highlight_end_tag + in: query + schema: + description: > + The end tag used for the highlighted snippets. Default: `` + type: string + - name: enable_highlight_v1 + in: query + schema: + description: > + Flag for enabling/disabling the deprecated, old highlight structure in + the response. Default: true + type: boolean + default: true + - name: 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 + - 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 + description: > + Set this parameter to false to disable typos on alphanumerical query tokens. + Default: true. + - name: filter_curated_hits + in: query + schema: + type: boolean + description: > + Whether the filter_by condition of the search query should be applicable + to curated results (override definitions, pinned hits, hidden hits, etc.). + Default: false + - name: enable_synonyms + in: query + schema: + type: boolean + description: > + If you have some synonyms defined but want to disable all of them for + a particular search query, set enable_synonyms to false. Default: true + - name: synonym_prefix + in: query + schema: + type: boolean + description: > + Allow synonym resolution on word prefixes in the query. Default: false + - name: synonym_num_typos + in: query + schema: + type: integer + description: > + Allow synonym resolution on typo-corrected words in the query. Default: + 0 + - name: pinned_hits + in: query + schema: + description: > + A list of records to unconditionally include in the search results at + specific positions. An example use case would be to feature or promote + certain items on the top of search results. A list of `record_id:hit_position`. + Eg: to include a record with ID 123 at Position 1 and another record with + ID 456 at Position 5, you'd specify `123:1,456:5`. + + You could also use the Overrides feature to override search results based + on rules. Overrides are applied first, followed by `pinned_hits` and finally + `hidden_hits`. + type: string + - name: hidden_hits + in: query + schema: + description: > + A list of records to unconditionally hide from search results. A list + of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd + specify `123,456`. + + You could also use the Overrides feature to override search results based + on rules. Overrides are applied first, followed by `pinned_hits` and finally + `hidden_hits`. + type: string + - name: override_tags + in: query + schema: + description: Comma separated list of tags to trigger the curations rules + that match the tags. + type: string + - name: highlight_fields + in: query + schema: + description: > + A list of custom fields that must be highlighted even if you don't query + for them + type: string + - name: split_join_tokens + in: query + schema: + description: > + Treat space as typo: search for q=basket ball if q=basketball is not found + or vice-versa. Splitting/joining of tokens will only be attempted if the + original query produces no results. To always trigger this behavior, set + value to `always``. To disable, set value to `off`. Default is `fallback`. + type: string + - name: pre_segmented_query + in: query + schema: + description: > + You can index content from any logographic language into Typesense if + you are able to segment / split the text into space-separated words yourself + before indexing and querying. + + Set this parameter to true to do the same + type: boolean + - name: preset + in: query + schema: + description: > + Search using a bunch of search parameters by setting this parameter to + the name of the existing Preset. + type: string + - name: enable_overrides + in: query + schema: + description: > + If you have some overrides defined but want to disable all of them during + query time, you can do that by setting this parameter to false + type: boolean + default: false + - name: prioritize_exact_match + in: query + schema: + description: > + Set this parameter to true to ensure that an exact match is ranked above + the others + type: boolean + default: true + - name: max_candidates + in: query + schema: + description: > + Control the number of words that Typesense considers for typo and prefix + searching. + type: integer + - name: prioritize_token_position + in: query + schema: + description: > + Make Typesense prioritize documents where the query words appear earlier + in the text. + type: boolean + default: false + - name: prioritize_num_matching_fields + in: query + schema: + description: > + Make Typesense prioritize documents where the query words appear in more + number of fields. + type: boolean + default: true + - name: enable_typos_for_numerical_tokens + in: query + schema: + description: > + Make Typesense disable typos for numerical tokens. + type: boolean + default: true + - name: exhaustive_search + in: query + schema: + description: > + Setting this to true will make Typesense consider all prefixes and typo + corrections of the words in the query without stopping early when enough + results are found (drop_tokens_threshold and typo_tokens_threshold configurations + are ignored). + type: boolean + - name: search_cutoff_ms + in: query + schema: + description: > + Typesense will attempt to return results early if the cutoff time has + elapsed. This is not a strict guarantee and facet computation is not bound + by this parameter. + type: integer + - name: use_cache + in: query + schema: + description: > + Enable server side caching of search query results. By default, caching + is disabled. + type: boolean + - name: cache_ttl + in: query + schema: + description: > + The duration (in seconds) that determines how long the search query is + cached. This value can be set on a per-query basis. Default: 60. + type: integer + - name: min_len_1typo + in: query + schema: + description: > + Minimum word length for 1-typo correction to be applied. The value of + num_typos is still treated as the maximum allowed typos. + type: integer + - name: min_len_2typo + in: query + schema: + description: > + Minimum word length for 2-typo correction to be applied. The value of + num_typos is still treated as the maximum allowed typos. + type: integer + - name: vector_query + in: query + schema: + description: > + Vector query expression for fetching documents "closest" to a given query/document + vector. + type: string + - name: remote_embedding_timeout_ms + in: query + schema: + description: > + Timeout (in milliseconds) for fetching remote embeddings. + type: integer + - name: remote_embedding_num_tries + in: query + schema: + description: > + Number of times to retry fetching remote embeddings. + type: integer + - name: facet_strategy + in: query + schema: + description: > + Choose the underlying faceting strategy used. Comma separated string of + allows values: exhaustive, top_values or automatic (default). + type: string + - name: stopwords + in: query + schema: + description: > + Name of the stopwords set to apply for this search, the keywords present + in the set will be removed from the search query. + type: string + - name: facet_return_parent + in: query + schema: + description: > + Comma separated string of nested facet fields whose parent object should + be returned in facet response. + type: string + - name: voice_query + in: query + schema: + description: > + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + - name: conversation + in: query + schema: + description: > + Enable conversational search. + type: boolean + - name: conversation_model_id + in: query + schema: + description: > + The Id of Conversation Model to be used. + type: string + - name: conversation_id + in: query + schema: + description: > + The Id of a previous conversation to continue, this tells Typesense to + include prior context when communicating with the LLM. + type: string + responses: + '200': + description: Search results + content: + application/json: + schema: + $ref: "#/components/schemas/SearchResult" + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + '404': + description: The collection or field was not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /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: filter_by + in: query + schema: + description: Filter conditions for refining your search results. Separate + multiple conditions with &&. + type: string + - name: include_fields + in: query + schema: + description: List of fields from the document to include in the search result + type: string + - name: exclude_fields + in: query + schema: + description: List of fields from the document to exclude in the search result + type: string + responses: + '200': + description: Exports all the documents in a given collection. + content: + application/octet-stream: + schema: + type: string + example: | + {"id": "124", "company_name": "Stark Industries", "num_employees": 5215, "country": "US"} + {"id": "125", "company_name": "Future Technology", "num_employees": 1232,"country": "UK"} + {"id": "126", "company_name": "Random Corp.", "num_employees": 531,"country": "AU"} + '404': + description: The collection was not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /collections/{collectionName}/documents/import: + post: + tags: + - documents + summary: Import documents into a collection + description: The documents to be imported must be formatted in a newline delimited + JSON structure. You can feed the output file from a Typesense export operation + directly as import. + operationId: importDocuments + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: batch_size + in: query + schema: + type: integer + - name: return_id + in: query + schema: + type: boolean + description: Returning the id of the imported documents. If you want the + import response to return the ingested document's id in the response, + you can use the return_id parameter. + - name: remote_embedding_batch_size + in: query + schema: + type: integer + - name: return_doc + in: query + schema: + type: boolean + - name: action + in: query + schema: + $ref: "#/components/schemas/IndexAction" + - name: dirty_values + in: query + schema: + $ref: "#/components/schemas/DirtyValues" + requestBody: + description: The json array of documents or the JSONL file to import + content: + application/octet-stream: + schema: + type: string + description: The JSONL file to import + required: true + responses: + '200': + description: Result of the import operation. Each line of the response indicates + the result of each document present in the request body (in the same order). + If the import of a single document fails, it does not affect the other + documents. If there is a failure, the response line will include a corresponding + error message and as well as the actual document content. + content: + application/octet-stream: + schema: + type: string + example: | + {"success": true} + {"success": false, "error": "Bad JSON.", "document": "[bad doc"} + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + '404': + description: The collection was not found + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /collections/{collectionName}/documents/{documentId}: + get: + tags: + - documents + summary: 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: q + in: query + schema: + description: The query text to search for in the collection. Use * as the + search string to return all documents. This is typically useful when used + in conjunction with filter_by. + type: string + - name: query_by + in: query + schema: + description: A list of `string` fields that should be queried against. Multiple + fields are separated with a comma. + type: string + - name: query_by_weights + in: query + schema: + description: The relative weight to give each `query_by` field when ranking + results. This can be used to boost fields in priority, when looking for + matches. Multiple fields are separated with a comma. + type: string + - name: text_match_type + in: query + schema: + description: In a multi-field matching context, this parameter determines + how the representative text match score of a record is calculated. Possible + values are max_score (default) or max_weight. + type: string + - name: prefix + in: query + schema: + description: Boolean field to indicate that the last word in the query should + be treated as a prefix, and not as a whole word. This is used for building + autocomplete and instant search interfaces. Defaults to true. + type: string + - name: infix + in: query + schema: + description: If infix index is enabled for this field, infix searching can + be done on a per-field basis by sending a comma separated string parameter + called infix to the search query. This parameter can have 3 values; `off` + infix search is disabled, which is default `always` infix search is performed + along with regular search `fallback` infix search is performed if regular + search does not produce results + type: string + - name: max_extra_prefix + in: query + schema: + description: There are also 2 parameters that allow you to control the extent + of infix searching max_extra_prefix and max_extra_suffix which specify + the maximum number of symbols before or after the query that can be present + in the token. For example query "K2100" has 2 extra symbols in "6PK2100". + By default, any number of prefixes/suffixes can be present for a match. + type: integer + - name: max_extra_suffix + in: query + schema: + description: There are also 2 parameters that allow you to control the extent + of infix searching max_extra_prefix and max_extra_suffix which specify + the maximum number of symbols before or after the query that can be present + in the token. For example query "K2100" has 2 extra symbols in "6PK2100". + By default, any number of prefixes/suffixes can be present for a match. + type: integer + - name: filter_by + in: query + schema: + description: Filter conditions for refining youropen api validator search + results. Separate multiple conditions with &&. + type: string + example: "num_employees:>100 && country: [USA, UK]" + - name: sort_by + in: query + schema: + description: A list of numerical fields and their corresponding sort orders + that will be used for ordering your results. Up to 3 sort fields can be + specified. The text similarity score is exposed as a special `_text_match` + field that you can use in the list of sorting fields. If no `sort_by` + parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` + type: string + - name: facet_by + in: query + schema: + description: A list of fields that will be used for faceting your results + on. Separate multiple fields with a comma. + type: string + - name: max_facet_values + in: query + schema: + description: Maximum number of facet values to be returned. + type: integer + - name: facet_query + in: query + schema: + description: Facet values that are returned can now be filtered via this + parameter. The matching facet text is also highlighted. For example, when + faceting by `category`, you can set `facet_query=category:shoe` to return + only facet values that contain the prefix "shoe". + type: string + - name: num_typos + in: query + schema: + description: > + The number of typographical errors (1 or 2) that would be tolerated. Default: + 2 + type: string + - name: page + in: query + schema: + description: Results from this specific page number would be fetched. + type: integer + - name: per_page + in: query + schema: + description: "Number of results to fetch per page. Default: 10" + type: integer + - name: limit + in: query + schema: + description: > + Number of hits to fetch. Can be used as an alternative to the per_page + parameter. Default: 10. + type: integer + - name: offset + in: query + schema: + description: Identifies the starting point to return hits from a result + set. Can be used as an alternative to the page parameter. + type: integer + - name: group_by + in: query + schema: + description: You can aggregate search results into groups or buckets by + specify one or more `group_by` fields. Separate multiple fields with a + comma. To group on a particular field, it must be a faceted field. + type: string + - name: group_limit + in: query + schema: + description: > + Maximum number of hits to be returned for every group. If the `group_limit` + is set as `K` then only the top K hits in each group are returned in the + response. Default: 3 + type: integer + - name: group_missing_values + in: query + schema: + description: > + Setting this parameter to true will place all documents that have a null + value in the group_by field, into a single group. Setting this parameter + to false, will cause each document with a null value in the group_by field + to not be grouped with other documents. Default: true + type: boolean + - name: include_fields + in: query + schema: + description: List of fields from the document to include in the search result + type: string + - name: exclude_fields + in: query + schema: + description: List of fields from the document to exclude in the search result + type: string + - name: highlight_full_fields + in: query + schema: + description: List of fields which should be highlighted fully without snippeting + type: string + - name: highlight_affix_num_tokens + in: query + schema: + description: > + The number of tokens that should surround the highlighted text on each + side. Default: 4 + type: integer + - name: highlight_start_tag + in: query + schema: + description: > + The start tag used for the highlighted snippets. Default: `` + type: string + - name: highlight_end_tag + in: query + schema: + description: > + The end tag used for the highlighted snippets. Default: `` + type: string + - name: snippet_threshold + in: query + schema: + description: > + Field values under this length will be fully highlighted, instead of showing + a snippet of relevant portion. Default: 30 + type: integer + - name: drop_tokens_threshold + in: query + schema: + description: > + If the number of results found for a specific query is less than this + number, Typesense will attempt to drop the tokens in the query until enough + results are found. Tokens that have the least individual hits are dropped + first. Set to 0 to disable. Default: 10 + type: integer + - name: drop_tokens_mode + in: query + schema: + $ref: "#/components/schemas/DropTokensMode" + - name: typo_tokens_threshold + in: query + schema: + description: > + If the number of results found for a specific query is less than this + number, Typesense will attempt to look for tokens with more typos until + enough results are found. Default: 100 + type: integer + - name: enable_typos_for_alpha_numerical_tokens + in: query + schema: + type: boolean + description: > + Set this parameter to false to disable typos on alphanumerical query tokens. + Default: true. + - name: filter_curated_hits + in: query + schema: + type: boolean + description: > + Whether the filter_by condition of the search query should be applicable + to curated results (override definitions, pinned hits, hidden hits, etc.). + Default: false + - name: enable_synonyms + in: query + schema: + type: boolean + description: > + If you have some synonyms defined but want to disable all of them for + a particular search query, set enable_synonyms to false. Default: true + - name: 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`. + + You could also use the Overrides feature to override search results based + on rules. Overrides are applied first, followed by `pinned_hits` and finally + `hidden_hits`. + type: string + - name: hidden_hits + in: query + schema: + description: > + A list of records to unconditionally hide from search results. A list + of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd + specify `123,456`. + + You could also use the Overrides feature to override search results based + on rules. Overrides are applied first, followed by `pinned_hits` and finally + `hidden_hits`. + type: string + - name: override_tags + in: query + schema: + description: Comma separated list of tags to trigger the curations rules + that match the tags. + type: string + - name: highlight_fields + in: query + schema: + description: > + A list of custom fields that must be highlighted even if you don't query + for them + type: string + - name: pre_segmented_query + in: query + schema: + description: > + You can index content from any logographic language into Typesense if + you are able to segment / split the text into space-separated words yourself + before indexing and querying. + + Set this parameter to true to do the same + type: boolean + default: false + - name: preset + in: query + schema: + description: > + Search using a bunch of search parameters by setting this parameter to + the name of the existing Preset. + type: string + - name: enable_overrides + in: query + schema: + description: > + If you have some overrides defined but want to disable all of them during + query time, you can do that by setting this parameter to false + type: boolean + default: false + - name: prioritize_exact_match + in: query + schema: + description: > + Set this parameter to true to ensure that an exact match is ranked above + the others + type: boolean + default: true + - name: prioritize_token_position + in: query + schema: + description: > + Make Typesense prioritize documents where the query words appear earlier + in the text. + type: boolean + default: false + - name: prioritize_num_matching_fields + in: query + schema: + description: > + Make Typesense prioritize documents where the query words appear in more + number of fields. + type: boolean + default: true + - name: enable_typos_for_numerical_tokens + in: query + schema: + description: > + Make Typesense disable typos for numerical tokens. + type: boolean + default: true + - name: exhaustive_search + in: query + schema: + description: > + Setting this to true will make Typesense consider all prefixes and typo + corrections of the words in the query without stopping early when enough + results are found (drop_tokens_threshold and typo_tokens_threshold configurations + are ignored). + type: boolean + - name: search_cutoff_ms + in: query + schema: + description: > + Typesense will attempt to return results early if the cutoff time has + elapsed. This is not a strict guarantee and facet computation is not bound + by this parameter. + type: integer + - name: use_cache + in: query + schema: + description: > + Enable server side caching of search query results. By default, caching + is disabled. + type: boolean + - name: cache_ttl + in: query + schema: + description: > + The duration (in seconds) that determines how long the search query is + cached. This value can be set on a per-query basis. Default: 60. + type: integer + - name: min_len_1typo + in: query + schema: + description: > + Minimum word length for 1-typo correction to be applied. The value of + num_typos is still treated as the maximum allowed typos. + type: integer + - name: min_len_2typo + in: query + schema: + description: > + Minimum word length for 2-typo correction to be applied. The value of + num_typos is still treated as the maximum allowed typos. + type: integer + - name: vector_query + in: query + schema: + description: > + Vector query expression for fetching documents "closest" to a given query/document + vector. + type: string + - name: remote_embedding_timeout_ms + in: query + schema: + description: > + Timeout (in milliseconds) for fetching remote embeddings. + type: integer + - name: remote_embedding_num_tries + in: query + schema: + description: > + Number of times to retry fetching remote embeddings. + type: integer + - name: facet_strategy + in: query + schema: + description: > + Choose the underlying faceting strategy used. Comma separated string of + allows values: exhaustive, top_values or automatic (default). + type: string + - name: stopwords + in: query + schema: + description: > + Name of the stopwords set to apply for this search, the keywords present + in the set will be removed from the search query. + type: string + - name: facet_return_parent + in: query + schema: + description: > + Comma separated string of nested facet fields whose parent object should + be returned in facet response. + type: string + - name: voice_query + in: query + schema: + description: > + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + - name: conversation + in: query + schema: + description: > + Enable conversational search. + type: boolean + - name: conversation_model_id + in: query + schema: + description: > + The Id of Conversation Model to be used. + type: string + - name: conversation_id + in: query + schema: + description: > + The Id of a previous conversation to continue, this tells Typesense to + include prior context when communicating with the LLM. + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/MultiSearchSearchesParameter" + responses: + '200': + description: Search results + content: + application/json: + schema: + $ref: "#/components/schemas/MultiSearchResult" + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + /analytics/events: + post: + tags: + - analytics + summary: Create an analytics event + description: 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 + 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: > + 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 + drop: + type: boolean + example: true + store: + type: boolean + description: > + When set to false, the field value will not be stored on disk. Default: + true. + vec_dist: + type: string + description: > + The distance metric to be used for vector search. Default: `cosine`. You + can also use `ip` for inner product. + range_index: + type: boolean + description: > + Enables an index optimized for range filtering on numerical fields (e.g. + rating:>3.5). Default: false. + stem: + type: boolean + description: > + Values are stemmed before indexing in-memory. Default: false. + stem_dictionary: + type: string + description: Name of the stemming dictionary to use for this field + example: irregular-plurals + token_separators: + type: array + description: > + List of symbols or special characters to be used for splitting the text + into individual words in addition to space and new-line characters. + items: + type: string + minLength: 1 + maxLength: 1 + default: [] + symbols_to_index: + type: array + description: > + List of symbols or special characters to be indexed. + items: + type: string + minLength: 1 + maxLength: 1 + default: [] + embed: + type: object + required: + - from + - model_config + properties: + from: + type: array + items: + type: string + model_config: + type: object + required: + - model_name + properties: + model_name: + type: string + api_key: + type: string + url: + type: string + access_token: + type: string + refresh_token: + type: string + client_id: + type: string + client_secret: + type: string + project_id: + type: string + indexing_prefix: + type: string + query_prefix: + type: string + VoiceQueryModelCollectionConfig: + type: object + description: > + Configuration for the voice query model + properties: + model_name: + type: string + example: "ts/whisper/base.en" + CollectionAliasSchema: + type: object + required: + - collection_name + properties: + collection_name: + type: string + description: Name of the collection you wish to map the alias to + CollectionAlias: + type: object + required: + - collection_name + - name + properties: + name: + type: string + readOnly: true + description: Name of the collection alias + collection_name: + type: string + description: Name of the collection the alias mapped to + CollectionAliasesResponse: + type: object + required: + - aliases + properties: + aliases: + type: array + x-go-type: "[]*CollectionAlias" + items: + $ref: "#/components/schemas/CollectionAlias" + SearchResult: + type: object + properties: + facet_counts: + type: array + items: + $ref: "#/components/schemas/FacetCounts" + found: + type: integer + description: The number of documents found + found_docs: + type: integer + search_time_ms: + type: integer + description: The number of milliseconds the search took + out_of: + type: integer + description: The total number of documents in the collection + search_cutoff: + type: boolean + description: Whether the search was cut off + page: + type: integer + description: The search result page number + grouped_hits: + type: array + items: + $ref: "#/components/schemas/SearchGroupedHit" + 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 + 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" + 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 + 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 + x-swift-generic-parameter: 'T: Codable' + 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" + 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 + 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 + AnalyticsEventsRetrieveParams: + type: object + properties: + user_id: + type: string + name: + type: string + 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 + include_fields: + description: List of fields from the document to include in the search result + type: string + exclude_fields: + description: List of fields from the document to exclude in the search result + type: string + UpdateDocumentsParameters: + type: object + properties: + filter_by: + type: string + example: "num_employees:>100 && country: [USA, UK]" + DeleteDocumentsParameters: + type: object + required: + - filter_by + properties: + filter_by: + type: string + example: "num_employees:>100 && country: [USA, UK]" + batch_size: + description: Batch size parameter controls the number of documents that + should be deleted at a time. A larger value will speed up deletions, but + will impact performance of other operations running on the server. + type: integer + ignore_not_found: + type: boolean + truncate: + description: When true, removes all documents from the collection while + preserving the collection and its schema. + type: boolean + 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