diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0356dc7..b50ee12 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,26 +1,40 @@ name: CI on: + workflow_dispatch: push: branches: - main + paths-ignore: + - '**/*.md' pull_request: branches: - main + paths-ignore: + - '**/*.md' jobs: tests: - runs-on: "${{ matrix.platform.os }}-latest" + runs-on: '${{ matrix.platform.os }}-latest' strategy: matrix: - platform: [ - { os: "ubuntu", target: "x86_64-unknown-linux-gnu" }, - { os: "ubuntu", target: "wasm32-unknown-unknown" }, - ] - env: - # used to connect to httpmock - URL: "http://localhost:5000" - API_KEY: "VerySecretKey" + platform: + [ + { os: 'ubuntu', target: 'x86_64-unknown-linux-gnu' }, + { os: 'ubuntu', target: 'wasm32-unknown-unknown' }, + ] + services: + typesense: + image: typesense/typesense:30.0.rc10 + ports: + - 8108:8108/tcp + volumes: + - /tmp/typesense-server-data:/data + env: + TYPESENSE_DATA_DIR: '/data' + TYPESENSE_API_KEY: 'xyz' + TYPESENSE_ENABLE_CORS: true + TYPESENSE_URL: 'http://localhost:8108' steps: - uses: actions/checkout@v4 - name: Cache .cargo and target @@ -38,16 +52,9 @@ jobs: target: ${{ matrix.platform.target }} profile: minimal default: true - - name: Install httpmock - uses: actions-rs/cargo@v1 - with: - command: install - args: --features standalone -- httpmock - - name: Run httpmock - run: httpmock --expose --mock-files-dir=./mocks & - name: Install test runner for wasm if: matrix.platform.target == 'wasm32-unknown-unknown' - run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh + run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh - name: Stable Build uses: actions-rs/cargo@v1 with: diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 0527114..f1c26dd 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -1,16 +1,23 @@ name: Lint checks on: + workflow_dispatch: push: - branches: [ main ] + branches: + - main + paths-ignore: + - '**/*.md' pull_request: - branches: [ main ] + branches: + - main + paths-ignore: + - '**/*.md' jobs: lint: runs-on: ubuntu-latest env: - TZ: "/usr/share/zoneinfo/your/location" + TZ: '/usr/share/zoneinfo/your/location' steps: - uses: actions/checkout@v4 - name: Cache .cargo and target @@ -28,11 +35,11 @@ jobs: profile: minimal default: true - run: rustup component add rustfmt - - name: Check formt + - name: Check format uses: actions-rs/cargo@v1 with: command: fmt - args: --all -- --check + args: -- --check - run: rustup component add clippy - name: Run clippy uses: actions-rs/cargo@v1 diff --git a/Cargo.toml b/Cargo.toml index 23adab9..36c1189 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,20 @@ repository = "https://github.com/typesense/typesense-rust" authors = ["Typesense "] [workspace.dependencies] - -typesense_derive = { path = "./typesense_derive", version = "0.3.0" } -typesense_codegen = { path = "./typesense_codegen", version = "0.25.0" } \ No newline at end of file +typesense_codegen = { path = "./typesense_codegen", version = "0.25" } +typesense_derive = { path = "./typesense_derive", version = "0.3" } +anyhow = "1" +base64 = "0.22" +bon = "3" +clap = { version = "4", features = ["derive"] } +debug_unsafe = "0.1" +hmac = "0.12" +reqwest-retry = "0.7" +serde = { version = "1", features = ["derive"] } +serde_json = "1.0" +serde_repr = "0.1" +serde_yaml = "0.9" +sha2 = "0.10" +thiserror = "2" +url = "2" +web-time = "=1.1.0" diff --git a/README.md b/README.md index f99ccab..625f55c 100644 --- a/README.md +++ b/README.md @@ -5,14 +5,40 @@ Rust client library for Typesense | Work In Progress & Help Wanted! -OpenAPI codegen folder was generated with: +### Development + +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 (you can also run tasks individually): + +```bash +cargo xtask fetch code-gen +``` + +This will: + +- Download the latest API spec. +- Write it to our local [`openapi.yml`](./openapi.yml). +- Preprocess it into [`preprocessed_openapi.yml`](./preprocessed_openapi.yml). +- Regenerate the `/typesense_codegen` crate. + +The preprocessing step does two things: + +- Flatten the URL params defined as objects into individual URL parameters (in [`preprocess_openapi.rs`](xtask/src/preprocess_openapi.rs)) +- Inject OpenAPI vendor attributes (e.g., generic parameters, schema builders) into the spec before code generation (in [`add_vendor_attributes.rs`](./xtask/src/add_vendor_attributes.rs)) + +You can also run `code-gen` directly through Docker: ``` docker run --rm \ -v $PWD:/local openapitools/openapi-generator-cli generate \ - -i /local/openapi.yml \ + -i /local/preprocessed_openapi.yml \ -g rust \ - -o /local/typesense_codegen_new + -o /local/typesense_codegen \ + -t /local/openapi-generator-template \ + --additional-properties library=reqwest \ + --additional-properties supportMiddleware=true \ + --additional-properties useSingleRequestParameter=true ``` -If you'd like to contribute, please join our [Slack Community](https://join.slack.com/t/typesense-community/shared_invite/zt-mx4nbsbn-AuOL89O7iBtvkz136egSJg) and say hello! +If you'd like to contribute, please join our [Slack Community](https://join.slack.com/t/typesense-community/shared_invite/zt-mx4nbsbn-AuOL89O7iBtvkz136egSJg) and say hello! diff --git a/compose.yml b/compose.yml index c77de65..ad85db6 100644 --- a/compose.yml +++ b/compose.yml @@ -1,6 +1,6 @@ services: typesense: - image: typesense/typesense:29.0 + image: typesense/typesense:30.0.rc10 restart: on-failure ports: - '8108:8108' diff --git a/mocks/create_collection.yaml b/mocks/create_collection.yaml deleted file mode 100644 index a2168e6..0000000 --- a/mocks/create_collection.yaml +++ /dev/null @@ -1,24 +0,0 @@ -when: - method: POST - path: /collections - header: - - name: X-TYPESENSE-API-KEY - value: VerySecretKey - body: '{"name":"companies","fields":[{"name":"company_name","type":"string"},{"name":"num_employees","type":"int32"},{"name":"country","type":"string","facet":true}],"default_sorting_field":"num_employees"}' -then: - status: 200 - header: - - name: content-type - value: text/json - body: ' - { - "name": "companies", - "num_documents": 0, - "fields": [ - {"name": "company_name", "type": "string" }, - {"name": "num_employees", "type": "int32" }, - {"name": "country", "type": "string", "facet": true } - ], - "default_sorting_field": "num_employees", - "created_at": 1 - }' diff --git a/mocks/drop_collection.yaml b/mocks/drop_collection.yaml deleted file mode 100644 index 26c3655..0000000 --- a/mocks/drop_collection.yaml +++ /dev/null @@ -1,23 +0,0 @@ -when: - method: DELETE - path: /collections/companies - header: - - name: X-TYPESENSE-API-KEY - value: VerySecretKey -then: - status: 200 - header: - - name: content-type - value: text/json - body: ' - { - "name": "companies", - "num_documents": 1200, - "fields": [ - {"name": "company_name", "type": "string" }, - {"name": "num_employees", "type": "int32" }, - {"name": "country", "type": "string", "facet": true } - ], - "default_sorting_field": "num_employees", - "created_at": 1 - }' diff --git a/mocks/import_documents.yaml b/mocks/import_documents.yaml deleted file mode 100644 index e7469b7..0000000 --- a/mocks/import_documents.yaml +++ /dev/null @@ -1,13 +0,0 @@ -when: - method: POST - path: /collections/companies/documents/import - header: - - name: X-TYPESENSE-API-KEY - value: VerySecretKey - body: "{\"company_name\":\"test\",\"num_employees\":1,\"country\":\"c1\"}\n{\"company_name\":\"test2\",\"num_employees\":2,\"country\":\"c2\"}" -then: - status: 200 - header: - - name: content-type - value: application/text - body: "{\"success\":true}\n{\"success\":true}" diff --git a/mocks/retrieve_all_collections.yaml b/mocks/retrieve_all_collections.yaml deleted file mode 100644 index ccaaa50..0000000 --- a/mocks/retrieve_all_collections.yaml +++ /dev/null @@ -1,34 +0,0 @@ -when: - method: GET - path: /collections - header: - - name: X-TYPESENSE-API-KEY - value: VerySecretKey -then: - status: 200 - header: - - name: content-type - value: text/json - body: ' - [{ - "num_documents": 1250, - "name": "companies", - "fields": [ - {"name": "company_name", "type": "string"}, - {"name": "num_employees", "type": "int32"}, - {"name": "country", "type": "string", "facet": true} - ], - "default_sorting_field": "num_employees", - "created_at": 1 - }, - { - "num_documents": 1250, - "name": "ceos", - "fields": [ - {"name": "company_name", "type": "string"}, - {"name": "full_name", "type": "string"}, - {"name": "from_year", "type": "int32"} - ], - "default_sorting_field": "num_employees", - "created_at": 1 - }]' diff --git a/mocks/retrieve_collection.yaml b/mocks/retrieve_collection.yaml deleted file mode 100644 index ff4d743..0000000 --- a/mocks/retrieve_collection.yaml +++ /dev/null @@ -1,23 +0,0 @@ -when: - method: GET - path: /collections/companies - header: - - name: X-TYPESENSE-API-KEY - value: VerySecretKey -then: - status: 200 - header: - - name: content-type - value: text/json - body: ' - { - "name": "companies", - "num_documents": 1250, - "fields": [ - {"name": "company_name", "type": "string" }, - {"name": "num_employees", "type": "int32" }, - {"name": "country", "type": "string", "facet": true } - ], - "default_sorting_field": "num_employees", - "created_at": 1 - }' diff --git a/mocks/search_collection.yaml b/mocks/search_collection.yaml deleted file mode 100644 index 1c5f294..0000000 --- a/mocks/search_collection.yaml +++ /dev/null @@ -1,17 +0,0 @@ -when: - method: GET - path: /collections/companies/documents/search - header: - - name: X-TYPESENSE-API-KEY - value: VerySecretKey - query_param: - - name: q - value: test - - name: query_by - value: company_name -then: - status: 200 - header: - - name: content-type - value: application/text - body: "{\"facet_counts\":[],\"found\":2,\"hits\":[{\"document\":{\"company_name\":\"test\",\"country\":\"c1\",\"id\":\"0\",\"num_employees\":1},\"highlight\":{\"company_name\":{\"matched_tokens\":[\"test\"],\"snippet\":\"test\"}},\"highlights\":[{\"field\":\"company_name\",\"matched_tokens\":[\"test\"],\"snippet\":\"test\"}],\"text_match\":578730123365711993,\"text_match_info\":{\"best_field_score\":\"1108091339008\",\"best_field_weight\":15,\"fields_matched\":1,\"score\":\"578730123365711993\",\"tokens_matched\":1}},{\"document\":{\"company_name\":\"test2\",\"country\":\"c2\",\"id\":\"1\",\"num_employees\":2},\"highlight\":{\"company_name\":{\"matched_tokens\":[\"test\"],\"snippet\":\"test2\"}},\"highlights\":[{\"field\":\"company_name\",\"matched_tokens\":[\"test\"],\"snippet\":\"test2\"}],\"text_match\":578730089005449337,\"text_match_info\":{\"best_field_score\":\"1108074561536\",\"best_field_weight\":15,\"fields_matched\":1,\"score\":\"578730089005449337\",\"tokens_matched\":1}}],\"out_of\":2,\"page\":1,\"request_params\":{\"collection_name\":\"companies\",\"per_page\":10,\"q\":\"test\"},\"search_cutoff\":false,\"search_time_ms\":0}" diff --git a/openapi-generator-template/README.mustache b/openapi-generator-template/README.mustache new file mode 100644 index 0000000..0e8bfb3 --- /dev/null +++ b/openapi-generator-template/README.mustache @@ -0,0 +1,54 @@ +# Rust API client for {{{packageName}}} + +{{#appDescriptionWithNewLines}} +{{{.}}} +{{/appDescriptionWithNewLines}} + +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Overview + +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client. + +- API version: {{{appVersion}}} +- Package version: {{{packageVersion}}} +{{^hideGenerationTimestamp}} +- Build date: {{{generatedDate}}} +{{/hideGenerationTimestamp}} +- Generator version: {{generatorVersion}} +- Build package: `{{{generatorClass}}}` + +## Installation + +Put the package under your project folder in a directory named `{{packageName}}` and add the following to `Cargo.toml` under `[dependencies]`: + +``` +{{{packageName}}} = { path = "./{{{packageName}}}" } +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{{classname}}}* | [**{{{operationId}}}**]({{{apiDocPath}}}{{classname}}.md#{{{operationIdLowerCase}}}) | **{{{httpMethod}}}** {{{path}}} | {{{summary}}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation For Models + +{{#models}}{{#model}} - [{{{classname}}}]({{{modelDocPath}}}{{{classname}}}.md) +{{/model}}{{/models}} + +To get access to the crate's generated documentation, use: + +``` +cargo doc --open +``` + +## Author + +{{#apiInfo}}{{#apis}}{{#-last}}{{{infoEmail}}} +{{/-last}}{{/apis}}{{/apiInfo}} diff --git a/openapi-generator-template/api_doc.mustache b/openapi-generator-template/api_doc.mustache new file mode 100644 index 0000000..f8ea520 --- /dev/null +++ b/openapi-generator-template/api_doc.mustache @@ -0,0 +1,47 @@ +# {{{invokerPackage}}}\{{{classname}}}{{#description}} + +{{{.}}}{{/description}} + +All URIs are relative to *{{{basePath}}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{{operationId}}}**]({{{classname}}}.md#{{{operationId}}}) | **{{{httpMethod}}}** {{{path}}} | {{{summary}}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +## {{{operationId}}} + +> {{#returnType}}{{{.}}} {{/returnType}}{{{operationId}}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) +{{{summary}}}{{#notes}} + +{{{.}}}{{/notes}} + +### Parameters + +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} +**{{{paramName}}}** | {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{{baseType}}}.md){{/isPrimitiveType}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}} | {{{description}}} | {{#required}}[required]{{/required}} |{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{{returnBaseType}}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + +- **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} +- **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/openapi-generator-template/lib.mustache b/openapi-generator-template/lib.mustache new file mode 100644 index 0000000..d9c227b --- /dev/null +++ b/openapi-generator-template/lib.mustache @@ -0,0 +1,7 @@ +#![allow(unused_imports)] +#![allow(clippy::empty_docs)] +#![allow(clippy::needless_return)] +#![allow(elided_lifetimes_in_paths)] + +pub mod apis; +pub mod models; diff --git a/openapi-generator-template/model.mustache b/openapi-generator-template/model.mustache new file mode 100644 index 0000000..627362a --- /dev/null +++ b/openapi-generator-template/model.mustache @@ -0,0 +1,241 @@ +{{>partial_header}} +use crate::models; +use serde::{Deserialize, Serialize}; +{{#models}} +{{#model}} +{{^isEnum}}{{#vendorExtensions.x-rust-has-byte-array}} +use serde_with::serde_as; +{{/vendorExtensions.x-rust-has-byte-array}}{{/isEnum}} +{{#isEnum}} +{{#isInteger}} +use serde_repr::{Serialize_repr,Deserialize_repr}; +{{/isInteger}} +{{/isEnum}} +{{#description}} +/// {{{classname}}} : {{{description}}} +{{/description}} +{{!-- for repr(int) enum schemas --}} +{{#isEnum}} +{{#isInteger}} +/// {{{description}}} +#[repr(i64)] +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize_repr, Deserialize_repr)] +pub enum {{{classname}}} { +{{#allowableValues}} +{{#enumVars}} + {{{name}}} = {{{value}}}, +{{/enumVars}}{{/allowableValues}} +} + +impl std::fmt::Display for {{{classname}}} { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", match self { + {{#allowableValues}} + {{#enumVars}} + Self::{{{name}}} => "{{{value}}}", + {{/enumVars}} + {{/allowableValues}} + }) + } +} +{{/isInteger}} +{{/isEnum}} +{{!-- for enum schemas --}} +{{#isEnum}} +{{^isInteger}} +/// {{{description}}} +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum {{{classname}}} { +{{#allowableValues}} +{{#enumVars}} + #[serde(rename = "{{{value}}}")] + {{{name}}}, +{{/enumVars}}{{/allowableValues}} +} + +impl std::fmt::Display for {{{classname}}} { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + {{#allowableValues}} + {{#enumVars}} + Self::{{{name}}} => write!(f, "{{{value}}}"), + {{/enumVars}} + {{/allowableValues}} + } + } +} + +{{/isInteger}} +impl Default for {{{classname}}} { + fn default() -> {{{classname}}} { + {{#allowableValues}} + Self::{{ enumVars.0.name }} + {{/allowableValues}} + } +} +{{/isEnum}} +{{!-- for schemas that have a discriminator --}} +{{#discriminator}} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "{{{propertyBaseName}}}")] +pub enum {{{classname}}} { + {{^oneOf}} + {{#mappedModels}} + #[serde(rename="{{mappingName}}")] + {{{modelName}}} { + {{#vars}} + {{#description}} + /// {{{.}}} + {{/description}} + #[serde(rename = "{{{baseName}}}"{{^required}}, skip_serializing_if = "Option::is_none"{{/required}})] + {{{name}}}: {{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{^required}}Option<{{/required}}{{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{#isModel}}{{^avoidBoxedModels}}Box<{{/avoidBoxedModels}}{{{dataType}}}{{^avoidBoxedModels}}>{{/avoidBoxedModels}}{{/isModel}}{{^isModel}}{{{dataType}}}{{/isModel}}{{/isEnum}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^required}}>{{/required}}, + {{/vars}} + }, + {{/mappedModels}} + {{/oneOf}} + {{^oneOf.isEmpty}} + {{#composedSchemas.oneOf}} + {{#description}} + /// {{{.}}} + {{/description}} + {{#baseName}} + #[serde(rename="{{{.}}}")] + {{/baseName}} + {{{name}}}({{#isModel}}{{^avoidBoxedModels}}Box<{{/avoidBoxedModels}}{{/isModel}}{{{dataType}}}{{#isModel}}{{^avoidBoxedModels}}>{{/avoidBoxedModels}}{{/isModel}}), + {{/composedSchemas.oneOf}} + {{/oneOf.isEmpty}} +} + +impl Default for {{classname}} { + fn default() -> Self { + {{^oneOf}}{{#mappedModels}}{{#-first}}Self::{{modelName}} { + {{#vars}} + {{{name}}}: Default::default(), + {{/vars}} + }{{/-first}}{{/mappedModels}} + {{/oneOf}}{{^oneOf.isEmpty}}{{#composedSchemas.oneOf}}{{#-first}}Self::{{{name}}}(Default::default()){{/-first}}{{/composedSchemas.oneOf}}{{/oneOf.isEmpty}} + } +} + +{{/discriminator}} +{{!-- for non-enum schemas --}} +{{^isEnum}} +{{^discriminator}} +{{#vendorExtensions.x-rust-builder}} +#[derive(bon::Builder)] +#[builder(on(String, into))] +{{/vendorExtensions.x-rust-builder}} +{{#vendorExtensions.x-rust-has-byte-array}}#[serde_as] +{{/vendorExtensions.x-rust-has-byte-array}}{{#oneOf.isEmpty}}#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct {{{classname}}}{{{vendorExtensions.x-rust-generic-parameter}}} { +{{#vars}} + {{#description}} + /// {{{.}}} + {{/description}} + {{#isByteArray}} + {{#vendorExtensions.isMandatory}}#[serde_as(as = "serde_with::base64::Base64")]{{/vendorExtensions.isMandatory}}{{^vendorExtensions.isMandatory}}#[serde_as(as = "{{^serdeAsDoubleOption}}Option{{/serdeAsDoubleOption}}{{#serdeAsDoubleOption}}super::DoubleOption{{/serdeAsDoubleOption}}")]{{/vendorExtensions.isMandatory}} + {{/isByteArray}} + #[serde(rename = "{{{baseName}}}"{{^required}}{{#isNullable}}, default{{^isByteArray}}, with = "::serde_with::rust::double_option"{{/isByteArray}}{{/isNullable}}{{/required}}{{^required}}, skip_serializing_if = "Option::is_none"{{/required}}{{#required}}{{#isNullable}}, deserialize_with = "Option::deserialize"{{/isNullable}}{{/required}})] + {{#vendorExtensions.x-rust-type}} + pub {{{name}}}: {{{.}}}, + {{/vendorExtensions.x-rust-type}} + {{^vendorExtensions.x-rust-type}} + pub {{{name}}}: {{! + ### Option Start + }}{{#isNullable}}Option<{{/isNullable}}{{^required}}Option<{{/required}}{{! + ### Enums + }}{{#isEnum}}{{#isArray}}{{#uniqueItems}}std::collections::HashSet<{{/uniqueItems}}{{^uniqueItems}}Vec<{{/uniqueItems}}{{/isArray}}{{{enumName}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{! + ### Non-Enums Start + }}{{^isEnum}}{{! + ### Models + }}{{#isModel}}{{^avoidBoxedModels}}Box<{{/avoidBoxedModels}}{{{dataType}}}{{^avoidBoxedModels}}>{{/avoidBoxedModels}}{{/isModel}}{{! + ### Primative datatypes + }}{{^isModel}}{{#isByteArray}}Vec{{/isByteArray}}{{^isByteArray}}{{{dataType}}}{{/isByteArray}}{{/isModel}}{{! + ### Non-Enums End + }}{{/isEnum}}{{! + ### Option End (and trailing comma) + }}{{#isNullable}}>{{/isNullable}}{{^required}}>{{/required}}, + {{/vendorExtensions.x-rust-type}} +{{/vars}} +} + +impl{{{vendorExtensions.x-rust-generic-parameter}}} {{{classname}}}{{{vendorExtensions.x-rust-generic-parameter}}} { + {{#description}} + /// {{{.}}} + {{/description}} + pub fn new({{#requiredVars}}{{{name}}}: {{! + ### CHANGE 1: If x-rust-type is available for a required var, use it for the parameter type. + }}{{#vendorExtensions.x-rust-type}}{{{.}}}{{/vendorExtensions.x-rust-type}}{{! + ### Fallback to original logic if x-rust-type is not present. + }}{{^vendorExtensions.x-rust-type}}{{#isNullable}}Option<{{/isNullable}}{{#isEnum}}{{#isArray}}{{#uniqueItems}}std::collections::HashSet<{{/uniqueItems}}{{^uniqueItems}}Vec<{{/uniqueItems}}{{/isArray}}{{{enumName}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{#isByteArray}}Vec{{/isByteArray}}{{^isByteArray}}{{{dataType}}}{{/isByteArray}}{{/isEnum}}{{#isNullable}}>{{/isNullable}}{{/vendorExtensions.x-rust-type}}{{! + ### Comma for next arguement + }}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{{classname}}}{{{vendorExtensions.x-rust-generic-parameter}}}{ + {{{classname}}} { + {{#vars}} + {{#vendorExtensions.x-rust-type}} + {{! Differentiate between required and optional fields with x-rust-type.}} + {{#required}} + {{{name}}}, + {{/required}} + {{^required}} + {{{name}}}: None, + {{/required}} + {{/vendorExtensions.x-rust-type}} + {{^vendorExtensions.x-rust-type}} + {{{name}}}{{^required}}: None{{/required}}{{#required}}{{#isModel}}{{^avoidBoxedModels}}: {{^isNullable}}Box::new({{{name}}}){{/isNullable}}{{#isNullable}}if let Some(x) = {{{name}}} {Some(Box::new(x))} else {None}{{/isNullable}}{{/avoidBoxedModels}}{{/isModel}}{{/required}}, + {{/vendorExtensions.x-rust-type}} + {{/vars}} + } + } +} +{{/oneOf.isEmpty}} +{{^oneOf.isEmpty}} +{{! TODO: add other vars that are not part of the oneOf}} +{{#description}} +/// {{{.}}} +{{/description}} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum {{classname}} { +{{#composedSchemas.oneOf}} + {{#description}} + /// {{{.}}} + {{/description}} + {{{name}}}({{#isModel}}{{^avoidBoxedModels}}Box<{{/avoidBoxedModels}}{{/isModel}}{{{dataType}}}{{#isModel}}{{^avoidBoxedModels}}>{{/avoidBoxedModels}}{{/isModel}}), +{{/composedSchemas.oneOf}} +} + +impl Default for {{classname}} { + fn default() -> Self { + {{#composedSchemas.oneOf}}{{#-first}}Self::{{{name}}}(Default::default()){{/-first}}{{/composedSchemas.oneOf}} + } +} +{{/oneOf.isEmpty}} +{{/discriminator}} +{{/isEnum}} +{{!-- for properties that are of enum type --}} +{{#vars}} +{{#isEnum}} +/// {{{description}}} +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum {{{enumName}}} { +{{#allowableValues}} +{{#enumVars}} + #[serde(rename = "{{{value}}}")] + {{{name}}}, +{{/enumVars}} +{{/allowableValues}} +} + +impl Default for {{{enumName}}} { + fn default() -> {{{enumName}}} { + {{#allowableValues}} + Self::{{ enumVars.0.name }} + {{/allowableValues}} + } +} +{{/isEnum}} +{{/vars}} + +{{/model}} +{{/models}} diff --git a/openapi-generator-template/model_doc.mustache b/openapi-generator-template/model_doc.mustache new file mode 100644 index 0000000..2aba759 --- /dev/null +++ b/openapi-generator-template/model_doc.mustache @@ -0,0 +1,54 @@ +{{#models}}{{#model}}# {{{classname}}} +{{#isEnum}} + +## Enum Variants + +| Name | Value | +|---- | -----|{{#allowableValues}}{{#enumVars}} +| {{name}} | {{value}} |{{/enumVars}}{{/allowableValues}} + +{{/isEnum}} +{{#discriminator}} + +## Enum Variants + +| Name | Value | +|---- | -----|{{#vendorExtensions}}{{#x-mapped-models}} +| {{modelName}} | {{mappingName}} |{{/x-mapped-models}}{{/vendorExtensions}} +{{#vendorExtensions}} +{{#x-mapped-models}} + +## {{modelName}} + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{{name}}}** | {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{{complexType}}}.md){{/isPrimitiveType}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}} | {{{description}}} | {{^required}}[optional]{{/required}}{{#isReadOnly}}[readonly]{{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} +{{/x-mapped-models}} +{{/vendorExtensions}} +{{/discriminator}} +{{^discriminator}} +{{^isEnum}} +{{#oneOf.isEmpty}} + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{{name}}}** | {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{{complexType}}}.md){{/isPrimitiveType}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}} | {{{description}}} | {{^required}}[optional]{{/required}}{{#isReadOnly}}[readonly]{{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} +{{/oneOf.isEmpty}} +{{^oneOf.isEmpty}} + +## Enum Variants + +| Name | Description | +|---- | -----|{{#oneOf}} +| {{{.}}} | {{description}} |{{/oneOf}} +{{/oneOf.isEmpty}} +{{/isEnum}} +{{/discriminator}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}}{{/models}} diff --git a/openapi-generator-template/model_mod.mustache b/openapi-generator-template/model_mod.mustache new file mode 100644 index 0000000..bdb080f --- /dev/null +++ b/openapi-generator-template/model_mod.mustache @@ -0,0 +1,45 @@ +{{#models}} +{{#model}} +pub mod {{{classFilename}}}; +pub use self::{{{classFilename}}}::{{{classname}}}; +{{/model}} +{{/models}} +{{#serdeAsDoubleOption}} +use serde::{Deserialize, Deserializer, Serializer}; +use serde_with::{de::DeserializeAsWrap, ser::SerializeAsWrap, DeserializeAs, SerializeAs}; +use std::marker::PhantomData; + +pub(crate) struct DoubleOption(PhantomData); + +impl SerializeAs>> for DoubleOption +where + TAs: SerializeAs, +{ + fn serialize_as(values: &Option>, serializer: S) -> Result + where + S: Serializer, + { + match values { + None => serializer.serialize_unit(), + Some(None) => serializer.serialize_none(), + Some(Some(v)) => serializer.serialize_some(&SerializeAsWrap::::new(v)), + } + } +} + +impl<'de, T, TAs> DeserializeAs<'de, Option>> for DoubleOption +where + TAs: DeserializeAs<'de, T>, + T: std::fmt::Debug, +{ + fn deserialize_as(deserializer: D) -> Result>, D::Error> + where + D: Deserializer<'de>, + { + Ok(Some( + DeserializeAsWrap::, Option>::deserialize(deserializer)? + .into_inner(), + )) + } +} +{{/serdeAsDoubleOption}} \ No newline at end of file diff --git a/openapi-generator-template/partial_header.mustache b/openapi-generator-template/partial_header.mustache new file mode 100644 index 0000000..408d841 --- /dev/null +++ b/openapi-generator-template/partial_header.mustache @@ -0,0 +1,13 @@ +/* + {{#appName}} + * {{{.}}} + * + {{/appName}} + {{#appDescription}} + * {{{.}}} + * + {{/appDescription}} + * {{#version}}The version of the OpenAPI document: {{{.}}}{{/version}} + * {{#infoEmail}}Contact: {{{.}}}{{/infoEmail}} + * Generated by: https://openapi-generator.tech + */ diff --git a/openapi-generator-template/reqwest/api.mustache b/openapi-generator-template/reqwest/api.mustache new file mode 100644 index 0000000..e56af93 --- /dev/null +++ b/openapi-generator-template/reqwest/api.mustache @@ -0,0 +1,516 @@ +{{>partial_header}} + +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; +use crate::{apis::ResponseContent, models}; +use super::{Error, configuration, ContentType}; + +{{#operations}} +{{#operation}} +{{#vendorExtensions.x-group-parameters}} +{{#allParams}} +{{#-first}} +/// struct for passing parameters to the method [`{{operationId}}`] +#[derive(Clone, Debug)] +pub struct {{{operationIdCamelCase}}}Params { +{{/-first}} + {{#description}} + /// {{{.}}} + {{/description}} + pub {{{paramName}}}: {{! + ### Option Start + }}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! + ### &str and Vec<&str> + }}{{^isUuid}}{{#isString}}{{#isArray}}Vec<{{/isArray}}String{{#isArray}}>{{/isArray}}{{/isString}}{{/isUuid}}{{! + ### UUIDs + }}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}String{{#isArray}}>{{/isArray}}{{/isUuid}}{{! + ### Models and primative types + }}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{! + ### Option End + }}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{! + ### Comma for next arguement + }}{{^-last}},{{/-last}} +{{#-last}} +} + +{{/-last}} +{{/allParams}} +{{/vendorExtensions.x-group-parameters}} +{{/operation}} +{{/operations}} + +{{#supportMultipleResponses}} +{{#operations}} +{{#operation}} +/// struct for typed successes of method [`{{operationId}}`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum {{{operationIdCamelCase}}}Success { + {{#responses}} + {{#is2xx}} + Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/is2xx}} + {{#is3xx}} + Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/is3xx}} + {{/responses}} + UnknownValue(serde_json::Value), +} + +{{/operation}} +{{/operations}} +{{/supportMultipleResponses}} +{{#operations}} +{{#operation}} +/// struct for typed errors of method [`{{operationId}}`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum {{{operationIdCamelCase}}}Error { + {{#responses}} + {{#is4xx}} + Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/is4xx}} + {{#is5xx}} + Status{{code}}({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/is5xx}} + {{#isDefault}} + DefaultResponse({{#isEnum}}{{{enumName}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}), + {{/isDefault}} + {{/responses}} + UnknownValue(serde_json::Value), +} + +{{/operation}} +{{/operations}} + +{{#operations}} +{{#operation}} +{{#description}} +/// {{{.}}} +{{/description}} +{{#notes}} +/// {{{.}}} +{{/notes}} +{{#vendorExtensions.x-group-parameters}} +pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensions.x-rust-generic-parameter}}}(configuration: &configuration::Configuration{{#allParams}}{{#-first}}, {{! +### Params +}}params: &{{{operationIdCamelCase}}}Params{{/-first}}{{/allParams}}{{! +### Function return type +}}) -> Result<{{#vendorExtensions.x-rust-return-type}}{{{.}}}{{/vendorExtensions.x-rust-return-type}}{{^vendorExtensions.x-rust-return-type}}{{#isResponseFile}}{{#supportAsync}}reqwest::Response{{/supportAsync}}{{^supportAsync}}reqwest::blocking::Response{{/supportAsync}}{{/isResponseFile}}{{^isResponseFile}}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{/vendorExtensions.x-rust-return-type}}, Error<{{{operationIdCamelCase}}}Error>> { +{{/vendorExtensions.x-group-parameters}} +{{^vendorExtensions.x-group-parameters}} +pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}{{{vendorExtensions.x-rust-generic-parameter}}}(configuration: &configuration::Configuration, {{#allParams}}{{{paramName}}}: {{! +### Option Start +}}{{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{! +### &str and Vec<&str> +}}{{#isString}}{{#isArray}}Vec<{{/isArray}}{{^isUuid}}&str{{/isUuid}}{{#isArray}}>{{/isArray}}{{/isString}}{{! +### UUIDs +}}{{#isUuid}}{{#isArray}}Vec<{{/isArray}}&str{{#isArray}}>{{/isArray}}{{/isUuid}}{{! +### Models and primative types +}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{! +### Option End +}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{! +### Comma for next arguement +}}{{^-last}}, {{/-last}}{{/allParams}}{{! +### Function return type +}}) -> Result<{{#vendorExtensions.x-rust-return-type}}{{{vendorExtensions.x-rust-return-type}}}{{/vendorExtensions.x-rust-return-type}}{{^vendorExtensions.x-rust-return-type}}{{! +### Response File Support +}}{{#isResponseFile}}{{#supportAsync}}reqwest::Response{{/supportAsync}}{{^supportAsync}}reqwest::blocking::Response{{/supportAsync}}{{/isResponseFile}}{{! +### Regular Responses +}}{{^isResponseFile}}{{! +### Multi response support +}}{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{! +### Regular return type +}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{{returnType}}}{{{vendorExtensions.x-rust-return-type-generic-parameter}}}{{/supportMultipleResponses}}{{/isResponseFile}}{{/vendorExtensions.x-rust-return-type}}{{! +### Error Type +}}, Error<{{{operationIdCamelCase}}}Error>> { + {{#allParams.0}} + // add a prefix to parameters to efficiently prevent name collisions + {{/allParams.0}} + {{#allParams}} + let {{{vendorExtensions.x-rust-param-identifier}}} = {{{paramName}}}; + {{/allParams}} +{{/vendorExtensions.x-group-parameters}} + + let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode(&{{/isString}}{{{vendorExtensions.x-rust-param-identifier}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isArray}}.join(",").as_ref(){{/isArray}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}.to_string(){{/isContainer}}{{/isPrimitiveType}}{{/isUuid}}{{/isString}}{{#isString}}){{/isString}}{{/pathParams}}); + let mut req_builder = configuration.client.request(reqwest::Method::{{{httpMethod}}}, &uri_str); + + {{#queryParams}} + {{#required}} + {{#isArray}} + req_builder = match "{{collectionFormat}}" { + "multi" => req_builder.query(&{{{vendorExtensions.x-rust-param-identifier}}}.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::>()), + _ => req_builder.query(&[("{{{baseName}}}", &{{{vendorExtensions.x-rust-param-identifier}}}.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]), + }; + {{/isArray}} + {{^isArray}} + {{^isNullable}} + req_builder = req_builder.query(&[("{{{baseName}}}", &{{{vendorExtensions.x-rust-param-identifier}}}.to_string())]); + {{/isNullable}} + {{#isNullable}} + {{#isDeepObject}} + if let Some(ref param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + {{^isExplode}} + let params = crate::apis::parse_deep_object("{{{baseName}}}", &serde_json::to_value(param_value)?); + req_builder = req_builder.query(¶ms); + {{/isExplode}} + {{#isExplode}} + {{#isModel}} + req_builder = req_builder.query(¶m_value); + {{/isModel}} + {{#isMap}} + let mut query_params = Vec::with_capacity(param_value.len()); + for (key, value) in param_value.iter() { + query_params.push((key.to_string(), serde_json::to_string(value)?)); + } + req_builder = req_builder.query(&query_params); + {{/isMap}} + {{/isExplode}} + }; + {{/isDeepObject}} + {{^isDeepObject}} + {{#isObject}} + if let Some(ref param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + req_builder = req_builder.query(&[("{{{baseName}}}", &serde_json::to_string(param_value)?)]); + }; + {{/isObject}} + {{#isModel}} + if let Some(ref param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + req_builder = req_builder.query(&[("{{{baseName}}}", &serde_json::to_string(param_value)?)]); + }; + {{/isModel}} + {{/isDeepObject}} + {{^isObject}} + {{^isModel}} + if let Some(ref param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + req_builder = req_builder.query(&[("{{{baseName}}}", ¶m_value.to_string())]); + }; + {{/isModel}} + {{/isObject}} + {{/isNullable}} + {{/isArray}} + {{/required}} + {{^required}} + if let Some(ref param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + {{#isArray}} + req_builder = match "{{collectionFormat}}" { + "multi" => req_builder.query(¶m_value.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::>()), + _ => req_builder.query(&[("{{{baseName}}}", ¶m_value.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]), + }; + {{/isArray}} + {{^isArray}} + {{#isDeepObject}} + {{^isExplode}} + let params = crate::apis::parse_deep_object("{{{baseName}}}", &serde_json::to_value(param_value)?); + req_builder = req_builder.query(¶ms); + {{/isExplode}} + {{#isExplode}} + {{#isModel}} + req_builder = req_builder.query(¶m_value); + {{/isModel}} + {{#isMap}} + let mut query_params = Vec::with_capacity(param_value.len()); + for (key, value) in param_value.iter() { + query_params.push((key.to_string(), serde_json::to_string(value)?)); + } + req_builder = req_builder.query(&query_params); + {{/isMap}} + {{/isExplode}} + {{/isDeepObject}} + {{^isDeepObject}} + {{#isObject}} + req_builder = req_builder.query(&[("{{{baseName}}}", &serde_json::to_string(param_value)?)]); + {{/isObject}} + {{#isModel}} + req_builder = req_builder.query(&[("{{{baseName}}}", &serde_json::to_string(param_value)?)]); + {{/isModel}} + {{^isObject}} + {{^isModel}} + req_builder = req_builder.query(&[("{{{baseName}}}", ¶m_value.to_string())]); + {{/isModel}} + {{/isObject}} + {{/isDeepObject}} + {{/isArray}} + } + {{/required}} + {{/queryParams}} + {{#hasAuthMethods}} + {{#authMethods}} + {{#isApiKey}} + {{#isKeyInQuery}} + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.query(&[("{{{keyParamName}}}", value)]); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{/authMethods}} + {{/hasAuthMethods}} + {{#hasAuthMethods}} + {{#withAWSV4Signature}} + if let Some(ref aws_v4_key) = configuration.aws_v4_key { + let new_headers = match aws_v4_key.sign( + &uri_str, + "{{{httpMethod}}}", + {{#hasBodyParam}} + {{#bodyParams}} + &serde_json::to_string(&{{{vendorExtensions.x-rust-param-identifier}}}).expect("param should serialize to string"), + {{/bodyParams}} + {{/hasBodyParam}} + {{^hasBodyParam}} + "", + {{/hasBodyParam}} + ) { + Ok(new_headers) => new_headers, + Err(err) => return Err(Error::AWSV4SignatureError(err)), + }; + for (name, value) in new_headers.iter() { + req_builder = req_builder.header(name.as_str(), value.as_str()); + } + } + {{/withAWSV4Signature}} + {{/hasAuthMethods}} + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + {{#hasHeaderParams}} + {{#headerParams}} + {{#required}} + {{^isNullable}} + req_builder = req_builder.header("{{{baseName}}}", {{{vendorExtensions.x-rust-param-identifier}}}{{#isArray}}.join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{vendorExtensions.x-rust-param-identifier}}} { + Some(param_value) => { req_builder = req_builder.header("{{{baseName}}}", param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, + None => { req_builder = req_builder.header("{{{baseName}}}", ""); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + req_builder = req_builder.header("{{{baseName}}}", param_value{{#isArray}}.join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/headerParams}} + {{/hasHeaderParams}} + {{#hasAuthMethods}} + {{#authMethods}} + {{#supportTokenSource}} + // Obtain a token from source provider. + // Tokens can be Id or access tokens depending on the provider type and configuration. + let token = configuration.token_source.token().await.map_err(Error::TokenSource)?; + // The token format is the responsibility of the provider, thus we just set the authorization header with whatever is given. + req_builder = req_builder.header(reqwest::header::AUTHORIZATION, token); + {{/supportTokenSource}} + {{^supportTokenSource}} + {{#isApiKey}} + {{#isKeyInHeader}} + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("{{{keyParamName}}}", value); + }; + {{/isKeyInHeader}} + {{/isApiKey}} + {{#isBasic}} + {{#isBasicBasic}} + if let Some(ref auth_conf) = configuration.basic_auth { + req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned()); + }; + {{/isBasicBasic}} + {{#isBasicBearer}} + if let Some(ref token) = configuration.bearer_access_token { + req_builder = req_builder.bearer_auth(token.to_owned()); + }; + {{/isBasicBearer}} + {{/isBasic}} + {{#isOAuth}} + if let Some(ref token) = configuration.oauth_access_token { + req_builder = req_builder.bearer_auth(token.to_owned()); + }; + {{/isOAuth}} + {{/supportTokenSource}} + {{/authMethods}} + {{/hasAuthMethods}} + {{#isMultipart}} + {{#hasFormParams}} + let mut multipart_form = reqwest{{^supportAsync}}::blocking{{/supportAsync}}::multipart::Form::new(); + {{#formParams}} + {{#isFile}} + {{^supportAsync}} + {{#required}} + {{^isNullable}} + multipart_form = multipart_form.file("{{{baseName}}}", {{{vendorExtensions.x-rust-param-identifier}}})?; + {{/isNullable}} + {{#isNullable}} + match {{{vendorExtensions.x-rust-param-identifier}}} { + Some(param_value) => { multipart_form = multipart_form.file("{{{baseName}}}", param_value)?; }, + None => { unimplemented!("Required nullable form file param not supported"); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + multipart_form = multipart_form.file("{{{baseName}}}", param_value)?; + } + {{/required}} + {{/supportAsync}} + {{#supportAsync}} + // TODO: support file upload for '{{{baseName}}}' parameter + {{/supportAsync}} + {{/isFile}} + {{^isFile}} + {{#required}} + {{^isNullable}} + multipart_form = multipart_form.text("{{{baseName}}}", {{{vendorExtensions.x-rust-param-identifier}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{vendorExtensions.x-rust-param-identifier}}} { + Some(param_value) => { multipart_form = multipart_form.text("{{{baseName}}}", param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); }, + None => { multipart_form = multipart_form.text("{{{baseName}}}", ""); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + multipart_form = multipart_form.text("{{{baseName}}}", param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/isFile}} + {{/formParams}} + req_builder = req_builder.multipart(multipart_form); + {{/hasFormParams}} + {{/isMultipart}} + {{^isMultipart}} + {{#hasFormParams}} + let mut multipart_form_params = std::collections::HashMap::new(); + {{#formParams}} + {{#isFile}} + {{#required}} + {{^isNullable}} + multipart_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); + {{/isNullable}} + {{#isNullable}} + match {{{vendorExtensions.x-rust-param-identifier}}} { + Some(param_value) => { multipart_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); }, + None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + multipart_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); + } + {{/required}} + {{/isFile}} + {{^isFile}} + {{#required}} + {{^isNullable}} + multipart_form_params.insert("{{{baseName}}}", {{{vendorExtensions.x-rust-param-identifier}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{vendorExtensions.x-rust-param-identifier}}} { + Some(param_value) => { multipart_form_params.insert("{{{baseName}}}", param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); }, + None => { multipart_form_params.insert("{{{baseName}}}", ""); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(param_value) = {{{vendorExtensions.x-rust-param-identifier}}} { + multipart_form_params.insert("{{{baseName}}}", param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/isFile}} + {{/formParams}} + req_builder = req_builder.form(&multipart_form_params); + {{/hasFormParams}} + {{/isMultipart}} + {{#hasBodyParam}} + {{! Check for the raw text body extension first }} + {{#vendorExtensions.x-rust-body-is-raw-text}} + {{! If the flag is true, we generate only the raw text body logic }} + {{#bodyParams}} + req_builder = req_builder.header(reqwest::header::CONTENT_TYPE, "text/plain").body({{{vendorExtensions.x-rust-param-identifier}}}.to_owned()); + {{/bodyParams}} + {{/vendorExtensions.x-rust-body-is-raw-text}} + {{! Now, handle the case where the extension is NOT present. This is the "else" block }} + {{^vendorExtensions.x-rust-body-is-raw-text}} + {{! This contains the original default logic }} + {{#bodyParams}} + {{#isFile}} + req_builder = req_builder.body({{{vendorExtensions.x-rust-param-identifier}}}); + {{/isFile}} + {{^isFile}} + req_builder = req_builder.json(&{{{vendorExtensions.x-rust-param-identifier}}}); + {{/isFile}} + {{/bodyParams}} + {{/vendorExtensions.x-rust-body-is-raw-text}} + {{/hasBodyParam}} + + let req = req_builder.build()?; + let resp = configuration.client.execute(req){{#supportAsync}}.await{{/supportAsync}}?; + + let status = resp.status(); + {{^supportMultipleResponses}} + {{^isResponseFile}} + {{#returnType}} + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + {{/returnType}} + {{/isResponseFile}} + {{/supportMultipleResponses}} + + if !status.is_client_error() && !status.is_server_error() { + {{^supportMultipleResponses}} + {{#isResponseFile}} + Ok(resp) + {{/isResponseFile}} + {{^isResponseFile}} + {{^returnType}} + Ok(()) + {{/returnType}} + {{#returnType}} + let content = resp.text(){{#supportAsync}}.await{{/supportAsync}}?; + match content_type { + {{#vendorExtensions.x-supports-plain-text}} + ContentType::Json | ContentType::Text => return Ok(content), + {{/vendorExtensions.x-supports-plain-text}} + {{^vendorExtensions.x-supports-plain-text}} + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `{{#vendorExtensions.x-rust-return-type}}{{{.}}}{{/vendorExtensions.x-rust-return-type}}{{^vendorExtensions.x-rust-return-type}}{{{returnType}}}{{/vendorExtensions.x-rust-return-type}}`"))), + {{/vendorExtensions.x-supports-plain-text}} + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `{{#vendorExtensions.x-rust-return-type}}{{{.}}}{{/vendorExtensions.x-rust-return-type}}{{^vendorExtensions.x-rust-return-type}}{{{returnType}}}{{/vendorExtensions.x-rust-return-type}}`")))), + } + {{/returnType}} + {{/isResponseFile}} + {{/supportMultipleResponses}} + {{#supportMultipleResponses}} + {{#isResponseFile}} + Ok(resp) + {{/isResponseFile}} + {{^isResponseFile}} + let content = resp.text(){{#supportAsync}}.await{{/supportAsync}}?; + let entity: Option<{{{operationIdCamelCase}}}Success> = serde_json::from_str(&content).ok(); + Ok(ResponseContent { status, content, entity }) + {{/isResponseFile}} + {{/supportMultipleResponses}} + } else { + let content = resp.text(){{#supportAsync}}.await{{/supportAsync}}?; + let entity: Option<{{{operationIdCamelCase}}}Error> = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +{{/operation}} +{{/operations}} diff --git a/openapi-generator-template/reqwest/api_mod.mustache b/openapi-generator-template/reqwest/api_mod.mustache new file mode 100644 index 0000000..6a78390 --- /dev/null +++ b/openapi-generator-template/reqwest/api_mod.mustache @@ -0,0 +1,169 @@ +use std::{error, fmt}; + +{{#withAWSV4Signature}} +use aws_sigv4; +{{/withAWSV4Signature}} + +#[derive(Debug, Clone)] +pub struct ResponseContent { + pub status: reqwest::StatusCode, + pub content: String, + pub entity: Option, +} + +#[derive(Debug)] +pub enum Error { + Reqwest(reqwest::Error), + {{#supportMiddleware}} + #[cfg(not(target_family = "wasm"))] + ReqwestMiddleware(reqwest_middleware::Error), + {{/supportMiddleware}} + Serde(serde_json::Error), + Io(std::io::Error), + ResponseError(ResponseContent), + {{#withAWSV4Signature}} + AWSV4SignatureError(aws_sigv4::http_request::Error), + {{/withAWSV4Signature}} + {{#supportAsync}} + {{#supportTokenSource}} + TokenSource(Box), + {{/supportTokenSource}} + {{/supportAsync}} +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (module, e) = match self { + Error::Reqwest(e) => ("reqwest", e.to_string()), + {{#supportMiddleware}} + #[cfg(not(target_family = "wasm"))] + Error::ReqwestMiddleware(e) => ("reqwest-middleware", e.to_string()), + {{/supportMiddleware}} + Error::Serde(e) => ("serde", e.to_string()), + Error::Io(e) => ("IO", e.to_string()), + Error::ResponseError(e) => ("response", format!("status code {}", e.status)), + {{#withAWSV4Signature}} + Error::AWSV4SignatureError(e) => ("aws v4 signature", e.to_string()), + {{/withAWSV4Signature}} + {{#supportAsync}} + {{#supportTokenSource}} + Error::TokenSource(e) => ("token source failure", e.to_string()), + {{/supportTokenSource}} + {{/supportAsync}} + }; + write!(f, "error in {module}: {e}") + } +} + +impl error::Error for Error { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + Some(match self { + Error::Reqwest(e) => e, + {{#supportMiddleware}} + #[cfg(not(target_family = "wasm"))] + Error::ReqwestMiddleware(e) => e, + {{/supportMiddleware}} + Error::Serde(e) => e, + Error::Io(e) => e, + Error::ResponseError(_) => return None, + {{#withAWSV4Signature}} + Error::AWSV4SignatureError(_) => return None, + {{/withAWSV4Signature}} + {{#supportAsync}} + {{#supportTokenSource}} + Error::TokenSource(e) => &**e, + {{/supportTokenSource}} + {{/supportAsync}} + }) + } +} + +impl From for Error { + fn from(e: reqwest::Error) -> Self { + Error::Reqwest(e) + } +} + +{{#supportMiddleware}} +#[cfg(not(target_family = "wasm"))] +impl From for Error { + fn from(e: reqwest_middleware::Error) -> Self { + Error::ReqwestMiddleware(e) + } +} + +{{/supportMiddleware}} +impl From for Error { + fn from(e: serde_json::Error) -> Self { + Error::Serde(e) + } +} + +impl From for Error { + fn from(e: std::io::Error) -> Self { + Error::Io(e) + } +} + +pub fn urlencode>(s: T) -> String { + ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect() +} + +pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String, String)> { + if let serde_json::Value::Object(object) = value { + let mut params = vec![]; + + for (key, value) in object { + match value { + serde_json::Value::Object(_) => { + params.append(&mut parse_deep_object(&format!("{prefix}[{key}]"), value)) + } + serde_json::Value::Array(array) => { + for (i, value) in array.iter().enumerate() { + params.append(&mut parse_deep_object( + &format!("{prefix}[{key}][{i}]"), + value, + )); + } + } + serde_json::Value::String(s) => { + params.push((format!("{prefix}[{key}]"), s.clone())) + } + _ => params.push((format!("{prefix}[{key}]"), value.to_string())), + } + } + + return params; + } + + unimplemented!("Only objects are supported with style=deepObject") +} + +/// Internal use only +/// A content type supported by this client. +#[allow(dead_code)] +enum ContentType { + Json, + Text, + Unsupported(String) +} + +impl From<&str> for ContentType { + fn from(content_type: &str) -> Self { + if content_type.starts_with("application") && content_type.contains("json") { + return Self::Json; + } else if content_type.starts_with("text/plain") { + return Self::Text; + } else { + return Self::Unsupported(content_type.to_string()); + } + } +} + +{{#apiInfo}} +{{#apis}} +pub mod {{{classFilename}}}; +{{/apis}} +{{/apiInfo}} + +pub mod configuration; diff --git a/openapi-generator-template/reqwest/configuration.mustache b/openapi-generator-template/reqwest/configuration.mustache new file mode 100644 index 0000000..e29c73b --- /dev/null +++ b/openapi-generator-template/reqwest/configuration.mustache @@ -0,0 +1,122 @@ +{{>partial_header}} + +{{#withAWSV4Signature}} +use std::time::SystemTime; +use aws_sigv4::http_request::{sign, SigningSettings, SigningParams, SignableRequest}; +use http; +use secrecy::{SecretString, ExposeSecret}; +{{/withAWSV4Signature}} +{{#supportTokenSource}} +use std::sync::Arc; +use google_cloud_token::TokenSource; +use async_trait::async_trait; +{{/supportTokenSource}} + +#[derive(Debug, Clone)] +pub struct Configuration { + pub base_path: String, + pub user_agent: Option, + pub client: {{#supportMiddleware}}reqwest_middleware::ClientWithMiddleware{{/supportMiddleware}}{{^supportMiddleware}}reqwest{{^supportAsync}}::blocking{{/supportAsync}}::Client{{/supportMiddleware}}, + {{^supportTokenSource}} + pub basic_auth: Option, + pub oauth_access_token: Option, + pub bearer_access_token: Option, + pub api_key: Option, + {{/supportTokenSource}} + {{#withAWSV4Signature}} + pub aws_v4_key: Option, + {{/withAWSV4Signature}} + {{#supportAsync}} + {{#supportTokenSource}} + pub token_source: Arc, + {{/supportTokenSource}} + {{/supportAsync}} +} +{{^supportTokenSource}} + +pub type BasicAuth = (String, Option); + +#[derive(Debug, Clone)] +pub struct ApiKey { + pub prefix: Option, + pub key: String, +} +{{/supportTokenSource}} + +{{#withAWSV4Signature}} +#[derive(Debug, Clone)] +pub struct AWSv4Key { + pub access_key: String, + pub secret_key: SecretString, + pub region: String, + pub service: String, +} + +impl AWSv4Key { + pub fn sign(&self, uri: &str, method: &str, body: &str) -> Result, aws_sigv4::http_request::Error> { + let request = http::Request::builder() + .uri(uri) + .method(method) + .body(body).unwrap(); + let signing_settings = SigningSettings::default(); + let signing_params = SigningParams::builder() + .access_key(self.access_key.as_str()) + .secret_key(self.secret_key.expose_secret().as_str()) + .region(self.region.as_str()) + .service_name(self.service.as_str()) + .time(SystemTime::now()) + .settings(signing_settings) + .build() + .unwrap(); + let signable_request = SignableRequest::from(&request); + let (mut signing_instructions, _signature) = sign(signable_request, &signing_params)?.into_parts(); + let mut additional_headers = Vec::<(String, String)>::new(); + if let Some(new_headers) = signing_instructions.take_headers() { + for (name, value) in new_headers.into_iter() { + additional_headers.push((name.expect("header should have name").to_string(), + value.to_str().expect("header value should be a string").to_string())); + } + } + Ok(additional_headers) + } +} +{{/withAWSV4Signature}} + +impl Configuration { + pub fn new() -> Configuration { + Configuration::default() + } +} + +impl Default for Configuration { + fn default() -> Self { + Configuration { + base_path: "{{{basePath}}}".to_owned(), + user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}}, + client: {{#supportMiddleware}}reqwest_middleware::ClientBuilder::new(reqwest{{^supportAsync}}::blocking{{/supportAsync}}::Client::new()).build(){{/supportMiddleware}}{{^supportMiddleware}}reqwest{{^supportAsync}}::blocking{{/supportAsync}}::Client::new(){{/supportMiddleware}}, + {{^supportTokenSource}} + basic_auth: None, + oauth_access_token: None, + bearer_access_token: None, + api_key: None, + {{/supportTokenSource}} + {{#withAWSV4Signature}} + aws_v4_key: None, + {{/withAWSV4Signature}} + {{#supportTokenSource}} + token_source: Arc::new(NoopTokenSource{}), + {{/supportTokenSource}} + } + } +} +{{#supportTokenSource}} +#[derive(Debug)] +struct NoopTokenSource{} + +#[async_trait] +impl TokenSource for NoopTokenSource { + async fn token(&self) -> Result> { + panic!("This is dummy token source. You can use TokenSourceProvider from 'google_cloud_auth' crate, or any other compatible crate.") + } +} +{{/supportTokenSource}} diff --git a/openapi.yml b/openapi.yml index 3bac4f6..2eb7936 100644 --- a/openapi.yml +++ b/openapi.yml @@ -2,7 +2,23 @@ openapi: 3.0.3 info: title: Typesense API description: "An open source search engine for building delightful search experiences." - version: 0.25.0 + 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 @@ -19,8 +35,8 @@ tags: externalDocs: description: Find out more url: https://typesense.org/api/#index-document - - name: promote - description: Promote certain documents over others + - name: curation + description: Hand-curate search results based on conditional business rules externalDocs: description: Find out more url: https://typesense.org/docs/0.23.0/api/#curation @@ -28,7 +44,7 @@ tags: description: Typesense can aggregate search queries for both analytics purposes and for query suggestions. externalDocs: description: Find out more - url: https://typesense.org/docs/0.25.0/api/analytics-query-suggestions.html + url: https://typesense.org/docs/28.0/api/analytics-query-suggestions.html - name: keys description: Manage API Keys with fine-grain access control externalDocs: @@ -40,7 +56,37 @@ tags: description: Manage Typesense cluster externalDocs: description: Find out more - url: https://typesense.org/docs/0.23.0/api/#cluster-operations + url: https://typesense.org/docs/28.0/api/cluster-operations.html + - name: stopwords + description: Manage stopwords sets + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stopwords.html + - name: presets + description: Store and reference search parameters + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/search.html#presets + - name: conversations + description: Conversational Search (RAG) + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/conversational-search-rag.html + - name: synonyms + description: Manage synonyms + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/synonyms.html + - name: stemming + description: Manage stemming dictionaries + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stemming.html + - name: nl_search_models + description: Manage NL search models + externalDocs: + description: Find out more + url: https://typesense.org/docs/29.0/api/natural-language-search.html paths: /collections: @@ -53,8 +99,25 @@ paths: returned sorted by creation date, with the most recent collections appearing first. operationId: getCollections + parameters: + - name: getCollectionsParameters + in: query + schema: + type: object + properties: + exclude_fields: + description: Comma-separated list of fields from the collection to exclude from the response + type: string + limit: + description: > + Number of collections to fetch. + Default: returns all collections. + type: integer + offset: + description: Identifies the starting point to return collections when paginating. + type: integer responses: - 200: + '200': description: List of all collections content: application/json: @@ -79,19 +142,19 @@ paths: $ref: "#/components/schemas/CollectionSchema" required: true responses: - 201: + '201': description: Collection successfully created content: application/json: schema: $ref: "#/components/schemas/CollectionResponse" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 409: + '409': description: Collection already exists content: application/json: @@ -112,13 +175,13 @@ paths: schema: type: string responses: - 200: + '200': description: Collection fetched content: application/json: schema: $ref: "#/components/schemas/CollectionResponse" - 404: + '404': description: Collection not found content: application/json: @@ -146,19 +209,19 @@ paths: $ref: "#/components/schemas/CollectionUpdateSchema" required: true responses: - 200: + '200': description: The updated partial collection schema content: application/json: schema: $ref: "#/components/schemas/CollectionUpdateSchema" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: The collection was not found content: application/json: @@ -180,13 +243,13 @@ paths: schema: type: string responses: - 200: + '200': description: Collection deleted content: application/json: schema: $ref: "#/components/schemas/CollectionResponse" - 404: + '404': description: Collection not found content: application/json: @@ -214,8 +277,12 @@ paths: schema: type: string example: upsert - enum: - - upsert + $ref: "#/components/schemas/IndexAction" + - name: dirty_values + in: query + description: Dealing with Dirty Data + schema: + $ref: "#/components/schemas/DirtyValues" requestBody: description: The document object to be indexed content: @@ -226,14 +293,14 @@ paths: x-go-type: "interface{}" required: true responses: - 201: + '201': description: Document successfully created/indexed content: application/json: schema: type: object description: Can be any key-value pair - 404: + '404': description: Collection not found content: application/json: @@ -320,6 +387,8 @@ paths: in: query schema: type: object + required: + - filter_by properties: filter_by: type: string @@ -330,8 +399,13 @@ paths: at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. type: integer + ignore_not_found: + type: boolean + truncate: + description: When true, removes all documents from the collection while preserving the collection and its schema. + type: boolean responses: - 200: + '200': description: Documents successfully deleted content: application/json: @@ -342,7 +416,7 @@ paths: properties: num_deleted: type: integer - 404: + '404': description: Collection not found content: application/json: @@ -368,19 +442,19 @@ paths: schema: $ref: "#/components/schemas/SearchParameters" responses: - 200: + '200': description: Search results content: application/json: schema: $ref: "#/components/schemas/SearchResult" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: The collection or field was not found content: application/json: @@ -390,7 +464,7 @@ paths: get: tags: - documents - - promote + - curation summary: List all collection overrides operationId: getSearchOverrides parameters: @@ -401,7 +475,7 @@ paths: schema: type: string responses: - 200: + '200': description: List of all search overrides content: application/json: @@ -429,7 +503,7 @@ paths: schema: type: string responses: - 200: + '200': description: Search override fetched content: application/json: @@ -438,7 +512,7 @@ paths: put: tags: - documents - - promote + - curation summary: Create or update an override to promote certain documents over others description: Create or update an override to promote certain documents over others. @@ -465,13 +539,13 @@ paths: $ref: "#/components/schemas/SearchOverrideSchema" required: true responses: - 200: + '200': description: Created/updated search override content: application/json: schema: $ref: "#/components/schemas/SearchOverride" - 404: + '404': description: Search override not found content: application/json: @@ -480,7 +554,7 @@ paths: delete: tags: - documents - - promote + - curation summary: Delete an override associated with a collection operationId: deleteSearchOverride parameters: @@ -497,143 +571,118 @@ paths: schema: type: string responses: - 200: + '200': description: The ID of the deleted search override content: application/json: schema: - $ref: "#/components/schemas/SearchOverride" - 404: + $ref: "#/components/schemas/SearchOverrideDeleteResponse" + '404': description: Search override not found content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - /collections/{collectionName}/synonyms: + + /synonym_sets: get: tags: - - documents - summary: List all collection synonyms - operationId: getSearchSynonyms - parameters: - - name: collectionName - in: path - description: The name of the collection - required: true - schema: - type: string + - synonyms + summary: List all synonym sets + description: Retrieve all synonym sets + operationId: retrieveSynonymSets responses: - 200: - description: List of all search synonyms + "200": + description: List of all synonym sets content: application/json: schema: - $ref: "#/components/schemas/SearchSynonymsResponse" - 404: - description: Search synonyms was not found - content: - application/json: - schema: - $ref: "#/components/schemas/ApiResponse" - /collections/{collectionName}/synonyms/{synonymId}: + type: array + items: + $ref: "#/components/schemas/SynonymSetSchema" + + /synonym_sets/{synonymSetName}: get: tags: - - documents - summary: Retrieve a single search synonym - description: Retrieve the details of a search synonym, given its id. - operationId: getSearchSynonym + - synonyms + summary: Retrieve a synonym set + description: Retrieve a specific synonym set by its name + operationId: retrieveSynonymSet parameters: - - name: collectionName - in: path - description: The name of the collection - required: true - schema: - type: string - - name: synonymId + - name: synonymSetName in: path - description: The id of the search synonym + description: The name of the synonym set to retrieve required: true schema: type: string responses: - 200: - description: Search synonym fetched + "200": + description: Synonym set fetched content: application/json: schema: - $ref: "#/components/schemas/SearchSynonym" - 404: - description: Search synonym was not found + $ref: "#/components/schemas/SynonymSetRetrieveSchema" + "404": + description: Synonym set not found content: application/json: schema: $ref: "#/components/schemas/ApiResponse" put: tags: - - documents - summary: Create or update a synonym - description: Create or update a synonym to define search terms that should be considered equivalent. - operationId: upsertSearchSynonym + - synonyms + summary: Create or update a synonym set + description: Create or update a synonym set with the given name + operationId: upsertSynonymSet parameters: - - name: collectionName - in: path - description: The name of the collection - required: true - schema: - type: string - - name: synonymId + - name: synonymSetName in: path - description: The ID of the search synonym to create/update + description: The name of the synonym set to create/update required: true schema: type: string requestBody: - description: The search synonym object to be created/updated + description: The synonym set to be created/updated content: application/json: schema: - $ref: "#/components/schemas/SearchSynonymSchema" + $ref: "#/components/schemas/SynonymSetCreateSchema" required: true responses: - 200: - description: Created/updated search synonym + "200": + description: Synonym set successfully created/updated content: application/json: schema: - $ref: "#/components/schemas/SearchSynonym" - 404: - description: Search synonym was not found + $ref: "#/components/schemas/SynonymSetSchema" + "400": + description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" delete: tags: - - documents - summary: Delete a synonym associated with a collection - operationId: deleteSearchSynonym + - synonyms + summary: Delete a synonym set + description: Delete a specific synonym set by its name + operationId: deleteSynonymSet parameters: - - name: collectionName - in: path - description: The name of the collection - required: true - schema: - type: string - - name: synonymId + - name: synonymSetName in: path - description: The ID of the search synonym to delete + description: The name of the synonym set to delete required: true schema: type: string responses: - 200: - description: The ID of the deleted search synonym + "200": + description: Synonym set successfully deleted content: application/json: schema: - $ref: "#/components/schemas/SearchSynonym" - 404: - description: Search synonym not found + $ref: "#/components/schemas/SynonymSetDeleteSchema" + "404": + description: Synonym set not found content: application/json: schema: @@ -657,9 +706,6 @@ paths: in: query schema: type: object - required: - - include_fields - - exclude_fields properties: filter_by: description: @@ -674,7 +720,7 @@ paths: type: string responses: - 200: + '200': description: Exports all the documents in a given collection. content: application/octet-stream: @@ -684,7 +730,7 @@ paths: {"id": "124", "company_name": "Stark Industries", "num_employees": 5215, "country": "US"} {"id": "125", "company_name": "Future Technology", "num_employees": 1232,"country": "UK"} {"id": "126", "company_name": "Random Corp.", "num_employees": 531,"country": "AU"} - 404: + '404': description: The collection was not found content: application/json: @@ -707,24 +753,28 @@ paths: required: true schema: type: string + # Do not change the index position of this param - name: importDocumentsParameters in: query schema: type: object properties: - action: - type: string batch_size: type: integer - dirty_values: - type: string - enum: - - coerce_or_reject - - coerce_or_drop - - drop - - reject + return_id: + type: boolean + description: + Returning the id of the imported documents. If you want the + import response to return the ingested document's id in the + response, you can use the return_id parameter. remote_embedding_batch_size: type: integer + return_doc: + type: boolean + action: + $ref: "#/components/schemas/IndexAction" + dirty_values: + $ref: "#/components/schemas/DirtyValues" requestBody: description: The json array of documents or the JSONL file to import content: @@ -734,7 +784,7 @@ paths: description: The JSONL file to import required: true responses: - 200: + '200': description: Result of the import operation. Each line of the response indicates the result of each document present in the request body (in the same order). If the import @@ -748,13 +798,13 @@ paths: example: | {"success": true} {"success": false, "error": "Bad JSON.", "document": "[bad doc"} - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: The collection was not found content: application/json: @@ -764,7 +814,7 @@ paths: get: tags: - documents - summary: Retreive a document + summary: Retrieve a document description: Fetch an individual document from a collection by using its ID. operationId: getDocument parameters: @@ -781,14 +831,14 @@ paths: schema: type: string responses: - 200: + '200': description: The document referenced by the ID content: application/json: schema: type: object description: Can be any key-value pair - 404: + '404': description: The document or collection was not found content: application/json: @@ -815,6 +865,11 @@ paths: required: true schema: type: string + - name: dirty_values + in: query + description: Dealing with Dirty Data + schema: + $ref: "#/components/schemas/DirtyValues" requestBody: description: The document object with fields to be updated content: @@ -825,14 +880,14 @@ paths: x-go-type: "interface{}" required: true responses: - 200: + '200': description: The document referenced by the ID was updated content: application/json: schema: type: object description: Can be any key-value pair - 404: + '404': description: The document or collection was not found content: application/json: @@ -858,19 +913,128 @@ paths: schema: type: string responses: - 200: + '200': description: The document referenced by the ID was deleted content: application/json: schema: type: object description: Can be any key-value pair - 404: + '404': description: The document or collection was not found content: application/json: schema: $ref: "#/components/schemas/ApiResponse" + /conversations/models: + get: + description: Retrieve all conversation models + operationId: retrieveAllConversationModels + responses: + '200': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/ConversationModelSchema' + type: array + x-go-type: '[]*ConversationModelSchema' + description: List of all conversation models + summary: List all conversation models + tags: + - conversations + post: + 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: @@ -878,7 +1042,7 @@ paths: summary: Retrieve (metadata about) all keys. operationId: getKeys responses: - 200: + '200': description: List of all keys content: application/json: @@ -901,19 +1065,19 @@ paths: schema: $ref: "#/components/schemas/ApiKeySchema" responses: - 201: + '201': description: Created API key content: application/json: schema: $ref: "#/components/schemas/ApiKey" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 409: + '409': description: API key generation conflict content: application/json: @@ -938,13 +1102,13 @@ paths: type: integer format: int64 responses: - 200: + '200': description: The key referenced by the ID content: application/json: schema: $ref: "#/components/schemas/ApiKey" - 404: + '404': description: The key was not found content: application/json: @@ -964,19 +1128,19 @@ paths: type: integer format: int64 responses: - 200: + '200': description: The key referenced by the ID content: application/json: schema: - $ref: "#/components/schemas/ApiKey" - 400: + $ref: "#/components/schemas/ApiKeyDeleteResponse" + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: Key not found content: application/json: @@ -990,7 +1154,7 @@ paths: description: List all aliases and the corresponding collections that they map to. operationId: getAliases responses: - 200: + '200': description: List of all collection aliases content: application/json: @@ -1022,19 +1186,19 @@ paths: schema: $ref: "#/components/schemas/CollectionAliasSchema" responses: - 200: + '200': description: The collection alias was created/updated content: application/json: schema: $ref: "#/components/schemas/CollectionAlias" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - 404: + '404': description: Alias not found content: application/json: @@ -1054,13 +1218,13 @@ paths: schema: type: string responses: - 200: + '200': description: Collection alias fetched content: application/json: schema: $ref: "#/components/schemas/CollectionAlias" - 404: + '404': description: The alias was not found content: application/json: @@ -1079,13 +1243,13 @@ paths: schema: type: string responses: - 200: + '200': description: Collection alias was deleted content: application/json: schema: $ref: "#/components/schemas/CollectionAlias" - 404: + '404': description: Alias not found content: application/json: @@ -1099,7 +1263,7 @@ paths: description: Print debugging information operationId: debug responses: - 200: + '200': description: Debugging information content: application/json: @@ -1116,12 +1280,28 @@ paths: description: Checks if Typesense server is ready to accept requests. operationId: health responses: - 200: + '200': description: Search service is ready for requests. content: application/json: schema: $ref: "#/components/schemas/HealthStatus" + /operations/schema_changes: + get: + tags: + - operations + summary: Get the status of in-progress schema change operations + description: Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. + operationId: getSchemaChanges + responses: + '200': + description: List of schema changes in progress + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/SchemaChangeStatus" /operations/snapshot: post: tags: @@ -1140,7 +1320,7 @@ paths: schema: type: string responses: - 201: + '201': description: Snapshot is created. content: application/json: @@ -1157,12 +1337,72 @@ paths: once this command succeeds. operationId: vote responses: - 200: + '200': description: Re-election is performed. content: application/json: schema: $ref: "#/components/schemas/SuccessStatus" + /operations/cache/clear: + post: + tags: + - operations + summary: Clear the cached responses of search requests in the LRU cache. + description: + Clear the cached responses of search requests that are sent with `use_cache` parameter in the LRU cache. + operationId: clearCache + responses: + '200': + description: Clear cache succeeded. + content: + application/json: + schema: + $ref: "#/components/schemas/SuccessStatus" + /operations/db/compact: + post: + tags: + - operations + summary: Compacting the on-disk database + description: + Typesense uses RocksDB to store your documents on the disk. If you do frequent writes or updates, you could benefit from running a compaction of the underlying RocksDB database. + This could reduce the size of the database and decrease read latency. While the database will not block during this operation, we recommend running it during off-peak hours. + operationId: compactDb + responses: + '200': + description: Compacting the on-disk database succeeded. + content: + application/json: + schema: + $ref: "#/components/schemas/SuccessStatus" + /config: + post: + tags: + - operations + summary: Toggle Slow Request Log + description: + Enable logging of requests that take over a defined threshold of time. + Default is `-1` which disables slow request logging. + Slow requests are logged to the primary log file, with the prefix SLOW REQUEST. + operationId: toggleSlowRequestLog + requestBody: + content: + application/json: + schema: + type: object + properties: + log-slow-requests-time-ms: + type: integer + required: + - log-slow-requests-time-ms + example: | + {"log-slow-requests-time-ms": 2000} + responses: + '200': + description: Compacting the on-disk database succeeded. + content: + application/json: + schema: + $ref: "#/components/schemas/SuccessStatus" /multi_search: post: operationId: multiSearch @@ -1184,61 +1424,207 @@ paths: schema: $ref: "#/components/schemas/MultiSearchSearchesParameter" responses: - 200: + '200': description: Search results content: application/json: schema: $ref: "#/components/schemas/MultiSearchResult" - 400: + '400': description: Bad request, see error message for details content: application/json: schema: $ref: "#/components/schemas/ApiResponse" - /analytics/rules: + /analytics/events: post: tags: - analytics - summary: Creates an analytics rule - description: - When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. - operationId: createAnalyticsRule + 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 rule to be created + description: The analytics event to be created content: application/json: schema: - $ref: "#/components/schemas/AnalyticsRuleSchema" + $ref: '#/components/schemas/AnalyticsEvent' required: true responses: - 201: - description: Analytics rule successfully created + '200': + description: Analytics event successfully created content: application/json: schema: - $ref: "#/components/schemas/AnalyticsRuleSchema" - 400: + $ref: '#/components/schemas/AnalyticsEventCreateResponse' + '400': description: Bad request, see error message for details content: application/json: schema: - $ref: "#/components/schemas/ApiResponse" + $ref: '#/components/schemas/ApiResponse' get: tags: - analytics - summary: Retrieves all analytics rules - description: - Retrieve the details of all analytics rules - operationId: retrieveAnalyticsRules - responses: - 200: - description: Analytics rules fetched + 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/AnalyticsRulesRetrieveSchema" + $ref: '#/components/schemas/AnalyticsStatus' + /analytics/rules: + post: + tags: + - analytics + summary: Create analytics rule(s) + description: Create one or more analytics rules. You can send a single rule object or an array of rule objects. + operationId: createAnalyticsRule + requestBody: + description: The analytics rule(s) to be created + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/AnalyticsRuleCreate" + - type: array + items: + $ref: "#/components/schemas/AnalyticsRuleCreate" + required: true + responses: + '200': + description: Analytics rule(s) successfully created + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/AnalyticsRule" + - type: array + items: + anyOf: + - $ref: "#/components/schemas/AnalyticsRule" + - type: object + properties: + error: + type: string + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + get: + tags: + - analytics + summary: Retrieve analytics rules + description: Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. + operationId: retrieveAnalyticsRules + parameters: + - in: query + name: rule_tag + schema: + type: string + required: false + description: Filter rules by rule_tag + responses: + '200': + description: Analytics rules fetched + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/AnalyticsRule" /analytics/rules/{ruleName}: + put: + tags: + - analytics + summary: Upserts an analytics rule + description: + Upserts an analytics rule with the given name. + operationId: upsertAnalyticsRule + parameters: + - in: path + name: ruleName + description: The name of the analytics rule to upsert + schema: + type: string + required: true + requestBody: + description: The Analytics rule to be upserted + content: + application/json: + schema: + $ref: "#/components/schemas/AnalyticsRuleUpdate" + required: true + responses: + '200': + description: Analytics rule successfully upserted + content: + application/json: + schema: + $ref: "#/components/schemas/AnalyticsRule" + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" get: tags: - analytics @@ -1254,13 +1640,13 @@ paths: type: string required: true responses: - 200: + '200': description: Analytics rule fetched content: application/json: schema: - $ref: "#/components/schemas/AnalyticsRuleSchema" - 404: + $ref: "#/components/schemas/AnalyticsRule" + '404': description: Analytics rule not found content: application/json: @@ -1281,18 +1667,491 @@ paths: type: string required: true responses: - 200: + '200': description: Analytics rule deleted content: application/json: schema: - $ref: "#/components/schemas/AnalyticsRuleSchema" - 404: + $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: @@ -1331,7 +2190,7 @@ components: token_separators: type: array description: > - List of symbols or special characters to be used for + List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. items: type: string # characters only @@ -1340,13 +2199,19 @@ components: 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 + type: boolean + description: + Enables experimental support at a collection level for nested object or object array fields. + This field is only available if the Typesense server is version `0.24.0.rcn34` or later. + default: false + example: true symbols_to_index: type: array description: > @@ -1358,6 +2223,12 @@ components: 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 @@ -1378,6 +2249,16 @@ components: 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" @@ -1428,6 +2309,10 @@ components: type: boolean example: true default: false + reference: + type: string + description: > + Name of a field in another collection that should be linked to this collection so that it can be joined during query. num_dim: type: integer example: 256 @@ -1435,6 +2320,49 @@ components: type: boolean example: true # omitting default value since we want it to be null + store: + type: boolean + description: > + When set to false, the field value will not be stored on disk. Default: true. + vec_dist: + type: string + description: > + The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. + range_index: + type: boolean + description: > + Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. + stem: + type: boolean + description: > + Values are stemmed before indexing in-memory. Default: false. + stem_dictionary: + type: string + description: Name of the stemming dictionary to use for this field + example: irregular-plurals + token_separators: + type: array + description: > + List of symbols or special characters to be used for + splitting the text into individual words in addition to space and new-line characters. + items: + type: string # characters only + # Could `enum` be used instead, given it's symbols/special *characters*, e.g.: + # enum: ["@", "!", ".", "/", ","] + minLength: 1 + maxLength: 1 + default: [] + symbols_to_index: + type: array + description: > + List of symbols or special characters to be indexed. + items: + type: string # characters only + # Could `enum` be used instead, given it's symbols/special *characters*, e.g.: + # enum: ["@", "!", ".", "/", ","] + minLength: 1 + maxLength: 1 + default: [] embed: type: object required: @@ -1454,14 +2382,30 @@ components: type: string api_key: type: string + url: + type: string access_token: type: string + refresh_token: + type: string client_id: type: string client_secret: type: string project_id: type: string + indexing_prefix: + type: string + query_prefix: + type: string + VoiceQueryModelCollectionConfig: + type: object + description: > + Configuration for the voice query model + properties: + model_name: + type: string + example: "ts/whisper/base.en" CollectionAliasSchema: type: object required: @@ -1503,6 +2447,8 @@ components: found: type: integer description: The number of documents found + found_docs: + type: integer search_time_ms: type: integer description: The number of milliseconds the search took @@ -1525,19 +2471,50 @@ components: items: $ref: "#/components/schemas/SearchResultHit" request_params: + $ref: "#/components/schemas/SearchRequestParams" + conversation: + $ref: "#/components/schemas/SearchResultConversation" + union_request_params: + type: array + description: Returned only for union query response. + items: + $ref: "#/components/schemas/SearchRequestParams" + 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 - required: - - collection_name - - q - - per_page properties: - collection_name: + transcribed_query: type: string - q: - type: string - per_page: - type: integer - + SearchResultConversation: + type: object + required: + - answer + - conversation_history + - conversation_id + - query + properties: + answer: + type: string + conversation_history: + type: array + items: + type: object + conversation_id: + type: string + query: + type: string SearchGroupedHit: type: object required: @@ -1574,6 +2551,25 @@ components: text_match: type: integer format: int64 + text_match_info: + type: object + properties: + best_field_score: + type: string + best_field_weight: + type: integer + fields_matched: + type: integer + num_tokens_dropped: + type: integer + format: int64 + x-go-type: uint64 + score: + type: string + tokens_matched: + type: integer + typo_prefix_score: + type: integer geo_distance_meters: type: object description: Can be any key-value pair @@ -1583,6 +2579,17 @@ components: 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: @@ -1664,6 +2671,37 @@ components: type: boolean description: > Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + metadata: + type: object + description: > + Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + sort_by: + type: string + description: > + A sort by clause that is applied to any search query that matches the override rule. + replace_query: + type: string + description: > + Replaces the current search query with this value, when the search query matches the override rule. + filter_curated_hits: + type: boolean + description: > + When set to true, the filter conditions of the query is applied to the curated records as well. + Default: false. + effective_from_ts: + type: integer + description: > + A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + effective_to_ts: + type: integer + description: > + A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + stop_processing: + type: boolean + description: > + When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. + Overrides are processed in the lexical sort order of their id field. + Default: true. SearchOverride: allOf: - $ref: "#/components/schemas/SearchOverrideSchema" @@ -1674,12 +2712,22 @@ components: id: type: string readOnly: true - SearchOverrideRule: + SearchOverrideDeleteResponse: type: object required: - - query - - match + - id + properties: + id: + type: string + description: The id of the override that was deleted + SearchOverrideRule: + type: object properties: + tags: + type: array + description: List of tag values to associate with this override rule. + items: + type: string query: type: string description: Indicates what search queries should be overridden @@ -1692,6 +2740,10 @@ components: enum: - exact - contains + filter_by: + type: string + description: > + Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). SearchOverrideInclude: type: object required: @@ -1735,6 +2787,14 @@ components: description: Array of words that should be considered as synonyms. items: type: string + locale: + type: string + description: Locale for the synonym, leave blank to use the standard tokenizer. + symbols_to_index: + type: array + description: By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. + items: + type: string SearchSynonym: allOf: - $ref: "#/components/schemas/SearchSynonymSchema" @@ -1745,6 +2805,14 @@ components: id: type: string readOnly: true + SearchSynonymDeleteResponse: + type: object + required: + - id + properties: + id: + type: string + description: The id of the synonym that was deleted SearchSynonymsResponse: type: object required: @@ -1762,6 +2830,18 @@ components: properties: ok: type: boolean + SchemaChangeStatus: + type: object + properties: + collection: + type: string + description: Name of the collection being modified + validated_docs: + type: integer + description: Number of documents that have been validated + altered_docs: + type: integer + description: Number of documents that have been altered SuccessStatus: type: object required: @@ -1810,6 +2890,15 @@ components: value_prefix: type: string readOnly: true + ApiKeyDeleteResponse: + type: object + required: + - id + properties: + id: + type: integer + format: int64 + description: The id of the API key that was deleted ApiKeysResponse: type: object required: @@ -1820,24 +2909,6 @@ components: x-go-type: "[]*ApiKey" items: $ref: "#/components/schemas/ApiKey" - ScopedKeyParameters: - type: object - properties: - filter_by: - type: string - expires_at: - type: integer - format: int64 - SnapshotParameters: - type: object - properties: - snapshot_path: - type: string - ErrorResponse: - type: object - properties: - message: - type: string MultiSearchResult: type: object required: @@ -1846,13 +2917,23 @@ components: results: type: array items: - $ref: "#/components/schemas/SearchResult" + $ref: "#/components/schemas/MultiSearchResultItem" + conversation: + $ref: "#/components/schemas/SearchResultConversation" + MultiSearchResultItem: + allOf: + - $ref: "#/components/schemas/SearchResult" + - type: object + properties: + code: + type: integer + description: HTTP error code + format: int64 + error: + type: string + description: Error description SearchParameters: type: object - required: - - q - - query_by - properties: q: description: The query text to search for in the collection. @@ -1865,6 +2946,14 @@ components: against. Multiple fields are separated with a comma. type: string + nl_query: + description: Whether to use natural language processing to parse the query. + type: boolean + + nl_model_id: + description: The ID of the natural language model to use. + type: string + query_by_weights: description: The relative weight to give each `query_by` field when ranking results. @@ -1874,7 +2963,7 @@ components: text_match_type: description: - In a multi-field matching context, this parameter determines how the representative text match + In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. type: string @@ -1887,36 +2976,42 @@ components: infix: description: - If infix index is enabled for this field, infix searching can be done on a per-field - basis by sending a comma separated string parameter called infix to the search query. + If infix index is enabled for this field, infix searching can be done on a per-field + basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default - `always` infix search is performed along with regular search - `fallback` infix search is performed if regular search does not produce results + `always` infix search is performed along with regular search + `fallback` infix search is performed if regular search does not produce results type: string max_extra_prefix: description: - There are also 2 parameters that allow you to control the extent of infix searching - max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before - or after the query that can be present in the token. For example query "K2100" has 2 extra + There are also 2 parameters that allow you to control the extent of infix searching + max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before + or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. type: integer max_extra_suffix: description: - There are also 2 parameters that allow you to control the extent of infix searching - max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before - or after the query that can be present in the token. For example query "K2100" has 2 extra + There are also 2 parameters that allow you to control the extent of infix searching + max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before + or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. type: integer filter_by: description: - Filter conditions for refining youropen api validator search results. Separate + 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 @@ -1963,7 +3058,7 @@ components: limit: description: > - Number of hits to fetch. Can be used as an alternative to the per_page parameter. + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. type: integer @@ -1985,6 +3080,13 @@ components: Default: 3 type: integer + group_missing_values: + description: > + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. + Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. + Default: true + type: boolean + include_fields: description: List of fields from the document to include in the search result type: string @@ -2021,12 +3123,24 @@ components: 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 @@ -2034,12 +3148,35 @@ components: enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 type: integer + drop_tokens_mode: + $ref: "#/components/schemas/DropTokensMode" typo_tokens_threshold: description: > If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 type: integer + enable_typos_for_alpha_numerical_tokens: + type: boolean + description: > + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + + filter_curated_hits: + type: boolean + description: > + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + enable_synonyms: + type: boolean + description: > + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + synonym_prefix: + type: boolean + description: > + Allow synonym resolution on word prefixes in the query. Default: false + synonym_num_typos: + type: integer + description: > + Allow synonym resolution on typo-corrected words in the query. Default: 0 pinned_hits: description: > @@ -2051,7 +3188,7 @@ components: you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based - on rules. Overrides are applied first, followed by `pinned_hits` and + on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. type: string @@ -2066,9 +3203,13 @@ components: finally `hidden_hits`. type: string + override_tags: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + highlight_fields: description: > - A list of custom fields that must be highlighted even if you don't query + A list of custom fields that must be highlighted even if you don't query for them type: string @@ -2083,7 +3224,7 @@ components: pre_segmented_query: description: > You can index content from any logographic language into Typesense if you - are able to segment / split the text into space-separated words yourself + are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same @@ -2100,12 +3241,14 @@ components: If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false type: boolean + default: false prioritize_exact_match: description: > Set this parameter to true to ensure that an exact match is ranked above the others type: boolean + default: true max_candidates: description: > Control the number of words that Typesense considers for typo and prefix searching. @@ -2114,15 +3257,26 @@ components: description: > Make Typesense prioritize documents where the query words appear earlier in the text. type: boolean + default: false + prioritize_num_matching_fields: + description: > + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + enable_typos_for_numerical_tokens: + description: > + Make Typesense disable typos for numerical tokens. + type: boolean + default: true exhaustive_search: description: > - Setting this to true will make Typesense consider all prefixes and typo - corrections of the words in the query without stopping early when enough results are found + Setting this to true will make Typesense consider all prefixes and typo + corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). type: boolean search_cutoff_ms: description: > - Typesense will attempt to return results early if the cutoff time has elapsed. + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. type: integer use_cache: @@ -2131,17 +3285,17 @@ components: type: boolean cache_ttl: description: > - The duration (in seconds) that determines how long the search query is cached. + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. type: integer min_len_1typo: description: > - Minimum word length for 1-typo correction to be applied. + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. type: integer min_len_2typo: description: > - Minimum word length for 2-typo correction to be applied. + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. type: integer vector_query: @@ -2156,6 +3310,36 @@ components: description: > Number of times to retry fetching remote embeddings. type: integer + facet_strategy: + description: > + Choose the underlying faceting strategy used. Comma separated string of allows values: + exhaustive, top_values or automatic (default). + type: string + stopwords: + description: > + Name of the stopwords set to apply for this search, + the keywords present in the set will be removed from the search query. + type: string + facet_return_parent: + description: > + Comma separated string of nested facet fields whose parent object should be returned in facet response. + type: string + voice_query: + description: > + The base64 encoded audio file in 16 khz 16-bit WAV format. + type: string + conversation: + description: > + Enable conversational search. + type: boolean + conversation_model_id: + description: > + The Id of Conversation Model to be used. + type: string + conversation_id: + description: > + The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + type: string MultiSearchParameters: description: > @@ -2195,26 +3379,26 @@ components: infix: description: - If infix index is enabled for this field, infix searching can be done on a per-field - basis by sending a comma separated string parameter called infix to the search query. + If infix index is enabled for this field, infix searching can be done on a per-field + basis by sending a comma separated string parameter called infix to the search query. This parameter can have 3 values; `off` infix search is disabled, which is default - `always` infix search is performed along with regular search - `fallback` infix search is performed if regular search does not produce results + `always` infix search is performed along with regular search + `fallback` infix search is performed if regular search does not produce results type: string max_extra_prefix: description: - There are also 2 parameters that allow you to control the extent of infix searching - max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before - or after the query that can be present in the token. For example query "K2100" has 2 extra + There are also 2 parameters that allow you to control the extent of infix searching + max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before + or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. type: integer max_extra_suffix: description: - There are also 2 parameters that allow you to control the extent of infix searching - max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before - or after the query that can be present in the token. For example query "K2100" has 2 extra + There are also 2 parameters that allow you to control the extent of infix searching + max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before + or after the query that can be present in the token. For example query "K2100" has 2 extra symbols in "6PK2100". By default, any number of prefixes/suffixes can be present for a match. type: integer @@ -2270,7 +3454,7 @@ components: limit: description: > - Number of hits to fetch. Can be used as an alternative to the per_page parameter. + Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. type: integer @@ -2292,6 +3476,13 @@ components: Default: 3 type: integer + group_missing_values: + description: > + Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. + Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. + Default: true + type: boolean + include_fields: description: List of fields from the document to include in the search result type: string @@ -2334,12 +3525,43 @@ components: enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 type: integer + drop_tokens_mode: + $ref: "#/components/schemas/DropTokensMode" typo_tokens_threshold: description: > If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 type: integer + enable_typos_for_alpha_numerical_tokens: + type: boolean + description: > + Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + + filter_curated_hits: + type: boolean + description: > + Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + enable_synonyms: + type: boolean + description: > + If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + + 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: > @@ -2351,7 +3573,7 @@ components: you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based - on rules. Overrides are applied first, followed by `pinned_hits` and + on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. type: string @@ -2366,20 +3588,25 @@ components: finally `hidden_hits`. type: string + override_tags: + description: Comma separated list of tags to trigger the curations rules that match the tags. + type: string + highlight_fields: description: > - A list of custom fields that must be highlighted even if you don't query + A list of custom fields that must be highlighted even if you don't query for them type: string pre_segmented_query: description: > You can index content from any logographic language into Typesense if you - are able to segment / split the text into space-separated words yourself + are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same type: boolean + default: false preset: description: > @@ -2392,21 +3619,42 @@ components: If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false type: boolean + default: false prioritize_exact_match: description: > Set this parameter to true to ensure that an exact match is ranked above the others type: boolean + default: true + + prioritize_token_position: + description: > + Make Typesense prioritize documents where the query words appear earlier in the text. + type: boolean + default: false + + prioritize_num_matching_fields: + description: > + Make Typesense prioritize documents where the query words appear in more number of fields. + type: boolean + default: true + + enable_typos_for_numerical_tokens: + description: > + Make Typesense disable typos for numerical tokens. + type: boolean + default: true + exhaustive_search: description: > - Setting this to true will make Typesense consider all prefixes and typo - corrections of the words in the query without stopping early when enough results are found + Setting this to true will make Typesense consider all prefixes and typo + corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). type: boolean search_cutoff_ms: description: > - Typesense will attempt to return results early if the cutoff time has elapsed. + Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. type: integer use_cache: @@ -2415,17 +3663,17 @@ components: type: boolean cache_ttl: description: > - The duration (in seconds) that determines how long the search query is cached. + The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. type: integer min_len_1typo: description: > - Minimum word length for 1-typo correction to be applied. + Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. type: integer min_len_2typo: description: > - Minimum word length for 2-typo correction to be applied. + Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. type: integer vector_query: @@ -2438,13 +3686,47 @@ components: type: integer remote_embedding_num_tries: description: > - Number of times to retry fetching remote embeddings. - type: integer + 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: @@ -2453,13 +3735,21 @@ components: allOf: - $ref: "#/components/schemas/MultiSearchParameters" - type: object - required: - - collection properties: collection: type: string description: > The collection to search in. + x-typesense-api-key: + type: string + description: A separate search API key for each search within a multi_search request + rerank_hybrid_matches: + type: boolean + description: > + When true, computes both text match and vector distance scores for all matches in hybrid search. + Documents found only through keyword search will get a vector distance score, and + documents found only through vector search will get a text match score. + default: false FacetCounts: type: object properties: @@ -2474,6 +3764,8 @@ components: type: string value: type: string + parent: + type: object field_name: type: string stats: @@ -2493,49 +3785,535 @@ components: avg: type: number format: double - AnalyticsRuleSchema: + 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 - - params + - collection + - event_type properties: name: type: string type: type: string + enum: [popular_queries, nohits_queries, counter, log] + collection: + type: string + event_type: + type: string + rule_tag: + type: string params: - $ref: "#/components/schemas/AnalyticsRuleParameters" - AnalyticsRuleParameters: + type: object + properties: + destination_collection: + type: string + limit: + type: integer + capture_search_requests: + type: boolean + meta_fields: + type: array + items: { type: string } + expand_query: + type: boolean + counter_field: + type: string + weight: + type: integer + AnalyticsRuleUpdate: type: object - required: - - source - - destination - - limit + description: Fields allowed to update on an analytics rule properties: - source: + name: + type: string + rule_tag: + type: string + params: type: object properties: - collections: + destination_collection: + type: string + limit: + type: integer + capture_search_requests: + type: boolean + meta_fields: type: array - items: - type: string - destination: + 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: - collection: + name: type: string - limit: + 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 - AnalyticsRulesRetrieveSchema: + description: Maximum output tokens for GCP Vertex AI + account_id: + type: string + description: Account ID for Cloudflare-specific models + + NLSearchModelCreateSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelBase' + - type: object + properties: + id: + type: string + description: Optional ID for the NL search model + + NLSearchModelSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelCreateSchema' + - type: object + required: + - id + properties: + id: + type: string + description: ID of the NL search model + + NLSearchModelUpdateSchema: + $ref: '#/components/schemas/NLSearchModelCreateSchema' + + NLSearchModelDeleteSchema: + type: object + required: + - id + properties: + id: + type: string + description: ID of the deleted NL search model + + SynonymItemSchema: + type: object + required: + - id + - synonyms + properties: + id: + type: string + description: Unique identifier for the synonym item + synonyms: + type: array + description: Array of words that should be considered as synonyms + items: + type: string + root: + type: string + description: For 1-way synonyms, indicates the root word that words in the synonyms parameter map to + locale: + type: string + description: Locale for the synonym, leave blank to use the standard tokenizer + symbols_to_index: + type: array + description: By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is + items: + type: string + + SynonymSetCreateSchema: + type: object + required: + - items + properties: + items: + type: array + description: Array of synonym items + items: + $ref: "#/components/schemas/SynonymItemSchema" + + SynonymSetSchema: + allOf: + - $ref: "#/components/schemas/SynonymSetCreateSchema" + - type: object + required: + - name + properties: + name: + type: string + description: Name of the synonym set + + SynonymSetsRetrieveSchema: type: object + required: + - synonym_sets properties: - rules: + synonym_sets: type: array + description: Array of synonym sets items: - $ref: "#/components/schemas/AnalyticsRuleSchema" + $ref: "#/components/schemas/SynonymSetSchema" + + SynonymSetRetrieveSchema: + $ref: "#/components/schemas/SynonymSetCreateSchema" + + SynonymSetDeleteSchema: + type: object + required: + - name + properties: + name: + type: string + description: Name of the deleted synonym set + securitySchemes: api_key_header: type: apiKey name: X-TYPESENSE-API-KEY - in: header + in: header \ No newline at end of file diff --git a/preprocessed_openapi.yml b/preprocessed_openapi.yml new file mode 100644 index 0000000..5bbf988 --- /dev/null +++ b/preprocessed_openapi.yml @@ -0,0 +1,4829 @@ +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: curation + description: Hand-curate search results based on conditional business rules + externalDocs: + description: Find out more + url: https://typesense.org/docs/0.23.0/api/#curation +- name: analytics + description: Typesense can aggregate search queries for both analytics purposes and for query suggestions. + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/analytics-query-suggestions.html +- name: keys + description: Manage API Keys with fine-grain access control + externalDocs: + description: Find out more + url: https://typesense.org/docs/0.23.0/api/#api-keys +- name: debug + description: Debugging information +- name: operations + description: Manage Typesense cluster + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/cluster-operations.html +- name: stopwords + description: Manage stopwords sets + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stopwords.html +- name: presets + description: Store and reference search parameters + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/search.html#presets +- name: conversations + description: Conversational Search (RAG) + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/conversational-search-rag.html +- name: synonyms + description: Manage synonyms + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/synonyms.html +- name: stemming + description: Manage stemming dictionaries + externalDocs: + description: Find out more + url: https://typesense.org/docs/28.0/api/stemming.html +- name: nl_search_models + description: Manage NL search models + externalDocs: + description: Find out more + url: https://typesense.org/docs/29.0/api/natural-language-search.html +paths: + /collections: + get: + tags: + - collections + summary: List all collections + description: Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first. + operationId: getCollections + 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' + x-rust-generic-parameter: ' serde::Deserialize<''de> + Serialize>' + x-rust-return-type: models::SearchResult + /collections/{collectionName}/overrides: + get: + tags: + - documents + - curation + summary: List all collection overrides + operationId: getSearchOverrides + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + responses: + '200': + description: List of all search overrides + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverridesResponse' + /collections/{collectionName}/overrides/{overrideId}: + get: + tags: + - documents + - override + summary: Retrieve a single search override + description: Retrieve the details of a search override, given its id. + operationId: getSearchOverride + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: overrideId + in: path + description: The id of the search override + required: true + schema: + type: string + responses: + '200': + description: Search override fetched + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverride' + put: + tags: + - documents + - curation + summary: Create or update an override to promote certain documents over others + description: Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. + operationId: upsertSearchOverride + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: overrideId + in: path + description: The ID of the search override to create/update + required: true + schema: + type: string + requestBody: + description: The search override object to be created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverrideSchema' + required: true + responses: + '200': + description: Created/updated search override + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverride' + '404': + description: Search override not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - documents + - curation + summary: Delete an override associated with a collection + operationId: deleteSearchOverride + parameters: + - name: collectionName + in: path + description: The name of the collection + required: true + schema: + type: string + - name: overrideId + in: path + description: The ID of the search override to delete + required: true + schema: + type: string + responses: + '200': + description: The ID of the deleted search override + content: + application/json: + schema: + $ref: '#/components/schemas/SearchOverrideDeleteResponse' + '404': + description: Search override not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /synonym_sets: + get: + tags: + - synonyms + summary: List all synonym sets + description: Retrieve all synonym sets + operationId: retrieveSynonymSets + responses: + '200': + description: List of all synonym sets + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SynonymSetSchema' + /synonym_sets/{synonymSetName}: + get: + tags: + - synonyms + summary: Retrieve a synonym set + description: Retrieve a specific synonym set by its name + operationId: retrieveSynonymSet + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to retrieve + required: true + schema: + type: string + responses: + '200': + description: Synonym set fetched + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymSetRetrieveSchema' + '404': + description: Synonym set not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + put: + tags: + - synonyms + summary: Create or update a synonym set + description: Create or update a synonym set with the given name + operationId: upsertSynonymSet + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to create/update + required: true + schema: + type: string + requestBody: + description: The synonym set to be created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymSetCreateSchema' + required: true + responses: + '200': + description: Synonym set successfully created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymSetSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - synonyms + summary: Delete a synonym set + description: Delete a specific synonym set by its name + operationId: deleteSynonymSet + parameters: + - name: synonymSetName + in: path + description: The name of the synonym set to delete + required: true + schema: + type: string + responses: + '200': + description: Synonym set successfully deleted + content: + application/json: + schema: + $ref: '#/components/schemas/SynonymSetDeleteSchema' + '404': + description: Synonym set not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /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' + x-supports-plain-text: true + /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' + x-rust-body-is-raw-text: true + x-supports-plain-text: true + /collections/{collectionName}/documents/{documentId}: + get: + tags: + - documents + summary: Retrieve a document + description: Fetch an individual document from a collection by using its ID. + operationId: getDocument + parameters: + - name: collectionName + in: path + description: The name of the collection to search for the document under + required: true + schema: + type: string + - name: documentId + in: path + description: The Document ID + required: true + schema: + type: string + responses: + '200': + description: The document referenced by the ID + content: + application/json: + schema: + type: object + description: Can be any key-value pair + '404': + description: The document or collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + patch: + tags: + - documents + summary: Update a document + description: Update an individual document from a collection by using its ID. The update can be partial. + operationId: updateDocument + parameters: + - name: collectionName + in: path + description: The name of the collection to search for the document under + required: true + schema: + type: string + - name: documentId + in: path + description: The Document ID + required: true + schema: + type: string + - name: dirty_values + in: query + description: Dealing with Dirty Data + schema: + $ref: '#/components/schemas/DirtyValues' + requestBody: + description: The document object with fields to be updated + content: + application/json: + schema: + type: object + description: Can be any key-value pair + x-go-type: interface{} + required: true + responses: + '200': + description: The document referenced by the ID was updated + content: + application/json: + schema: + type: object + description: Can be any key-value pair + '404': + description: The document or collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - documents + summary: Delete a document + description: Delete an individual document from a collection by using its ID. + operationId: deleteDocument + parameters: + - name: collectionName + in: path + description: The name of the collection to search for the document under + required: true + schema: + type: string + - name: documentId + in: path + description: The Document ID + required: true + schema: + type: string + responses: + '200': + description: The document referenced by the ID was deleted + content: + application/json: + schema: + type: object + description: Can be any key-value pair + '404': + description: The document or collection was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /conversations/models: + get: + description: Retrieve all conversation models + operationId: retrieveAllConversationModels + responses: + '200': + content: + application/json: + schema: + items: + $ref: '#/components/schemas/ConversationModelSchema' + type: array + x-go-type: '[]*ConversationModelSchema' + description: List of all conversation models + summary: List all conversation models + tags: + - conversations + post: + summary: Create a conversation model + description: Create a Conversation Model + operationId: createConversationModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelCreateSchema' + required: true + responses: + '201': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: Created Conversation Model + '400': + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: Bad request, see error message for details + tags: + - conversations + /conversations/models/{modelId}: + get: + description: Retrieve a conversation model + operationId: retrieveConversationModel + parameters: + - name: modelId + in: path + description: The id of the conversation model to retrieve + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: A conversation model + summary: Retrieve a conversation model + tags: + - conversations + put: + description: Update a conversation model + operationId: updateConversationModel + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelUpdateSchema' + required: true + parameters: + - name: modelId + in: path + description: The id of the conversation model to update + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: The conversation model was successfully updated + summary: Update a conversation model + tags: + - conversations + delete: + description: Delete a conversation model + operationId: deleteConversationModel + parameters: + - name: modelId + in: path + description: The id of the conversation model to delete + required: true + schema: + type: string + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationModelSchema' + description: The conversation model was successfully deleted + summary: Delete a conversation model + tags: + - conversations + /keys: + get: + tags: + - keys + summary: Retrieve (metadata about) all keys. + operationId: getKeys + responses: + '200': + description: List of all keys + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeysResponse' + post: + tags: + - keys + summary: Create an API Key + description: Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. + operationId: createKey + requestBody: + description: The object that describes API key scope + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeySchema' + responses: + '201': + description: Created API key + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKey' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '409': + description: API key generation conflict + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /keys/{keyId}: + get: + tags: + - keys + summary: Retrieve (metadata about) a key + description: Retrieve (metadata about) a key. Only the key prefix is returned when you retrieve a key. Due to security reasons, only the create endpoint returns the full API key. + operationId: getKey + parameters: + - name: keyId + in: path + description: The ID of the key to retrieve + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: The key referenced by the ID + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKey' + '404': + description: The key was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - keys + summary: Delete an API key given its ID. + operationId: deleteKey + parameters: + - name: keyId + in: path + description: The ID of the key to delete + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: The key referenced by the ID + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeyDeleteResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: Key not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /aliases: + get: + tags: + - collections + summary: List all aliases + description: List all aliases and the corresponding collections that they map to. + operationId: getAliases + responses: + '200': + description: List of all collection aliases + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAliasesResponse' + /aliases/{aliasName}: + put: + tags: + - collections + summary: Create or update a collection alias + description: Create or update a collection alias. An alias is a virtual collection name that points to a real collection. If you're familiar with symbolic links on Linux, it's very similar to that. Aliases are useful when you want to reindex your data in the background on a new collection and switch your application to it without any changes to your code. + operationId: upsertAlias + parameters: + - name: aliasName + in: path + description: The name of the alias to create/update + required: true + schema: + type: string + requestBody: + description: Collection alias to be created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAliasSchema' + responses: + '200': + description: The collection alias was created/updated + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAlias' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: Alias not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - collections + summary: Retrieve an alias + description: Find out which collection an alias points to by fetching it + operationId: getAlias + parameters: + - name: aliasName + in: path + description: The name of the alias to retrieve + required: true + schema: + type: string + responses: + '200': + description: Collection alias fetched + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAlias' + '404': + description: The alias was not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - collections + summary: Delete an alias + operationId: deleteAlias + parameters: + - name: aliasName + in: path + description: The name of the alias to delete + required: true + schema: + type: string + responses: + '200': + description: Collection alias was deleted + content: + application/json: + schema: + $ref: '#/components/schemas/CollectionAlias' + '404': + description: Alias not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /debug: + get: + tags: + - debug + summary: Print debugging information + description: Print debugging information + operationId: debug + responses: + '200': + description: Debugging information + content: + application/json: + schema: + type: object + properties: + version: + type: string + /health: + get: + tags: + - health + summary: Checks if Typesense server is ready to accept requests. + description: Checks if Typesense server is ready to accept requests. + operationId: health + responses: + '200': + description: Search service is ready for requests. + content: + application/json: + schema: + $ref: '#/components/schemas/HealthStatus' + /operations/schema_changes: + get: + tags: + - operations + summary: Get the status of in-progress schema change operations + description: Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. + operationId: getSchemaChanges + responses: + '200': + description: List of schema changes in progress + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SchemaChangeStatus' + /operations/snapshot: + post: + tags: + - operations + summary: Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. + description: Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. + operationId: takeSnapshot + parameters: + - name: snapshot_path + in: query + description: The directory on the server where the snapshot should be saved. + required: true + schema: + type: string + responses: + '201': + description: Snapshot is created. + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + /operations/vote: + post: + tags: + - operations + summary: Triggers a follower node to initiate the raft voting process, which triggers leader re-election. + description: Triggers a follower node to initiate the raft voting process, which triggers leader re-election. The follower node that you run this operation against will become the new leader, once this command succeeds. + operationId: vote + responses: + '200': + description: Re-election is performed. + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + /operations/cache/clear: + post: + tags: + - operations + summary: Clear the cached responses of search requests in the LRU cache. + description: Clear the cached responses of search requests that are sent with `use_cache` parameter in the LRU cache. + operationId: clearCache + responses: + '200': + description: Clear cache succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + /operations/db/compact: + post: + tags: + - operations + summary: Compacting the on-disk database + description: Typesense uses RocksDB to store your documents on the disk. If you do frequent writes or updates, you could benefit from running a compaction of the underlying RocksDB database. This could reduce the size of the database and decrease read latency. While the database will not block during this operation, we recommend running it during off-peak hours. + operationId: compactDb + responses: + '200': + description: Compacting the on-disk database succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + /config: + post: + tags: + - operations + summary: Toggle Slow Request Log + description: Enable logging of requests that take over a defined threshold of time. Default is `-1` which disables slow request logging. Slow requests are logged to the primary log file, with the prefix SLOW REQUEST. + operationId: toggleSlowRequestLog + requestBody: + content: + application/json: + schema: + type: object + properties: + log-slow-requests-time-ms: + type: integer + required: + - log-slow-requests-time-ms + example: | + {"log-slow-requests-time-ms": 2000} + responses: + '200': + description: Compacting the on-disk database succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessStatus' + /multi_search: + post: + operationId: multiSearch + tags: + - documents + summary: send multiple search requests in a single HTTP request + description: This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. + parameters: + - name: 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' + x-rust-return-type: serde_json::Value + /analytics/events: + post: + tags: + - analytics + summary: Create an analytics event + description: Submit a single analytics event. The event must correspond to an existing analytics rule by name. + operationId: createAnalyticsEvent + requestBody: + description: The analytics event to be created + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEvent' + required: true + responses: + '200': + description: Analytics event successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventCreateResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - analytics + summary: Retrieve analytics events + description: Retrieve the most recent events for a user and rule. + operationId: getAnalyticsEvents + parameters: + - name: user_id + in: query + required: true + schema: + type: string + - name: name + in: query + description: Analytics rule name + required: true + schema: + type: string + - name: n + in: query + description: Number of events to return (max 1000) + required: true + schema: + type: integer + responses: + '200': + description: Events fetched + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventsResponse' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /analytics/flush: + post: + tags: + - analytics + summary: Flush in-memory analytics to disk + description: Triggers a flush of analytics data to persistent storage. + operationId: flushAnalytics + responses: + '200': + description: Flush triggered + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsEventCreateResponse' + /analytics/status: + get: + tags: + - analytics + summary: Get analytics subsystem status + description: Returns sizes of internal analytics buffers and queues. + operationId: getAnalyticsStatus + responses: + '200': + description: Status fetched + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsStatus' + /analytics/rules: + post: + tags: + - analytics + summary: Create analytics rule(s) + description: Create one or more analytics rules. You can send a single rule object or an array of rule objects. + operationId: createAnalyticsRule + requestBody: + description: The analytics rule(s) to be created + content: + application/json: + schema: + oneOf: + - $ref: '#/components/schemas/AnalyticsRuleCreate' + - type: array + items: + $ref: '#/components/schemas/AnalyticsRuleCreate' + required: true + responses: + '200': + description: Analytics rule(s) successfully created + content: + application/json: + schema: + oneOf: + - $ref: '#/components/schemas/AnalyticsRule' + - type: array + items: + anyOf: + - $ref: '#/components/schemas/AnalyticsRule' + - type: object + properties: + error: + type: string + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - analytics + summary: Retrieve analytics rules + description: Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. + operationId: retrieveAnalyticsRules + parameters: + - in: query + name: rule_tag + schema: + type: string + required: false + description: Filter rules by rule_tag + responses: + '200': + description: Analytics rules fetched + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/AnalyticsRule' + /analytics/rules/{ruleName}: + put: + tags: + - analytics + summary: Upserts an analytics rule + description: Upserts an analytics rule with the given name. + operationId: upsertAnalyticsRule + parameters: + - in: path + name: ruleName + description: The name of the analytics rule to upsert + schema: + type: string + required: true + requestBody: + description: The Analytics rule to be upserted + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRuleUpdate' + required: true + responses: + '200': + description: Analytics rule successfully upserted + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRule' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - analytics + summary: Retrieves an analytics rule + description: Retrieve the details of an analytics rule, given it's name + operationId: retrieveAnalyticsRule + parameters: + - in: path + name: ruleName + description: The name of the analytics rule to retrieve + schema: + type: string + required: true + responses: + '200': + description: Analytics rule fetched + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRule' + '404': + description: Analytics rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - analytics + summary: Delete an analytics rule + description: Permanently deletes an analytics rule, given it's name + operationId: deleteAnalyticsRule + parameters: + - in: path + name: ruleName + description: The name of the analytics rule to delete + schema: + type: string + required: true + responses: + '200': + description: Analytics rule deleted + content: + application/json: + schema: + $ref: '#/components/schemas/AnalyticsRule' + '404': + description: Analytics rule not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /metrics.json: + get: + tags: + - operations + summary: Get current RAM, CPU, Disk & Network usage metrics. + description: Retrieve the metrics. + operationId: retrieveMetrics + responses: + '200': + description: Metrics fetched. + content: + application/json: + schema: + type: object + /stats.json: + get: + tags: + - operations + summary: Get stats about API endpoints. + description: Retrieve the stats about API endpoints. + operationId: retrieveAPIStats + responses: + '200': + description: Stats fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/APIStatsResponse' + /stopwords: + get: + tags: + - stopwords + summary: Retrieves all stopwords sets. + description: Retrieve the details of all stopwords sets + operationId: retrieveStopwordsSets + responses: + '200': + description: Stopwords sets fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetsRetrieveAllSchema' + /stopwords/{setId}: + put: + tags: + - stopwords + summary: Upserts a stopwords set. + description: When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. + operationId: upsertStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to upsert. + schema: + type: string + required: true + example: countries + requestBody: + description: The stopwords set to upsert. + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetUpsertSchema' + required: true + responses: + '200': + description: Stopwords set successfully upserted. + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetSchema' + '400': + description: Bad request, see error message for details. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + get: + tags: + - stopwords + summary: Retrieves a stopwords set. + description: Retrieve the details of a stopwords set, given it's name. + operationId: retrieveStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to retrieve. + schema: + type: string + required: true + example: countries + responses: + '200': + description: Stopwords set fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/StopwordsSetRetrieveSchema' + '404': + description: Stopwords set not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - stopwords + summary: Delete a stopwords set. + description: Permanently deletes a stopwords set, given it's name. + operationId: deleteStopwordsSet + parameters: + - in: path + name: setId + description: The ID of the stopwords set to delete. + schema: + type: string + required: true + example: countries + responses: + '200': + description: Stopwords set rule deleted. + content: + application/json: + schema: + type: object + properties: + id: + type: string + required: + - id + example: | + {"id": "countries"} + '404': + description: Stopwords set not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /presets: + get: + tags: + - presets + summary: Retrieves all presets. + description: Retrieve the details of all presets + operationId: retrieveAllPresets + responses: + '200': + description: Presets fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetsRetrieveSchema' + /presets/{presetId}: + get: + tags: + - presets + summary: Retrieves a preset. + description: Retrieve the details of a preset, given it's name. + operationId: retrievePreset + parameters: + - in: path + name: presetId + description: The ID of the preset to retrieve. + schema: + type: string + required: true + example: listing_view + responses: + '200': + description: Preset fetched. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetSchema' + '404': + description: Preset not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + put: + tags: + - presets + summary: Upserts a preset. + description: Create or update an existing preset. + operationId: upsertPreset + parameters: + - in: path + name: presetId + description: The name of the preset set to upsert. + schema: + type: string + required: true + example: listing_view + requestBody: + description: The stopwords set to upsert. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetUpsertSchema' + required: true + responses: + '200': + description: Preset successfully upserted. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - presets + summary: Delete a preset. + description: Permanently deletes a preset, given it's name. + operationId: deletePreset + parameters: + - in: path + name: presetId + description: The ID of the preset to delete. + schema: + type: string + required: true + example: listing_view + responses: + '200': + description: Preset deleted. + content: + application/json: + schema: + $ref: '#/components/schemas/PresetDeleteSchema' + '404': + description: Preset not found. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /stemming/dictionaries: + get: + tags: + - stemming + summary: List all stemming dictionaries + description: Retrieve a list of all available stemming dictionaries. + operationId: listStemmingDictionaries + responses: + '200': + description: List of all dictionaries + content: + application/json: + schema: + type: object + properties: + dictionaries: + type: array + items: + type: string + example: + - irregular-plurals + - company-terms + /stemming/dictionaries/{dictionaryId}: + get: + tags: + - stemming + summary: Retrieve a stemming dictionary + description: Fetch details of a specific stemming dictionary. + operationId: getStemmingDictionary + parameters: + - name: dictionaryId + in: path + description: The ID of the dictionary to retrieve + required: true + schema: + type: string + example: irregular-plurals + responses: + '200': + description: Stemming dictionary details + content: + application/json: + schema: + $ref: '#/components/schemas/StemmingDictionary' + '404': + description: Dictionary not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /stemming/dictionaries/import: + post: + tags: + - stemming + summary: Import a stemming dictionary + description: Upload a JSONL file containing word mappings to create or update a stemming dictionary. + operationId: importStemmingDictionary + parameters: + - name: id + in: query + description: The ID to assign to the dictionary + required: true + schema: + type: string + example: irregular-plurals + requestBody: + description: The JSONL file containing word mappings + required: true + content: + application/json: + schema: + type: string + example: | + {"word": "people", "root": "person"} + {"word": "children", "root": "child"} + responses: + '200': + description: Dictionary successfully imported + content: + application/octet-stream: + schema: + type: string + example: | + {"word": "people", "root": "person"} {"word": "children", "root": "child"} + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /nl_search_models: + get: + tags: + - nl_search_models + summary: List all NL search models + description: Retrieve all NL search models. + operationId: retrieveAllNLSearchModels + responses: + '200': + description: List of all NL search models + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/NLSearchModelSchema' + post: + tags: + - nl_search_models + summary: Create a NL search model + description: Create a new NL search model. + operationId: createNLSearchModel + requestBody: + description: The NL search model to be created + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelCreateSchema' + required: true + responses: + '201': + description: NL search model successfully created + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /nl_search_models/{modelId}: + get: + tags: + - nl_search_models + summary: Retrieve a NL search model + description: Retrieve a specific NL search model by its ID. + operationId: retrieveNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to retrieve + required: true + schema: + type: string + responses: + '200': + description: NL search model fetched + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + put: + tags: + - nl_search_models + summary: Update a NL search model + description: Update an existing NL search model. + operationId: updateNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to update + required: true + schema: + type: string + requestBody: + description: The NL search model fields to update + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelUpdateSchema' + required: true + responses: + '200': + description: NL search model successfully updated + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelSchema' + '400': + description: Bad request, see error message for details + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + delete: + tags: + - nl_search_models + summary: Delete a NL search model + description: Delete a specific NL search model by its ID. + operationId: deleteNLSearchModel + parameters: + - name: modelId + in: path + description: The ID of the NL search model to delete + required: true + schema: + type: string + responses: + '200': + description: NL search model successfully deleted + content: + application/json: + schema: + $ref: '#/components/schemas/NLSearchModelDeleteSchema' + '404': + description: NL search model not found + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' +components: + schemas: + CollectionSchema: + required: + - name + - fields + type: object + properties: + name: + type: string + description: Name of the collection + example: companies + fields: + type: array + description: A list of fields for querying, filtering and faceting + example: + - name: num_employees + type: int32 + facet: false + - name: company_name + type: string + facet: false + - name: country + type: string + facet: true + items: + $ref: '#/components/schemas/Field' + default_sorting_field: + type: string + description: The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. + example: num_employees + 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. + x-rust-builder: true + CollectionUpdateSchema: + required: + - fields + type: object + properties: + fields: + type: array + description: A list of fields for querying, filtering and faceting + example: + - name: company_name + type: string + facet: false + - name: num_employees + type: int32 + facet: false + - name: country + type: string + facet: true + items: + $ref: '#/components/schemas/Field' + synonym_sets: + type: array + description: List of synonym set names to associate with this collection + items: + type: string + example: synonym_set_1 + metadata: + type: object + description: | + Optional details about the collection, e.g., when it was created, who created it etc. + CollectionResponse: + allOf: + - $ref: '#/components/schemas/CollectionSchema' + - type: object + required: + - num_documents + - created_at + properties: + num_documents: + type: integer + description: Number of documents in the collection + format: int64 + readOnly: true + created_at: + type: integer + description: Timestamp of when the collection was created (Unix epoch in seconds) + format: int64 + readOnly: true + Field: + required: + - name + - type + type: object + properties: + name: + type: string + example: company_name + type: + type: string + example: string + optional: + type: boolean + example: true + facet: + type: boolean + example: false + index: + type: boolean + example: true + default: true + locale: + type: string + example: el + sort: + type: boolean + example: true + infix: + type: boolean + example: true + default: false + reference: + type: string + description: | + Name of a field in another collection that should be linked to this collection so that it can be joined during query. + num_dim: + type: integer + example: 256 + drop: + type: boolean + example: true + 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 + x-rust-builder: true + 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-rust-type: Option>> + hits: + type: array + description: The documents that matched the search query + items: + $ref: '#/components/schemas/SearchResultHit' + x-rust-type: Option>> + 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' + x-rust-generic-parameter: + 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-rust-type: Vec> + x-rust-generic-parameter: + 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-rust-type: Option + 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-rust-generic-parameter: + SearchHighlight: + type: object + properties: + field: + type: string + example: company_name + snippet: + type: string + description: Present only for (non-array) string fields + example: Stark Industries + snippets: + type: array + description: Present only for (array) string[] fields + example: + - Stark Industries + - Stark Corp + items: + type: string + value: + type: string + description: Full field value with highlighting, present only for (non-array) string fields + example: Stark Industries is a major supplier of space equipment. + values: + type: array + description: Full field value with highlighting, present only for (array) string[] fields + example: + - Stark Industries + - Stark Corp + items: + type: string + indices: + type: array + description: The indices property will be present only for string[] fields and will contain the corresponding indices of the snippets in the search field + example: 1 + items: + type: integer + matched_tokens: + type: array + items: + type: object + x-go-type: interface{} + SearchOverrideSchema: + type: object + required: + - rule + properties: + rule: + $ref: '#/components/schemas/SearchOverrideRule' + includes: + type: array + description: List of document `id`s that should be included in the search results with their corresponding `position`s. + items: + $ref: '#/components/schemas/SearchOverrideInclude' + excludes: + type: array + description: List of document `id`s that should be excluded from the search results. + items: + $ref: '#/components/schemas/SearchOverrideExclude' + filter_by: + type: string + description: | + A filter by clause that is applied to any search query that matches the override rule. + remove_matched_tokens: + type: boolean + description: | + Indicates whether search query tokens that exist in the override's rule should be removed from the search query. + metadata: + type: object + description: | + Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + sort_by: + type: string + description: | + A sort by clause that is applied to any search query that matches the override rule. + replace_query: + type: string + description: | + Replaces the current search query with this value, when the search query matches the override rule. + filter_curated_hits: + type: boolean + description: | + When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + effective_from_ts: + type: integer + description: | + A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + effective_to_ts: + type: integer + description: | + A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + stop_processing: + type: boolean + description: | + When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + SearchOverride: + allOf: + - $ref: '#/components/schemas/SearchOverrideSchema' + - type: object + required: + - id + properties: + id: + type: string + readOnly: true + SearchOverrideDeleteResponse: + type: object + required: + - id + properties: + id: + type: string + description: The id of the override that was deleted + SearchOverrideRule: + type: object + properties: + tags: + type: array + description: List of tag values to associate with this override rule. + items: + type: string + query: + type: string + description: Indicates what search queries should be overridden + match: + type: string + description: | + Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. + enum: + - exact + - contains + filter_by: + type: string + description: | + Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). + SearchOverrideInclude: + type: object + required: + - id + - position + properties: + id: + type: string + description: document id that should be included + position: + type: integer + description: position number where document should be included in the search results + SearchOverrideExclude: + type: object + required: + - id + properties: + id: + type: string + description: document id that should be excluded from the search results. + SearchOverridesResponse: + type: object + required: + - overrides + properties: + overrides: + type: array + x-go-type: '[]*SearchOverride' + items: + $ref: '#/components/schemas/SearchOverride' + SearchSynonymSchema: + type: object + required: + - synonyms + properties: + root: + type: string + description: For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. + synonyms: + type: array + description: Array of words that should be considered as synonyms. + items: + type: string + locale: + type: string + description: Locale for the synonym, leave blank to use the standard tokenizer. + symbols_to_index: + type: array + description: By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. + items: + type: string + SearchSynonym: + allOf: + - $ref: '#/components/schemas/SearchSynonymSchema' + - type: object + required: + - id + properties: + id: + type: string + readOnly: true + SearchSynonymDeleteResponse: + type: object + required: + - id + properties: + id: + type: string + description: The id of the synonym that was deleted + SearchSynonymsResponse: + type: object + required: + - synonyms + properties: + synonyms: + type: array + x-go-type: '[]*SearchSynonym' + items: + $ref: '#/components/schemas/SearchSynonym' + HealthStatus: + type: object + required: + - ok + properties: + ok: + type: boolean + SchemaChangeStatus: + type: object + properties: + collection: + type: string + description: Name of the collection being modified + validated_docs: + type: integer + description: Number of documents that have been validated + altered_docs: + type: integer + description: Number of documents that have been altered + SuccessStatus: + type: object + required: + - success + properties: + success: + type: boolean + ApiResponse: + type: object + required: + - message + properties: + message: + type: string + ApiKeySchema: + type: object + required: + - actions + - collections + - description + properties: + value: + type: string + description: + type: string + actions: + type: array + items: + type: string + collections: + type: array + items: + type: string + expires_at: + type: integer + format: int64 + ApiKey: + allOf: + - $ref: '#/components/schemas/ApiKeySchema' + - type: object + properties: + id: + type: integer + format: int64 + readOnly: true + value_prefix: + type: string + readOnly: true + ApiKeyDeleteResponse: + type: object + required: + - id + properties: + id: + type: integer + format: int64 + description: The id of the API key that was deleted + ApiKeysResponse: + type: object + required: + - keys + properties: + keys: + type: array + x-go-type: '[]*ApiKey' + items: + $ref: '#/components/schemas/ApiKey' + MultiSearchResult: + type: object + required: + - results + properties: + results: + type: array + items: + $ref: '#/components/schemas/MultiSearchResultItem' + x-rust-type: Vec> + conversation: + $ref: '#/components/schemas/SearchResultConversation' + x-rust-generic-parameter: + 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-rust-generic-parameter: + 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 + x-rust-builder: true + 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 + x-rust-builder: true + 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 + x-rust-builder: true + FacetCounts: + type: object + properties: + counts: + type: array + items: + type: object + properties: + count: + type: integer + highlighted: + type: string + value: + type: string + parent: + type: object + field_name: + type: string + stats: + type: object + properties: + max: + type: number + format: double + min: + type: number + format: double + sum: + type: number + format: double + total_values: + type: integer + avg: + type: number + format: double + AnalyticsEventCreateResponse: + type: object + required: + - ok + properties: + ok: + type: boolean + AnalyticsEvent: + type: object + required: + - name + - event_type + - data + properties: + name: + type: string + description: Name of the analytics rule this event corresponds to + event_type: + type: string + description: Type of event (e.g., click, conversion, query, visit) + data: + type: object + description: Event payload + properties: + user_id: + type: string + doc_id: + type: string + doc_ids: + type: array + items: + type: string + q: + type: string + analytics_tag: + type: string + AnalyticsEventsResponse: + type: object + required: + - events + properties: + events: + type: array + items: + type: object + properties: + name: + type: string + event_type: + type: string + collection: + type: string + timestamp: + type: integer + format: int64 + user_id: + type: string + doc_id: + type: string + doc_ids: + type: array + items: + type: string + query: + type: string + AnalyticsRuleCreate: + type: object + required: + - name + - type + - collection + - event_type + properties: + name: + type: string + type: + type: string + enum: + - popular_queries + - nohits_queries + - counter + - log + collection: + type: string + event_type: + type: string + rule_tag: + type: string + params: + type: object + properties: + destination_collection: + type: string + limit: + type: integer + capture_search_requests: + type: boolean + meta_fields: + type: array + items: + type: string + expand_query: + type: boolean + counter_field: + type: string + weight: + type: integer + AnalyticsRuleUpdate: + type: object + description: Fields allowed to update on an analytics rule + properties: + name: + type: string + rule_tag: + type: string + params: + type: object + properties: + destination_collection: + type: string + limit: + type: integer + capture_search_requests: + type: boolean + meta_fields: + type: array + items: + type: string + expand_query: + type: boolean + counter_field: + type: string + weight: + type: integer + AnalyticsRule: + allOf: + - $ref: '#/components/schemas/AnalyticsRuleCreate' + - type: object + AnalyticsStatus: + type: object + properties: + popular_prefix_queries: + type: integer + nohits_prefix_queries: + type: integer + log_prefix_queries: + type: integer + query_log_events: + type: integer + query_counter_events: + type: integer + doc_log_events: + type: integer + doc_counter_events: + type: integer + APIStatsResponse: + type: object + properties: + delete_latency_ms: + type: number + format: double + delete_requests_per_second: + type: number + format: double + import_latency_ms: + type: number + format: double + import_requests_per_second: + type: number + format: double + latency_ms: + type: object + x-go-type: map[string]float64 + overloaded_requests_per_second: + type: number + format: double + pending_write_batches: + type: number + format: double + requests_per_second: + type: object + x-go-type: map[string]float64 + search_latency_ms: + type: number + format: double + search_requests_per_second: + type: number + format: double + total_requests_per_second: + type: number + format: double + write_latency_ms: + type: number + format: double + write_requests_per_second: + type: number + format: double + StopwordsSetUpsertSchema: + type: object + properties: + stopwords: + type: array + items: + type: string + locale: + type: string + required: + - stopwords + example: | + {"stopwords": ["Germany", "France", "Italy"], "locale": "en"} + StopwordsSetSchema: + type: object + properties: + id: + type: string + stopwords: + type: array + items: + type: string + locale: + type: string + required: + - id + - stopwords + example: | + {"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"} + StopwordsSetRetrieveSchema: + type: object + properties: + stopwords: + $ref: '#/components/schemas/StopwordsSetSchema' + required: + - stopwords + example: | + {"stopwords": {"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"}} + StopwordsSetsRetrieveAllSchema: + type: object + properties: + stopwords: + type: array + items: + $ref: '#/components/schemas/StopwordsSetSchema' + required: + - stopwords + example: | + {"stopwords": [{"id": "countries", "stopwords": ["Germany", "France", "Italy"], "locale": "en"}]} + PresetUpsertSchema: + properties: + value: + oneOf: + - $ref: '#/components/schemas/SearchParameters' + - $ref: '#/components/schemas/MultiSearchSearchesParameter' + required: + - value + PresetSchema: + allOf: + - $ref: '#/components/schemas/PresetUpsertSchema' + - type: object + required: + - name + properties: + name: + type: string + PresetsRetrieveSchema: + type: object + required: + - presets + properties: + presets: + type: array + items: + $ref: '#/components/schemas/PresetSchema' + x-go-type: '[]*PresetSchema' + PresetDeleteSchema: + type: object + required: + - name + properties: + name: + type: string + DirtyValues: + type: string + enum: + - coerce_or_reject + - coerce_or_drop + - drop + - reject + IndexAction: + type: string + enum: + - create + - update + - upsert + - emplace + DropTokensMode: + type: string + enum: + - right_to_left + - left_to_right + - both_sides:3 + description: | + Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries up to 3 tokens (words) in length, this mode will drop tokens from both sides and exhaustively rank all matching results. If query length is greater than 3 words, Typesense will just fallback to default behavior of right_to_left + ConversationModelCreateSchema: + required: + - model_name + - max_bytes + allOf: + - $ref: '#/components/schemas/ConversationModelUpdateSchema' + - type: object + required: + - model_name + - max_bytes + - history_collection + properties: + model_name: + description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM + type: string + max_bytes: + description: | + The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + type: integer + history_collection: + type: string + description: Typesense collection that stores the historical conversations + ConversationModelUpdateSchema: + type: object + properties: + id: + type: string + description: An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + model_name: + description: Name of the LLM model offered by OpenAI, Cloudflare or vLLM + type: string + api_key: + description: The LLM service's API Key + type: string + history_collection: + type: string + description: Typesense collection that stores the historical conversations + account_id: + description: LLM service's account ID (only applicable for Cloudflare) + type: string + system_prompt: + description: The system prompt that contains special instructions to the LLM + type: string + ttl: + type: integer + description: | + Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + max_bytes: + description: | + The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + type: integer + vllm_url: + description: URL of vLLM service + type: string + ConversationModelSchema: + allOf: + - $ref: '#/components/schemas/ConversationModelCreateSchema' + - type: object + required: + - id + properties: + id: + type: string + description: An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + StemmingDictionary: + type: object + required: + - id + - words + properties: + id: + type: string + description: Unique identifier for the dictionary + example: irregular-plurals + words: + type: array + description: List of word mappings in the dictionary + items: + type: object + required: + - word + - root + properties: + word: + type: string + description: The word form to be stemmed + example: people + root: + type: string + description: The root form of the word + example: person + NLSearchModelBase: + type: object + properties: + model_name: + type: string + description: Name of the NL model to use + api_key: + type: string + description: API key for the NL model service + api_url: + type: string + description: Custom API URL for the NL model service + max_bytes: + type: integer + description: Maximum number of bytes to process + temperature: + type: number + description: Temperature parameter for the NL model + system_prompt: + type: string + description: System prompt for the NL model + top_p: + type: number + description: Top-p parameter for the NL model (Google-specific) + top_k: + type: integer + description: Top-k parameter for the NL model (Google-specific) + stop_sequences: + type: array + items: + type: string + description: Stop sequences for the NL model (Google-specific) + api_version: + type: string + description: API version for the NL model service + project_id: + type: string + description: Project ID for GCP Vertex AI + access_token: + type: string + description: Access token for GCP Vertex AI + refresh_token: + type: string + description: Refresh token for GCP Vertex AI + client_id: + type: string + description: Client ID for GCP Vertex AI + client_secret: + type: string + description: Client secret for GCP Vertex AI + region: + type: string + description: Region for GCP Vertex AI + max_output_tokens: + type: integer + description: Maximum output tokens for GCP Vertex AI + account_id: + type: string + description: Account ID for Cloudflare-specific models + NLSearchModelCreateSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelBase' + - type: object + properties: + id: + type: string + description: Optional ID for the NL search model + NLSearchModelSchema: + allOf: + - $ref: '#/components/schemas/NLSearchModelCreateSchema' + - type: object + required: + - id + properties: + id: + type: string + description: ID of the NL search model + NLSearchModelUpdateSchema: + $ref: '#/components/schemas/NLSearchModelCreateSchema' + NLSearchModelDeleteSchema: + type: object + required: + - id + properties: + id: + type: string + description: ID of the deleted NL search model + SynonymItemSchema: + type: object + required: + - id + - synonyms + properties: + id: + type: string + description: Unique identifier for the synonym item + synonyms: + type: array + description: Array of words that should be considered as synonyms + items: + type: string + root: + type: string + description: For 1-way synonyms, indicates the root word that words in the synonyms parameter map to + locale: + type: string + description: Locale for the synonym, leave blank to use the standard tokenizer + symbols_to_index: + type: array + description: By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is + items: + type: string + SynonymSetCreateSchema: + type: object + required: + - items + properties: + items: + type: array + description: Array of synonym items + items: + $ref: '#/components/schemas/SynonymItemSchema' + SynonymSetSchema: + allOf: + - $ref: '#/components/schemas/SynonymSetCreateSchema' + - type: object + required: + - name + properties: + name: + type: string + description: Name of the synonym set + SynonymSetsRetrieveSchema: + type: object + required: + - synonym_sets + properties: + synonym_sets: + type: array + description: Array of synonym sets + items: + $ref: '#/components/schemas/SynonymSetSchema' + SynonymSetRetrieveSchema: + $ref: '#/components/schemas/SynonymSetCreateSchema' + SynonymSetDeleteSchema: + type: object + required: + - name + properties: + name: + type: string + description: Name of the deleted synonym set + 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 diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..c3c8c37 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +imports_granularity = "Crate" diff --git a/typesense/Cargo.toml b/typesense/Cargo.toml index f1a0491..b25914f 100644 --- a/typesense/Cargo.toml +++ b/typesense/Cargo.toml @@ -9,7 +9,6 @@ description = "Client for typesense" [features] default = ["derive"] -tokio_test = [] # Provide derive(Typesense) macro. derive = ["typesense_derive"] @@ -18,25 +17,45 @@ derive = ["typesense_derive"] crate-type = ["cdylib", "rlib"] [dependencies] -anyhow = "1.0" -base64 = "0.22" -hmac = "0.12" -serde = { version = "1", features = ["derive"] } -serde_json = "1.0" -sha2 = "0.10" -typesense_derive = { workspace = true, optional = true } typesense_codegen = { workspace = true } +typesense_derive = { workspace = true, optional = true } +anyhow = { workspace = true } +base64 = { workspace = true } +bon = { workspace = true } +debug_unsafe = { workspace = true } +hmac = { workspace = true } +reqwest-retry = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +sha2 = { workspace = true } +thiserror = { workspace = true } +web-time = { workspace = true } # required for wasm32 target + +# native-only dependencies +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +reqwest = { version = "0.12", features = ["json"] } +reqwest-middleware = { version = "0.4.2"} + +# wasm deps +[target.'cfg(target_arch = "wasm32")'.dependencies] +# IMPORTANT: disable default features to avoid hyper/tokio/mio +reqwest = { version = "0.12", default-features = false, features = ["json"] } [dev-dependencies] dotenvy = "0.15" +nanoid = "0.4" trybuild = "1.0.42" +# native-only dev deps [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] tokio = { version = "1.5", features = ["macros", "rt", "rt-multi-thread"] } +wiremock = "0.6" +# wasm test deps [target.'cfg(target_arch = "wasm32")'.dev-dependencies] console_error_panic_hook = "0.1.6" wasm-bindgen = "0.2" +wasm-bindgen-futures = "0.4.50" wasm-bindgen-test = "0.3.23" [[test]] @@ -45,5 +64,5 @@ path = "tests/derive/lib.rs" required-features = ["derive"] [[test]] -name = "api_tests" -path = "tests/api/lib.rs" +name = "client" +path = "tests/client/mod.rs" \ No newline at end of file diff --git a/typesense/src/client/collection/document.rs b/typesense/src/client/collection/document.rs new file mode 100644 index 0000000..1398d60 --- /dev/null +++ b/typesense/src/client/collection/document.rs @@ -0,0 +1,134 @@ +//! Provides access to API endpoints for a single document within a Typesense collection. +//! +//! An instance of `Document` is scoped to a specific document and is created +//! via a parent `Collection` struct, for example: +//! `client.collection::().document("123")` + +use crate::{Client, Error, execute_wrapper}; +use serde::{Serialize, de::DeserializeOwned}; +use typesense_codegen::apis::documents_api; + +/// Provides methods for interacting with a single document within a specific Typesense collection. +/// +/// This struct is created by calling a method like `client.collection_schemaless("collection_name").document("document_id")` +/// or `client.collection::().document("document_id")`. +/// The generic `D` represents the shape of the document and must implement `Serialize` and `DeserializeOwned`. +/// If `D` is not specified, it defaults to `serde_json::Value` for schemaless interactions. +pub struct Document<'c, 'n, D = serde_json::Value> +where + D: DeserializeOwned + Serialize, +{ + client: &'c Client, + collection_name: &'n str, + document_id: String, + _phantom: std::marker::PhantomData, +} + +impl<'c, 'n, D> Document<'c, 'n, D> +where + D: DeserializeOwned + Serialize, +{ + /// Creates a new `Document` instance for a specific document ID. + #[inline] + pub(super) fn new(client: &'c Client, collection_name: &'n str, document_id: String) -> Self { + Self { + client, + collection_name, + document_id, + _phantom: std::marker::PhantomData, + } + } + + /// Fetches this individual document from the collection and deserializes it into `D`. + /// + /// # Returns + /// A `Result` containing the strongly-typed document `D` if successful. + pub async fn retrieve(&self) -> Result> { + let params = documents_api::GetDocumentParams { + collection_name: self.collection_name.to_owned(), + document_id: self.document_id.to_owned(), + }; + + let result_value = execute_wrapper!(self, documents_api::get_document, params)?; + + // Deserialize the raw JSON value into the user's type T. + serde_json::from_value(result_value).map_err(Error::from) + } + + /// Updates this individual document. The update can be partial. + /// The updated full document is returned. + /// + /// # Arguments + /// * `partial_document` - A serializable struct or a `serde_json::Value` containing the fields to update. For example: `serde_json::json!({ "in_stock": false })`. + /// * `params` - An optional `DocumentIndexParameters` struct to specify additional parameters, such as `dirty_values` which determines what Typesense should do when the type of a particular field being indexed does not match the previously inferred type for that field, or the one defined in the collection's schema. + /// + /// # Returns + /// A `Result` containing the full, updated document deserialized into `D`. + /// + /// # Example + /// ```no_run + /// # use serde::{Serialize, Deserialize}; + /// # use typesense::{Client, models}; + /// # use reqwest::Url; + /// # #[derive(Serialize, Deserialize)] + /// # struct Book { id: String, title: String, pages: i32 } + /// # + /// # async fn run() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// let book_update = serde_json::json!({ "pages": 654 }); + /// + /// // Simple update + /// let updated_book = client.collection_named::("books").document("123") + /// .update(&book_update, None) + /// .await?; + /// + /// // Update with additional parameters + /// let params = models::DocumentIndexParameters { + /// dirty_values: Some(models::DirtyValues::CoerceOrReject), + /// }; + /// let updated_book_with_params = client.collection_named::("books").document("124") + /// .update(&book_update, Some(params)) + /// .await?; + /// # + /// # Ok(()) + /// # } + /// ``` + pub async fn update( + &self, + partial_document: U, + params: Option, + ) -> Result> { + let params = documents_api::UpdateDocumentParams { + collection_name: self.collection_name.to_owned(), + document_id: self.document_id.to_owned(), + body: serde_json::to_value(partial_document)?, + dirty_values: params.and_then(|d| d.dirty_values), + }; + + let result_value = execute_wrapper!(self, documents_api::update_document, params)?; + + // Deserialize the raw JSON value of the updated document into T. + serde_json::from_value(result_value).map_err(Error::from) + } + + /// Deletes this individual document from the collection. + /// The deleted document is returned. + /// + /// # Returns + /// A `Result` containing the deleted document deserialized into `D`. + pub async fn delete(&self) -> Result> { + let params = documents_api::DeleteDocumentParams { + collection_name: self.collection_name.to_owned(), + document_id: self.document_id.to_owned(), + }; + + let result_value = execute_wrapper!(self, documents_api::delete_document, params)?; + + // Deserialize the raw JSON value of the deleted document into T. + serde_json::from_value(result_value).map_err(Error::from) + } +} diff --git a/typesense/src/client/collection/documents.rs b/typesense/src/client/collection/documents.rs new file mode 100644 index 0000000..c2c5d7d --- /dev/null +++ b/typesense/src/client/collection/documents.rs @@ -0,0 +1,273 @@ +//! Provides access to the document, search, and override-related API endpoints. +//! +//! An instance of `Documents` is scoped to a specific collection and is created +//! via the main `client.collection_schemaless("collection_name").documents()` method or +//! `client.collection_named::("...").documents()`. + +use crate::{ + Client, Error, execute_wrapper, + models::{DocumentIndexParameters, SearchResult}, +}; +use serde::{Serialize, de::DeserializeOwned}; +use typesense_codegen::{ + apis::documents_api, + models::{ + self as raw_models, DeleteDocumentsParameters, ExportDocumentsParameters, + ImportDocumentsParameters, UpdateDocumentsParameters, + }, +}; +/// Provides methods for interacting with documents within a specific Typesense collection. +/// +/// This struct is generic over the document type `D`. If created via `client.collection_schemaless(...)`, +/// `D` defaults to `serde_json::Value`. If created via `client.collection_named::(...)`, +/// `D` will be `MyType`. +pub struct Documents<'c, 'n, D = serde_json::Value> +where + D: DeserializeOwned + Serialize, +{ + client: &'c Client, + collection_name: &'n str, + _phantom: std::marker::PhantomData, +} + +impl<'c, 'n, D> Documents<'c, 'n, D> +where + D: DeserializeOwned + Serialize, +{ + /// Creates a new `Documents` instance. + #[inline] + pub(super) fn new(client: &'c Client, collection_name: &'n str) -> Self { + Self { + client, + collection_name, + _phantom: std::marker::PhantomData, + } + } + + /// Indexes a document in the collection. + /// # Arguments + /// * `document` - A `serde_json::Value` representing the document. + /// * `action` - The indexing action to perform (e.g., "create", "upsert"). + async fn index( + &self, + document: serde_json::Value, + action: &str, + params: Option, + ) -> Result> { + let params = documents_api::IndexDocumentParams { + collection_name: self.collection_name.to_owned(), + body: document, + action: Some(action.to_owned()), + dirty_values: params.and_then(|d| d.dirty_values), // Or expose this as an argument if needed + }; + execute_wrapper!(self, documents_api::index_document, params) + } + + /// Creates a new document in the collection. + /// + /// Fails if a document with the same ID already exists. If the document has an `id` field + /// of type `string`, it will be used as the document's ID. Otherwise, Typesense will + /// auto-generate an ID. The newly indexed document is returned. + /// + /// # Arguments + /// * `document` - A serializable struct or a `serde_json::Value` representing the document to create. + /// * `params` - Optional parameters like `dirty_values`. + pub async fn create( + &self, + document: U, + params: Option, + ) -> Result> { + let doc_value = serde_json::to_value(document)?; + let result_value = self.index(doc_value, "create", params).await?; + serde_json::from_value(result_value).map_err(Error::from) + } + + /// Creates a new document or updates an existing one if an ID match is found. + /// + /// This method requires the full document to be sent. For partial updates, use + /// `collection().document("...").update()`. The indexed document is returned. + /// + /// # Arguments + /// * `document` - A serializable struct or a `serde_json::Value` representing the document to upsert. + /// * `params` - Optional parameters like `dirty_values`. + pub async fn upsert( + &self, + document: U, + params: Option, + ) -> Result> { + let doc_value = serde_json::to_value(document)?; + let result_value = self.index(doc_value, "upsert", params).await?; + serde_json::from_value(result_value).map_err(Error::from) + } + + // --- Bulk Operation Methods --- + + /// Imports a batch of documents in JSONL format. + /// + /// The documents to be imported must be formatted as a newline-delimited JSON string. + /// + /// # Arguments + /// * `documents_jsonl` - A string containing the documents in JSONL format. + /// * `params` - An `ImportDocumentsParameters` struct containing options like `action` and `batch_size`. + pub async fn import_jsonl( + &self, + documents_jsonl: String, + params: ImportDocumentsParameters, + ) -> Result> { + let params = documents_api::ImportDocumentsParams { + body: documents_jsonl, + collection_name: self.collection_name.to_owned(), + + action: params.action, + batch_size: params.batch_size, + dirty_values: params.dirty_values, + remote_embedding_batch_size: params.remote_embedding_batch_size, + return_doc: params.return_doc, + return_id: params.return_id, + }; + execute_wrapper!(self, documents_api::import_documents, params) + } + + /// Exports all documents in a collection in JSONL format. + /// + /// # Arguments + /// * `params` - An `ExportDocumentsParameters` struct containing options like `filter_by` and `include_fields`. + pub async fn export( + &self, + params: ExportDocumentsParameters, + ) -> Result> { + let params = documents_api::ExportDocumentsParams { + collection_name: self.collection_name.to_owned(), + exclude_fields: params.exclude_fields, + filter_by: params.filter_by, + include_fields: params.include_fields, + }; + execute_wrapper!(self, documents_api::export_documents, params) + } + + /// Deletes a batch of documents matching a specific filter condition. + /// + /// # Arguments + /// * `params` - A `DeleteDocumentsParameters` describing the conditions for deleting documents. + pub async fn delete( + &self, + params: DeleteDocumentsParameters, + ) -> Result> + { + let params = documents_api::DeleteDocumentsParams { + collection_name: self.collection_name.to_owned(), + filter_by: Some(params.filter_by), + batch_size: params.batch_size, + ignore_not_found: params.ignore_not_found, + truncate: params.truncate, + }; + execute_wrapper!(self, documents_api::delete_documents, params) + } + + /// Updates a batch of documents matching a specific filter condition. + /// + /// # Arguments + /// * `document` - A serializable struct or a `serde_json::Value` containing the fields to update. + /// * `params` - A `UpdateDocumentsParameters` describing the conditions for updating documents. + pub async fn update( + &self, + document: U, + params: UpdateDocumentsParameters, + ) -> Result> + { + let params = documents_api::UpdateDocumentsParams { + collection_name: self.collection_name.to_owned(), + filter_by: params.filter_by, + body: serde_json::to_value(document)?, + }; + execute_wrapper!(self, documents_api::update_documents, params) + } + + /// Searches for documents in the collection that match the given criteria. + /// The search results will have their `document` field deserialized into type `D`. + /// + /// # Arguments + /// * `params` - A `SearchParameters` struct containing all search parameters. + pub async fn search( + &self, + params: raw_models::SearchParameters, + ) -> Result, Error> { + let search_params = documents_api::SearchCollectionParams { + collection_name: self.collection_name.to_owned(), + + // Map all corresponding fields directly. + cache_ttl: params.cache_ttl, + conversation: params.conversation, + conversation_id: params.conversation_id, + conversation_model_id: params.conversation_model_id, + drop_tokens_mode: params.drop_tokens_mode, + drop_tokens_threshold: params.drop_tokens_threshold, + enable_highlight_v1: params.enable_highlight_v1, + enable_overrides: params.enable_overrides, + enable_synonyms: params.enable_synonyms, + enable_typos_for_alpha_numerical_tokens: params.enable_typos_for_alpha_numerical_tokens, + enable_typos_for_numerical_tokens: params.enable_typos_for_numerical_tokens, + exclude_fields: params.exclude_fields, + exhaustive_search: params.exhaustive_search, + facet_by: params.facet_by, + facet_query: params.facet_query, + facet_return_parent: params.facet_return_parent, + facet_strategy: params.facet_strategy, + filter_by: params.filter_by, + filter_curated_hits: params.filter_curated_hits, + group_by: params.group_by, + group_limit: params.group_limit, + group_missing_values: params.group_missing_values, + hidden_hits: params.hidden_hits, + highlight_affix_num_tokens: params.highlight_affix_num_tokens, + highlight_end_tag: params.highlight_end_tag, + highlight_fields: params.highlight_fields, + highlight_full_fields: params.highlight_full_fields, + highlight_start_tag: params.highlight_start_tag, + include_fields: params.include_fields, + infix: params.infix, + limit: params.limit, + max_candidates: params.max_candidates, + max_extra_prefix: params.max_extra_prefix, + max_extra_suffix: params.max_extra_suffix, + max_facet_values: params.max_facet_values, + max_filter_by_candidates: params.max_filter_by_candidates, + min_len_1typo: params.min_len_1typo, + min_len_2typo: params.min_len_2typo, + num_typos: params.num_typos, + offset: params.offset, + override_tags: params.override_tags, + page: params.page, + per_page: params.per_page, + pinned_hits: params.pinned_hits, + pre_segmented_query: params.pre_segmented_query, + prefix: params.prefix, + preset: params.preset, + prioritize_exact_match: params.prioritize_exact_match, + prioritize_num_matching_fields: params.prioritize_num_matching_fields, + prioritize_token_position: params.prioritize_token_position, + q: params.q, + query_by: params.query_by, + query_by_weights: params.query_by_weights, + remote_embedding_num_tries: params.remote_embedding_num_tries, + remote_embedding_timeout_ms: params.remote_embedding_timeout_ms, + search_cutoff_ms: params.search_cutoff_ms, + snippet_threshold: params.snippet_threshold, + sort_by: params.sort_by, + split_join_tokens: params.split_join_tokens, + stopwords: params.stopwords, + synonym_num_typos: params.synonym_num_typos, + synonym_prefix: params.synonym_prefix, + text_match_type: params.text_match_type, + typo_tokens_threshold: params.typo_tokens_threshold, + use_cache: params.use_cache, + vector_query: params.vector_query, + voice_query: params.voice_query, + nl_model_id: params.nl_model_id, + nl_query: params.nl_query, + enable_analytics: params.enable_analytics, + synonym_sets: params.synonym_sets, + }; + execute_wrapper!(self, documents_api::search_collection, search_params) + } +} diff --git a/typesense/src/client/collection/mod.rs b/typesense/src/client/collection/mod.rs new file mode 100644 index 0000000..ba06950 --- /dev/null +++ b/typesense/src/client/collection/mod.rs @@ -0,0 +1,87 @@ +//! Provides access to the collection and alias-related API endpoints. +//! +//! A `Collections` instance is created via the main `client.collections()` method. + +mod document; +mod documents; +use crate::{Client, Error, execute_wrapper}; + +use serde::{Serialize, de::DeserializeOwned}; +use typesense_codegen::{apis::collections_api, models}; + +/// Provides methods for interacting with a Typesense collection. +/// +/// This struct is created by calling `client.collection()`. +pub struct Collection<'c, 'n, D = serde_json::Value> +where + D: DeserializeOwned + Serialize, +{ + client: &'c Client, + collection_name: &'n str, + _phantom: std::marker::PhantomData, +} + +impl<'c, 'n, D> Collection<'c, 'n, D> +where + D: DeserializeOwned + Serialize, +{ + /// Creates a new `Collection` instance. + #[inline] + pub(super) fn new(client: &'c Client, collection_name: &'n str) -> Self { + Self { + client, + collection_name, + _phantom: std::marker::PhantomData, + } + } + + /// Provides access to the document-related API endpoints for a specific collection. + #[inline] + pub fn documents(&self) -> documents::Documents<'c, 'n, D> { + documents::Documents::new(self.client, self.collection_name) + } + + /// Provides access to the API endpoints for a single document within a Typesense collection. + #[inline] + pub fn document(&self, document_id: impl Into) -> document::Document<'c, 'n, D> { + document::Document::new(self.client, self.collection_name, document_id.into()) + } + + /// Retrieves the details of a collection, given its name. + #[inline] + pub async fn retrieve( + &self, + ) -> Result> { + let params = collections_api::GetCollectionParams { + collection_name: self.collection_name.to_owned(), + }; + execute_wrapper!(self, collections_api::get_collection, params) + } + + /// Permanently drops a collection. + #[inline] + pub async fn delete( + &self, + ) -> Result> { + let params = collections_api::DeleteCollectionParams { + collection_name: self.collection_name.to_owned(), + }; + execute_wrapper!(self, collections_api::delete_collection, params) + } + + /// Updates a collection's schema to modify the fields and their types. + /// + /// # Arguments + /// * `update_schema` - A `CollectionUpdateSchema` object describing the fields to update. + #[inline] + pub async fn update( + &self, + update_schema: models::CollectionUpdateSchema, + ) -> Result> { + let params = collections_api::UpdateCollectionParams { + collection_name: self.collection_name.to_owned(), + collection_update_schema: update_schema, + }; + execute_wrapper!(self, collections_api::update_collection, params) + } +} diff --git a/typesense/src/client/collections.rs b/typesense/src/client/collections.rs new file mode 100644 index 0000000..060bf94 --- /dev/null +++ b/typesense/src/client/collections.rs @@ -0,0 +1,51 @@ +//! Provides access to the collection and alias-related API endpoints. +//! +//! A `Collections` instance is created via the main `client.collections()` method. + +use crate::{Client, Error, execute_wrapper}; +use typesense_codegen::{ + apis::collections_api::{self, GetCollectionsParams}, + models::{self, GetCollectionsParameters}, +}; + +/// Provides methods for interacting with Typesense collections and aliases. +/// +/// This struct is created by calling `client.collections()`. +pub struct Collections<'c> { + pub(super) client: &'c Client, +} + +impl<'c> Collections<'c> { + /// Creates a new `Collection` instance + #[inline] + pub(super) fn new(client: &'c Client) -> Self { + Self { client } + } + + /// Creates a new collection with the given schema. + /// + /// # Arguments + /// * `schema` - A `CollectionSchema` object describing the collection to be created. + pub async fn create( + &self, + schema: models::CollectionSchema, + ) -> Result> { + let params = collections_api::CreateCollectionParams { + collection_schema: schema, + }; + execute_wrapper!(self, collections_api::create_collection, params) + } + + /// List the existing Typesense collections. + pub async fn retrieve( + &self, + params: GetCollectionsParameters, + ) -> Result, Error> { + let params = GetCollectionsParams { + exclude_fields: params.exclude_fields, + limit: params.limit, + offset: params.offset, + }; + execute_wrapper!(self, collections_api::get_collections, params) + } +} diff --git a/typesense/src/client/key.rs b/typesense/src/client/key.rs new file mode 100644 index 0000000..03e9536 --- /dev/null +++ b/typesense/src/client/key.rs @@ -0,0 +1,45 @@ +//! Provides access to the API endpoints for managing a single API key. +//! +//! A `Key` instance is created via the `client.key(key_id)` method. + +use crate::{Client, Error, execute_wrapper}; +use typesense_codegen::{apis::keys_api, models}; + +/// Provides methods for managing a specific Typesense API key. +/// +/// This struct is created by calling `client.key(key_id)`. +pub struct Key<'c> { + pub(super) client: &'c Client, + pub(super) key_id: i64, +} + +impl<'c> Key<'c> { + /// Creates a new `Key` instance for a specific key ID. + #[inline] + pub(super) fn new(client: &'c Client, key_id: i64) -> Self { + Self { client, key_id } + } + + /// Retrieves metadata about this specific API key. + /// + /// For security reasons, this endpoint only returns the key prefix and metadata, + /// not the full key value. + #[inline] + pub async fn retrieve(&self) -> Result> { + let params = keys_api::GetKeyParams { + key_id: self.key_id, + }; + execute_wrapper!(self, keys_api::get_key, params) + } + + /// Deletes this specific API key. + #[inline] + pub async fn delete( + &self, + ) -> Result> { + let params = keys_api::DeleteKeyParams { + key_id: self.key_id, + }; + execute_wrapper!(self, keys_api::delete_key, params) + } +} diff --git a/typesense/src/client/keys.rs b/typesense/src/client/keys.rs new file mode 100644 index 0000000..a7979f0 --- /dev/null +++ b/typesense/src/client/keys.rs @@ -0,0 +1,72 @@ +//! Provides access to the API endpoints for managing the collection of API keys. +//! +//! An `Keys` instance is created via the `client.keys()` method. + +use crate::{ + Client, Error, execute_wrapper, + models::{self, ScopedKeyParameters}, +}; +use base64::{Engine, engine::general_purpose::STANDARD as Base64Engine}; +use hmac::{Hmac, Mac}; +use sha2::Sha256; +use typesense_codegen::apis::keys_api; + +/// Provides methods for managing a collection of Typesense API keys. +/// +/// This struct is created by calling `client.keys()`. +pub struct Keys<'c> { + pub(super) client: &'c Client, +} + +impl<'c> Keys<'c> { + /// Creates a new `Keys` instance. + #[inline] + pub(super) fn new(client: &'c Client) -> Self { + Self { client } + } + + /// Creates a new API key with fine-grained access control. + /// + /// You can restrict access on a per-collection and per-action level. + /// The full, unhashed key is only returned on creation. + /// + /// # Arguments + /// * `schema` - An `ApiKeySchema` object describing the key's permissions. + #[inline] + pub async fn create( + &self, + schema: models::ApiKeySchema, + ) -> Result> { + let params = keys_api::CreateKeyParams { + api_key_schema: Some(schema), + }; + execute_wrapper!(self, keys_api::create_key, params) + } + + /// Lists all API keys and their metadata. + #[inline] + pub async fn retrieve(&self) -> Result> { + execute_wrapper!(self, keys_api::get_keys) + } + + /// Generate a scoped search API key that can have embedded search parameters in them. + /// + /// More info [here](https://typesense.org/docs/latest/api/api-keys.html#generate-scoped-search-key). + pub fn generate_scoped_search_key( + &self, + key: impl AsRef, + params: &ScopedKeyParameters, + ) -> anyhow::Result { + let params = serde_json::to_string(params)?; + + let mut mac = Hmac::::new_from_slice(key.as_ref().as_bytes())?; + mac.update(params.as_bytes()); + let result = mac.finalize(); + let digest = Base64Engine.encode(result.into_bytes()); + + let key_prefix = &key.as_ref()[0..4]; + let raw_scoped_key = format!("{}{}{}", digest, key_prefix, params); + + Ok(Base64Engine.encode(raw_scoped_key.as_bytes())) + } +} diff --git a/typesense/src/client/mod.rs b/typesense/src/client/mod.rs new file mode 100644 index 0000000..5ccdead --- /dev/null +++ b/typesense/src/client/mod.rs @@ -0,0 +1,619 @@ +//! # A batteries-included, multi-node-aware client for the Typesense API. +//! +//! This module provides the main `Client` for interacting with a Typesense cluster. +//! It is designed for resilience and ease of use, incorporating features like +//! automatic failover, health checks, and a structured, ergonomic API. +//! +//! ## Key Features: +//! - **Multi-Node Configuration**: Automatically manages connections to multiple Typesense nodes. +//! - **Health Checks & Failover**: Monitors node health and seamlessly fails over to healthy nodes upon encountering server or network errors. +//! - **Nearest Node Priority**: Can be configured to always prioritize a specific nearest node to reduce latency. +//! - **Built-in Retries**: Handles transient network errors with an exponential backoff policy for each node. +//! +//! ## Example Usage +//! +//! The following example demonstrates how to use the client in a standard +//! server-side **Tokio** environment. +//! +//! ```no_run +//! #[cfg(not(target_family = "wasm"))] +//! { +//! use typesense::{Client, models, ExponentialBackoff}; +//! use std::time::Duration; +//! +//! #[tokio::main] +//! async fn main() -> Result<(), Box> { +//! let client = Client::builder() +//! .nodes(vec!["http://localhost:8108"]) +//! .api_key("xyz") +//! .healthcheck_interval(Duration::from_secs(60)) +//! .retry_policy(ExponentialBackoff::builder().build_with_max_retries(3)) +//! .connection_timeout(Duration::from_secs(5)) +//! .build() +//! .unwrap(); +//! +//! // Retrieve details for a collection +//! let collection = client.collection_schemaless("products").retrieve().await?; +//! println!("Collection Name: {}", collection.name); +//! +//! // Search for a document +//! let search_params = models::SearchParameters { +//! q: Some("phone".to_owned()), +//! query_by: Some("name".to_owned()), +//! ..Default::default() +//! }; +//! +//! let search_results = client +//! .collection_schemaless("products") +//! .documents() +//! .search(search_params) +//! .await?; +//! +//! println!("Found {} hits.", search_results.found.unwrap_or(0)); +//! Ok(()) +//! } +//! } +//! ``` +//! --- +//! +//! ### WebAssembly (Wasm) Usage +//! +//! When compiling for a WebAssembly target (`wasm32-unknown-unknown`), +//! Tokio-based features such as middleware, retries, and connection +//! timeouts are **not available**. +//! +//! Example: +//! +//! ```no_run +//! #[cfg(target_family = "wasm")] +//! { +//! use typesense::{Client, models}; +//! use reqwest::Url; +//! use std::time::Duration; +//! use wasm_bindgen_futures::spawn_local; +//! +//! fn main() { +//! spawn_local(async { +//! let client = Client::builder() +//! .nodes(vec!["http://localhost:8108"]) +//! .api_key("xyz") +//! .healthcheck_interval(Duration::from_secs(60)) +//! // .retry_policy(...) <-- not supported in Wasm +//! // .connection_timeout(...) <-- not supported in Wasm +//! .build() +//! .unwrap(); +//! +//! // Retrieve details for a collection +//! match client.collection_schemaless("products").retrieve().await { +//! Ok(collection) => println!("Collection Name: {}", collection.name), +//! Err(e) => eprintln!("Error retrieving collection: {}", e), +//! } +//! +//! // Search for a document +//! let search_params = models::SearchParameters { +//! q: Some("phone".to_owned()), +//! query_by: Some("name".to_owned()), +//! ..Default::default() +//! }; +//! +//! match client.collection_schemaless("products").documents().search(search_params).await { +//! Ok(search_results) => { +//! println!("Found {} hits.", search_results.found.unwrap_or(0)); +//! } +//! Err(e) => eprintln!("Error searching documents: {}", e), +//! } +//! }); +//! } +//! } +//! ``` +mod collection; +mod collections; +mod key; +mod keys; +mod multi_search; + +use crate::{Error, traits::Document}; +use collection::Collection; +use collections::Collections; +use key::Key; +use keys::Keys; + +#[cfg(not(target_arch = "wasm32"))] +use reqwest_middleware::ClientBuilder as ReqwestMiddlewareClientBuilder; +#[cfg(not(target_arch = "wasm32"))] +use reqwest_retry::RetryTransientMiddleware; +pub use reqwest_retry::policies::ExponentialBackoff; + +use debug_unsafe::{option::OptionUnwrapper, slice::SliceGetter}; +use serde::{Serialize, de::DeserializeOwned}; +use std::{ + future::Future, + sync::{ + RwLock, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, +}; +use typesense_codegen::apis::{self, configuration}; +use web_time::{Duration, Instant}; + +/// Wraps api call in `client::execute()` +#[macro_export] +macro_rules! execute_wrapper { + ($self:ident, $call:expr) => { + $self.client.execute($call).await + }; + ($self:ident, $call:expr, $params:ident) => { + $self + .client + .execute( + |config: &typesense_codegen::apis::configuration::Configuration| { + $call(config, &$params) + }, + ) + .await + }; +} + +// This is an internal detail to track the state of each node. +#[derive(Debug)] +struct Node { + config: configuration::Configuration, + is_healthy: AtomicBool, + last_accessed: RwLock, +} + +impl Node { + /// Sets the health status of the node + #[inline] + fn set_health(&self, is_healthy: bool) { + *self.last_accessed.write().unwrap() = Instant::now(); + self.is_healthy.store(is_healthy, Ordering::Relaxed); + } +} + +/// The main entry point for all interactions with the Typesense API. +/// +/// The client manages connections to multiple nodes and provides access to different +/// API resource groups (namespaces) like `collections`, `documents`, and `operations`. +#[derive(Debug)] +pub struct Client { + nodes: Vec, + is_nearest_node_set: bool, + healthcheck_interval: Duration, + current_node_index: AtomicUsize, +} + +#[bon::bon] +impl Client { + /// Creates a new `Client`. + /// + /// Returns an error if the configuration contains no nodes. Default values: + /// - **nearest_node**: None. + /// - **healthcheck_interval**: 60 seconds. + /// - **retry_policy**: Exponential backoff with a maximum of 3 retries. (disabled on WASM) + /// - **connection_timeout**: 5 seconds. (disabled on WASM) + #[builder] + pub fn new( + /// The Typesense API key used for authentication. + #[builder(into)] + api_key: String, + /// A list of all nodes in the Typesense cluster. + #[builder( + with = |iter: impl IntoIterator>| + iter.into_iter().map(Into::into).collect::>() + )] + nodes: Vec, + #[builder(into)] + /// An optional, preferred node to try first for every request. + /// This is for your server-side load balancer. + /// Do not add this node to all nodes list, should be a separate one. + nearest_node: Option, + #[builder(default = Duration::from_secs(60))] + /// The duration after which an unhealthy node will be retried for requests. + healthcheck_interval: Duration, + #[builder(default = ExponentialBackoff::builder().build_with_max_retries(3))] + /// The retry policy for transient network errors on a *single* node. + retry_policy: ExponentialBackoff, + #[builder(default = Duration::from_secs(5))] + /// The timeout for each individual network request. + connection_timeout: Duration, + ) -> Result { + let is_nearest_node_set = nearest_node.is_some(); + + let nodes: Vec<_> = nodes + .into_iter() + .chain(nearest_node) + .map(|mut url| { + #[cfg(target_arch = "wasm32")] + let http_client = reqwest::Client::builder() + .build() + .expect("Failed to build reqwest client"); + + #[cfg(not(target_arch = "wasm32"))] + let http_client = ReqwestMiddlewareClientBuilder::new( + reqwest::Client::builder() + .timeout(connection_timeout) + .build() + .expect("Failed to build reqwest client"), + ) + .with(RetryTransientMiddleware::new_with_policy(retry_policy)) + .build(); + + if url.len() > 1 && url.chars().last().unwrap_safe_unchecked() == '/' { + url.pop(); + } + + let config = configuration::Configuration { + base_path: url, + api_key: Some(configuration::ApiKey { + prefix: None, + key: api_key.clone(), + }), + client: http_client, + ..Default::default() + }; + + Node { + config, + is_healthy: AtomicBool::new(true), + last_accessed: RwLock::new(Instant::now()), + } + }) + .collect(); + + if nodes.is_empty() { + return Err("Configuration must include at least one node or a nearest_node."); + } + + Ok(Self { + nodes, + is_nearest_node_set, + healthcheck_interval, + current_node_index: AtomicUsize::new(0), + }) + } + + /// Selects the next node to use for a request based on health and priority. + fn get_next_node(&self) -> &Node { + // if only one node (including nearest) + if self.nodes.len() == 1 { + return self.nodes.first().unwrap_safe_unchecked(); + } + + let (nodes_len, mut index) = if self.is_nearest_node_set { + let last_node_index = self.nodes.len() - 1; + (last_node_index, last_node_index) + } else { + ( + self.nodes.len(), + self.current_node_index.fetch_add(1, Ordering::Relaxed) % self.nodes.len(), + ) + }; + + for _ in 0..self.nodes.len() { + let node = self.nodes.get_safe_unchecked(index); + + if node.is_healthy.load(Ordering::Relaxed) + || node.last_accessed.read().unwrap().elapsed() >= self.healthcheck_interval + { + return node; + } + index = self.current_node_index.fetch_add(1, Ordering::Relaxed) % nodes_len; + } + + // If all nodes are unhealthy and not due for a check, just pick the next one in the round-robin. + // This gives it a chance to prove it has recovered. + index = self.current_node_index.load(Ordering::Relaxed) % self.nodes.len(); + self.nodes.get_safe_unchecked(index) + } + + /// For use in legacy APIs. + #[inline] + pub fn get_legacy_config(&self) -> &configuration::Configuration { + &self.get_next_node().config + } + + /// The core execution method that handles multi-node failover and retries. + /// This internal method is called by all public API methods. + pub(super) async fn execute(&'a self, api_call: F) -> Result> + where + F: Fn(&'a configuration::Configuration) -> Fut, + Fut: Future>>, + E: std::fmt::Debug + 'static, + apis::Error: std::error::Error + 'static, + { + let mut last_api_error: Option> = None; + // Loop up to the total number of available nodes. + for _ in 0..self.nodes.len() { + let node = self.get_next_node(); + match api_call(&node.config).await { + Ok(response) => { + node.set_health(true); + return Ok(response); + } + Err(e) => { + if is_retriable(&e) { + node.set_health(false); + last_api_error = Some(e); + } else { + return Err(e.into()); + } + } + } + } + + Err(crate::Error::AllNodesFailed { + source: last_api_error + .expect("No nodes were available to try, or all errors were non-retriable."), + }) + } + + /// Provides access to API endpoints for managing collections like `create()` and `retrieve()`. + /// # Example + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::{Client, models::GetCollectionsParameters}; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec!["http://localhost:8108"]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// let all_collections = client.collections().retrieve(GetCollectionsParameters::default()).await.unwrap(); + /// # Ok(()) + /// # } + /// # } + /// ``` + #[inline] + pub fn collections(&self) -> Collections<'_> { + Collections::new(self) + } + + /// Provides access to API endpoints for a specific collection. + /// + /// This method returns a `Collection` handle, which is generic over the type of document + /// stored in that collection. + /// + /// # Type Parameters + /// * `D` - The type of the documents in the collection. It must be serializable and deserializable. + /// + /// # Arguments + /// * `collection_name` - The name of the collection to interact with. + /// + /// # Example: Working with a strongly-typed collection + /// + /// When you want to retrieve or search for documents and have them automatically + /// deserialized into your own structs. + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::Client; + /// # use serde::{Serialize, Deserialize}; + /// # + /// # #[derive(Serialize, Deserialize, Debug)] + /// # struct Book { id: String, title: String } + /// # async fn run() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec!["http://localhost:8108"]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// // Get a typed handle to the "books" collection + /// let books_collection = client.collection_named::("books"); + /// + /// // Retrieve a single book, it returns `Result` + /// let book = books_collection.document("123").retrieve().await?; + /// println!("Retrieved book: {:?}", book); + /// # + /// # Ok(()) + /// # } + /// # } + /// ``` + #[inline] + pub fn collection_named<'c, 'n, D>(&'c self, collection_name: &'n str) -> Collection<'c, 'n, D> + where + D: DeserializeOwned + Serialize, + { + Collection::new(self, collection_name) + } + + /// Provides access to API endpoints for a specific collection. + /// + /// This method returns a `Collection` handle, which is generic over the type of document + /// stored in that collection. + /// + /// # Type Parameters + /// * `D` - The type of the documents in the collection. It must be of trait Document. + /// + /// # Example: Working with a strongly-typed collection + /// + /// When you want to retrieve or search for documents and have them automatically + /// deserialized into your own structs. + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::{Client, Typesense}; + /// # use serde::{Serialize, Deserialize}; + /// # + /// # #[derive(Typesense, Serialize, Deserialize, Debug)] + /// # struct Book { id: String, title: String } + /// # async fn run() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec!["http://localhost:8108"]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// // Get a typed handle to the "books" collection + /// let books_collection = client.collection::(); + /// + /// // Retrieve a single book, it returns `Result` + /// let book = books_collection.document("123").retrieve().await?; + /// println!("Retrieved book: {:?}", book); + /// # + /// # Ok(()) + /// # } + /// # } + /// ``` + #[inline] + pub fn collection<'c, 'n, D>(&'c self) -> Collection<'c, 'n, D> + where + D: Document, + { + Collection::new(self, D::COLLECTION_NAME) + } + + /// Provides access to API endpoints for a specific collection using schemaless `serde_json::Value` documents. + /// + /// This is the simplest way to interact with a collection when you do not need strong typing. + /// It is a convenient shorthand for `client.collection_named::("...")`. + /// + /// The returned handle can be used for both document operations (which will return `serde_json::Value`) + /// and collection-level operations (like `.delete()` or `.retrieve()`). + /// + /// # Arguments + /// * `collection_name` - The name of the collection to interact with. + /// + /// # Example + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::Client; + /// # async fn run() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec!["http://localhost:8108"]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// let products_collection = client.collection_schemaless("products"); + /// # + /// # Ok(()) + /// # } + /// # } + /// ``` + #[inline] + pub fn collection_schemaless<'c, 'n>( + &'c self, + collection_name: &'n str, + ) -> Collection<'c, 'n, serde_json::Value> { + Collection::new(self, collection_name) + } + + /// Provides access to endpoints for managing the collection of API keys. + /// + /// # Example + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::{Client, models}; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec!["http://localhost:8108"]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// # let schema = models::ApiKeySchema { + /// # description: "Search-only key.".to_owned(), + /// # actions: vec!["documents:search".to_owned()], + /// # collections: vec!["*".to_owned()], + /// # ..Default::default() + /// # }; + /// let new_key = client.keys().create(schema).await.unwrap(); + /// # Ok(()) + /// # } + /// # } + /// ``` + #[inline] + pub fn keys(&self) -> Keys<'_> { + Keys::new(self) + } + + /// Provides access to endpoints for managing a single API key. + /// + /// # Arguments + /// * `key_id` - The ID of the key to manage. + /// + /// # Example + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::Client; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec!["http://localhost:8108"]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// let deleted_key = client.key(123).delete().await.unwrap(); + /// # Ok(()) + /// # } + /// # } + /// ``` + #[inline] + pub fn key(&self, key_id: i64) -> Key<'_> { + Key::new(self, key_id) + } + + /// Provides access to the multi search endpoint. + /// + /// # Example + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::{Client, models}; + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec!["http://localhost:8108"]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// # let search_requests = models::MultiSearchBody { + /// # searches: vec![models::MultiSearchCollectionParameters { + /// # collection: Some("products".to_owned()), + /// # q: Some("phone".to_owned()), + /// # query_by: Some("name".to_owned()), + /// # ..Default::default() + /// # }], + /// # ..Default::default() + /// # }; + /// # let common_params = models::MultiSearchParameters::default(); + /// let results = client.multi_search().perform(search_requests, common_params).await.unwrap(); + /// # Ok(()) + /// # } + /// # } + /// ``` + #[inline] + pub fn multi_search(&self) -> multi_search::MultiSearch<'_> { + multi_search::MultiSearch::new(self) + } +} + +/// A helper function to determine if an error is worth retrying on another node. +fn is_retriable(error: &apis::Error) -> bool +where + E: std::fmt::Debug + 'static, + apis::Error: std::error::Error + 'static, +{ + match error { + // Server-side errors (5xx) indicate a problem with the node, so we should try another. + apis::Error::ResponseError(content) => content.status.is_server_error(), + + // Underlying reqwest errors (e.g., connection refused) are retriable. + apis::Error::Reqwest(_) => true, + + // Network-level errors from middleware are always retriable. + #[cfg(not(target_arch = "wasm32"))] + apis::Error::ReqwestMiddleware(_) => true, + + // Client-side (4xx) or parsing errors are not retriable as the request is likely invalid. + _ => false, + } +} diff --git a/typesense/src/client/multi_search.rs b/typesense/src/client/multi_search.rs new file mode 100644 index 0000000..3188a01 --- /dev/null +++ b/typesense/src/client/multi_search.rs @@ -0,0 +1,352 @@ +//! Provides access to the API endpoints for Multi Search. +//! +//! A `MultiSearch` instance is created via the main `client.multi_search()` method. + +use crate::{ + Client, Error, execute_wrapper, + models::{MultiSearchBody, SearchResult}, +}; +use typesense_codegen::{ + apis::documents_api::{self, MultiSearchParams}, + models as raw_models, +}; + +/// Provides methods for performing multi-search operations across multiple collections. +/// +/// This struct is created by calling `client.multi_search()`. +pub struct MultiSearch<'c> { + pub(super) client: &'c Client, +} + +impl<'c> MultiSearch<'c> { + /// Creates a new `MultiSearch` instance. + #[inline] + pub(super) fn new(client: &'c Client) -> Self { + Self { client } + } + + /// Performs a **federated** multi-search operation, returning a list of search results. + /// + /// This function allows you to send multiple search queries in a single HTTP request, which is + /// efficient for reducing network latency. + /// + /// The returned `MultiSearchResult` contains a `results` vector where each item maps to a + /// query in the request, in the exact same order. To process these results in a type-safe + /// way, you can use the `MultiSearchResultExt::parse_at` helper method. + /// + /// This is the default multi-search behavior in Typesense. For more details, see the + /// [official Typesense API documentation on federated search](https://typesense.org/docs/latest/api/federated-multi-search.html#federated-search). + /// + /// For **union** searches that merge all hits into a single ranked list, use the + /// `perform_union` method instead. + /// + /// # Example + /// + /// This example demonstrates a federated search across two different collections. + /// + /// ```no_run + /// # #[cfg(not(target_family = "wasm"))] + /// # { + /// # use typesense::{Client, models::{self, SearchResult}, prelude::*}; + /// # use reqwest::Url; + /// # use serde::Deserialize; + /// # + /// # // Define the structs for your documents for typed parsing. + /// # #[derive(Deserialize, Debug)] + /// # struct Product { id: String, name: String } + /// # #[derive(Deserialize, Debug)] + /// # struct Brand { id: String, company_name: String } + /// # + /// # #[tokio::main] + /// # async fn main() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// // Define the individual search queries for different collections. + /// let search_requests = models::MultiSearchBody { + /// searches: vec![ + /// // Search #0 targets the 'products' collection + /// models::MultiSearchCollectionParameters { + /// collection: Some("products".to_owned()), + /// q: Some("shoe".to_owned()), + /// query_by: Some("name".to_owned()), + /// ..Default::default() + /// }, + /// // Search #1 targets the 'brands' collection + /// models::MultiSearchCollectionParameters { + /// collection: Some("brands".to_owned()), + /// q: Some("nike".to_owned()), + /// query_by: Some("company_name".to_owned()), + /// ..Default::default() + /// }, + /// ], + /// ..Default::default() + /// }; + /// + /// // Define parameters that will apply to all searches. + /// let common_params = models::MultiSearchParameters::default(); + /// + /// // Perform the federated multi-search. + /// let raw_response = client + /// .multi_search() + /// .perform(search_requests, common_params) + /// .await?; + /// + /// // The raw response contains a vector of results. + /// assert_eq!(raw_response.results.len(), 2); + /// + /// // Use the `parse_at` helper to get strongly-typed results for each search. + /// let typed_products: SearchResult = raw_response.parse_at(0)?; + /// let typed_brands: SearchResult = raw_response.parse_at(1)?; + /// + /// println!("Found {} products.", typed_products.found.unwrap_or(0)); + /// println!("Found {} brands.", typed_brands.found.unwrap_or(0)); + /// # Ok(()) + /// # } + /// # } + /// ``` + /// # Arguments + /// * `search_requests` - A `MultiSearchBody` containing the list of individual search queries. The `union` field is ignored. + /// * `common_search_params` - A `MultiSearchParameters` struct describing search parameters that are common to all searches. + pub async fn perform( + &self, + search_requests: MultiSearchBody, + common_search_params: raw_models::MultiSearchParameters, + ) -> Result< + raw_models::MultiSearchResult, + Error, + > { + let request_body = raw_models::MultiSearchSearchesParameter { + searches: search_requests.searches, + ..Default::default() + }; + let multi_search_params = build_multi_search_params(request_body, common_search_params); + + let raw_result = execute_wrapper!(self, documents_api::multi_search, multi_search_params); + + // Now, handle the raw result and parse it into the strong type. + match raw_result { + Ok(json_value) => serde_json::from_value(json_value).map_err(Error::from), + Err(e) => Err(e), + } + } + + /// Performs a multi-search request in **union** mode, returning a single, merged `SearchResult`. + /// + /// For more details, see the + /// [official Typesense API documentation on union search](https://typesense.org/docs/latest/api/federated-multi-search.html#union-search). + /// + /// ### Handling Search Results + /// + /// #### 1. Heterogeneous Documents (Different Schemas) + /// + /// When searching across different collections (e.g., `products` and `brands`), generic parameter `D` must be `serde_json::Value`. + /// You must inspect the `serde_json::Value` of each document to determine its type before + /// deserializing it into a concrete struct. + /// + /// ```no_run + /// # use typesense::{models, Client}; + /// # use serde_json::Value; + /// # use reqwest::Url; + /// # #[derive(serde::Deserialize)] + /// # struct Product { name: String } + /// # #[derive(serde::Deserialize)] + /// # struct Brand { company_name: String } + /// # async fn run() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// let search_requests = models::MultiSearchBody { + /// searches: vec![ + /// // Search #0 targets the 'products' collection + /// models::MultiSearchCollectionParameters { + /// collection: Some("products".to_owned()), + /// q: Some("shoe".to_owned()), + /// query_by: Some("name".to_owned()), + /// ..Default::default() + /// }, + /// // Search #1 targets the 'brands' collection + /// models::MultiSearchCollectionParameters { + /// collection: Some("brands".to_owned()), + /// q: Some("nike".to_owned()), + /// query_by: Some("company_name".to_owned()), + /// ..Default::default() + /// }, + /// ], + /// ..Default::default() + /// }; + /// let common_params = models::MultiSearchParameters::default(); + /// + /// let search_result: models::SearchResult = client.multi_search().perform_union(search_requests, common_params).await?; + /// for hit in search_result.hits.unwrap_or_default() { + /// if let Some(doc) = hit.document { + /// if doc.get("price").is_some() { + /// let product: Product = serde_json::from_value(doc)?; + /// println!("Found Product: {}", product.name); + /// } else if doc.get("country").is_some() { + /// let brand: Brand = serde_json::from_value(doc)?; + /// println!("Found Brand: {}", brand.company_name); + /// } + /// } + /// } + /// # Ok(()) + /// # } + /// ``` + /// + /// #### 2. Homogeneous Documents (Same Schema) + /// + /// If all search queries target collections that share the **same schema**, you can directly use the concrete type for `D`. + /// + /// ```no_run + /// # use typesense::{models, Client}; + /// # use reqwest::Url; + /// # use serde_json::Value; + /// # #[derive(serde::Deserialize)] + /// # struct Product { name: String } + /// # async fn run() -> Result<(), Box> { + /// # let client = Client::builder() + /// # .nodes(vec![Url::parse("http://localhost:8108").unwrap()]) + /// # .api_key("xyz") + /// # .build() + /// # .unwrap(); + /// let search_requests = models::MultiSearchBody { + /// searches: vec![ + /// models::MultiSearchCollectionParameters { + /// collection: Some("products".to_owned()), + /// q: Some("shoe".to_owned()), + /// query_by: Some("name".to_owned()), + /// ..Default::default() + /// }, + /// models::MultiSearchCollectionParameters { + /// collection: Some("products".to_owned()), + /// q: Some("sock".to_owned()), + /// query_by: Some("name".to_owned()), + /// ..Default::default() + /// }, + /// ], + /// ..Default::default() + /// }; + /// let common_params = models::MultiSearchParameters::default(); + /// + /// let typed_result: models::SearchResult = client.multi_search().perform_union(search_requests, common_params).await?; + /// + /// if let Some(product) = typed_result.hits.unwrap_or_default().get(0) { + /// println!("Found product: {}", product.document.as_ref().unwrap().name); + /// } + /// # Ok(()) + /// # } + /// ``` + /// + /// # Arguments + /// + /// * `search_requests` - A `MultiSearchBody` containing the list of search queries to perform. + /// * `common_search_params` - A `MultiSearchParameters` which will be applied to all individual searches. + /// + /// # Returns + /// + /// A `Result` containing a `SearchResult` on success, or an `Error` on failure. + pub async fn perform_union serde::Deserialize<'de>>( + &self, + search_requests: MultiSearchBody, + common_search_params: raw_models::MultiSearchParameters, + ) -> Result, Error> { + // Explicitly set `union: true` for the request body + let request_body = raw_models::MultiSearchSearchesParameter { + union: Some(true), + searches: search_requests.searches, + }; + + let multi_search_params = build_multi_search_params(request_body, common_search_params); + + // Execute the request to get the raw JSON value + let raw_result = execute_wrapper!(self, documents_api::multi_search, multi_search_params); + + match raw_result { + Ok(json_value) => serde_json::from_value(json_value).map_err(Error::from), + Err(e) => Err(e), + } + } +} +// Private helper function to construct the final search parameters object. +// This encapsulates the repetitive mapping logic. +fn build_multi_search_params( + request_body: raw_models::MultiSearchSearchesParameter, + params: raw_models::MultiSearchParameters, +) -> MultiSearchParams { + MultiSearchParams { + multi_search_searches_parameter: Some(request_body), + // Common URL search params + cache_ttl: params.cache_ttl, + conversation: params.conversation, + conversation_id: params.conversation_id, + conversation_model_id: params.conversation_model_id, + drop_tokens_mode: params.drop_tokens_mode, + drop_tokens_threshold: params.drop_tokens_threshold, + enable_overrides: params.enable_overrides, + enable_synonyms: params.enable_synonyms, + enable_typos_for_alpha_numerical_tokens: params.enable_typos_for_alpha_numerical_tokens, + enable_typos_for_numerical_tokens: params.enable_typos_for_numerical_tokens, + exclude_fields: params.exclude_fields, + exhaustive_search: params.exhaustive_search, + facet_by: params.facet_by, + facet_query: params.facet_query, + facet_return_parent: params.facet_return_parent, + facet_strategy: params.facet_strategy, + filter_by: params.filter_by, + filter_curated_hits: params.filter_curated_hits, + group_by: params.group_by, + group_limit: params.group_limit, + group_missing_values: params.group_missing_values, + hidden_hits: params.hidden_hits, + highlight_affix_num_tokens: params.highlight_affix_num_tokens, + highlight_end_tag: params.highlight_end_tag, + highlight_fields: params.highlight_fields, + highlight_full_fields: params.highlight_full_fields, + highlight_start_tag: params.highlight_start_tag, + include_fields: params.include_fields, + infix: params.infix, + limit: params.limit, + max_extra_prefix: params.max_extra_prefix, + max_extra_suffix: params.max_extra_suffix, + max_facet_values: params.max_facet_values, + min_len_1typo: params.min_len_1typo, + min_len_2typo: params.min_len_2typo, + num_typos: params.num_typos, + offset: params.offset, + override_tags: params.override_tags, + page: params.page, + per_page: params.per_page, + pinned_hits: params.pinned_hits, + pre_segmented_query: params.pre_segmented_query, + prefix: params.prefix, + preset: params.preset, + prioritize_exact_match: params.prioritize_exact_match, + prioritize_num_matching_fields: params.prioritize_num_matching_fields, + prioritize_token_position: params.prioritize_token_position, + q: params.q, + query_by: params.query_by, + query_by_weights: params.query_by_weights, + remote_embedding_num_tries: params.remote_embedding_num_tries, + remote_embedding_timeout_ms: params.remote_embedding_timeout_ms, + search_cutoff_ms: params.search_cutoff_ms, + snippet_threshold: params.snippet_threshold, + sort_by: params.sort_by, + stopwords: params.stopwords, + synonym_num_typos: params.synonym_num_typos, + synonym_prefix: params.synonym_prefix, + text_match_type: params.text_match_type, + typo_tokens_threshold: params.typo_tokens_threshold, + use_cache: params.use_cache, + vector_query: params.vector_query, + voice_query: params.voice_query, + enable_analytics: params.enable_analytics, + // enable_highlight_v1: None, + // max_candidates: None, + // max_filter_by_candidates: None, + // split_join_tokens: None, + } +} diff --git a/typesense/src/collection_schema.rs b/typesense/src/collection_schema.rs deleted file mode 100644 index c28207a..0000000 --- a/typesense/src/collection_schema.rs +++ /dev/null @@ -1,135 +0,0 @@ -//! # Collection -//! -//! In Typesense, a group of related documents is called a collection. A collection -//! is roughly equivalent to a table in a relational database. -//! -use crate::field::Field; - -pub use typesense_codegen::models::CollectionSchema; - -/// Builder for the [CollectionSchema] struct. -#[derive(Debug, Default)] -pub struct CollectionSchemaBuilder { - name: String, - fields: Vec, - default_sorting_field: Option, - token_separators: Option>, - enable_nested_fields: Option, - symbols_to_index: Option>, -} - -impl CollectionSchemaBuilder { - /// Create a builder for [CollectionSchema] - #[inline] - pub fn new(name: impl Into, fields: Vec) -> Self { - Self { - name: name.into(), - fields, - ..Default::default() - } - } - - /// Insert field - #[inline] - pub fn field(mut self, field: Field) -> Self { - self.fields.push(field); - self - } - - /// Set fields - #[inline] - pub fn fields(mut self, fields: &[Field]) -> Self { - self.fields.extend_from_slice(fields); - self - } - - /// Set default sorting field - #[inline] - pub fn default_sorting_field(mut self, default_sorting_field: impl Into) -> Self { - self.default_sorting_field = Some(default_sorting_field.into()); - self - } - - /// Set token separators - #[inline] - pub fn token_separators(mut self, token_separators: Vec) -> Self { - self.token_separators = Some(token_separators); - self - } - - /// Enable nested fields - #[inline] - pub fn enable_nested_fields(mut self, enable_nested_fields: Option) -> Self { - self.enable_nested_fields = enable_nested_fields; - self - } - - /// Set symbols to index - #[inline] - pub fn symbols_to_index(mut self, symbols_to_index: Vec) -> Self { - self.symbols_to_index = Some(symbols_to_index); - self - } - - /// Create a `CollectionSchema` with the current values of the builder, - /// It can fail if any of the required fields is not not defined. - #[inline] - pub fn build(self) -> CollectionSchema { - CollectionSchema { - name: self.name, - fields: self.fields, - default_sorting_field: self.default_sorting_field, - token_separators: self.token_separators, - enable_nested_fields: self.enable_nested_fields, - symbols_to_index: self.symbols_to_index, - } - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::field::*; - use serde_json::json; - - #[test] - fn collection_schema_serializes_as_expected() { - let fields = [ - ("company_name", "string".to_owned(), None), - ("num_employees", "int32".to_owned(), None), - ("country", "string".to_owned(), Some(true)), - ] - .map(|(name, typesense_type, facet)| { - FieldBuilder::new(name, typesense_type).facet(facet).build() - }) - .to_vec(); - - let collection = CollectionSchemaBuilder::new("companies", fields) - .default_sorting_field("num_employees".to_owned()) - .build(); - - let expected = json!( - { - "name": "companies", - "fields": [ - { - "name" : "company_name", - "type" : "string" - }, - { - "name" : "num_employees", - "type" : "int32" - }, - { - "name" : "country", - "type" : "string", - "facet" : true - } - ], - "default_sorting_field": "num_employees" - } - ); - - assert_eq!(serde_json::to_value(&collection).unwrap(), expected) - } -} diff --git a/typesense/src/error.rs b/typesense/src/error.rs new file mode 100644 index 0000000..e0f7530 --- /dev/null +++ b/typesense/src/error.rs @@ -0,0 +1,108 @@ +//! Contains the error types for the Typesense client + +use thiserror::Error; +pub use typesense_codegen::apis::{Error as ApiError, ResponseContent}; + +/// The primary error type for the Typesense client. +/// +/// This enum encapsulates all possible failures, from network issues to API errors +/// returned by the Typesense server, to client-side data handling problems. +/// +/// The generic parameter `E` represents the specific error type associated with a +/// particular API operation (e.g., `SearchCollectionError`, `GetDocumentError`). +#[derive(Debug, Error)] +pub enum Error +where + E: std::fmt::Debug + 'static, + ApiError: std::error::Error + 'static, +{ + /// Occurs when an operation fails against all configured Typesense nodes. + /// + /// It signifies that the client attempted the operation against each node in turn, + /// and every attempt failed. The user should check the health and connectivity + /// of all their Typesense nodes. + /// + /// The `source` field contains the error from the *last* node that was attempted. + #[error("All configured Typesense nodes failed to respond. Last error: {source}")] + AllNodesFailed { + /// The underlying API or network error from the last node attempt. + #[source] + source: ApiError, + }, + + /// Wraps an error returned by the Typesense API or the underlying network stack. + /// + /// This can be due to: + /// - A server-side issue (e.g., HTTP 5xx errors). + /// - A client-side mistake (e.g., HTTP 4xx errors like `404 Not Found` or `401 Unauthorized`). + /// - A network connectivity problem (e.g., connection refused, timeout, DNS failure). + /// + /// You should inspect the wrapped error to get specific details about the HTTP status code and response body. + #[error("An API or network error occurred: {0}")] + Api(#[from] ApiError), + + /// Occurs when the JSON response from Typesense cannot be deserialized into the target Rust struct. + /// + /// This typically signifies a mismatch between the data in your Typesense collection + /// and the fields or data types defined in your Rust struct (`T`). + /// + /// **To debug this, check for:** + /// - A field that exists in Typesense but not in your struct (unless your struct ignores unknown fields). + /// - A field in your struct that doesn't exist in the Typesense document and is not wrapped in an `Option`. + /// - A type mismatch (e.g., a Typesense `string` field that you are trying to deserialize into a `u64`). + #[error("Failed to deserialize the API response into the target struct: {0}")] + Deserialization(#[from] serde_json::Error), +} + +/// Represents the possible errors that can occur when parsing a `multi_search` response. +/// +/// This error enum is returned by the `MultiSearchResultExt::parse_at` method when it +/// fails to convert a raw search result into a strongly-typed `SearchResult`. +#[derive(Debug, Error)] +pub enum MultiSearchParseError { + /// Indicates that the requested index was outside the bounds of the results vector. + /// + /// For a `multi_search` request with `n` search queries, the valid indices for the + /// results are `0` through `n-1`. This error occurs if the provided index is `n` or greater. + /// + /// # Fields + /// * `0` - The invalid index that was requested. + #[error("Search result index {0} is out of bounds.")] + IndexOutOfBounds(usize), + + /// Indicates that the Typesense server returned an error for the specific search query at this index. + /// + // It's possible for a `multi_search` request to succeed overall, but for one or more + // individual searches within it to fail (e.g., due to a typo in a collection name). + /// + /// # Fields + /// * `index` - The index of the search query that failed. + /// * `message` - The error message returned by the Typesense API for this specific search. + #[error("The search at index {index} failed with an API error: {message}")] + ApiError { + /// The index of the search query that failed. + index: usize, + /// The error message returned by the Typesense API for this specific search. + message: String, + }, + + /// Indicates a failure to deserialize a document's JSON into the target struct `T`. + /// + /// This typically happens when the fields in the document stored in Typesense do not + /// match the fields defined in the target Rust struct `T`. Check for mismatches in + /// field names or data types. + /// + /// # Fields + /// * `index` - The index of the search query where the deserialization error occurred. + /// * `source` - The underlying `serde_json::Error` that provides detailed information + /// about the deserialization failure. + #[error("Failed to deserialize a document at index {index}: {source}")] + Deserialization { + /// The index of the search query where the deserialization error occurred. + index: usize, + /// The underlying `serde_json::Error` that provides detailed information + /// about the deserialization failure. + #[source] + source: serde_json::Error, + }, +} diff --git a/typesense/src/field/mod.rs b/typesense/src/field/mod.rs deleted file mode 100644 index 934abed..0000000 --- a/typesense/src/field/mod.rs +++ /dev/null @@ -1,110 +0,0 @@ -//! Module with the common definitions for the -//! [fields](https://github.com/typesense/typesense/blob/v0.19.0/include/field.) -//! available in Typesense. - -mod field_type; -pub use field_type::*; -pub use typesense_codegen::models::{Field, FieldEmbed}; - -/// Builder for the `Field` struct. -#[derive(Debug, Default)] -pub struct FieldBuilder { - name: String, - typesense_type: FieldType, - optional: Option, - facet: Option, - index: Option, - locale: Option, - sort: Option, - infix: Option, - num_dim: Option, - drop: Option, - embed: Option>, -} - -impl FieldBuilder { - /// Create a Builder - #[inline] - pub fn new(name: impl Into, typesense_type: FieldType) -> Self { - Self { - name: name.into(), - typesense_type, - ..Default::default() - } - } - - /// Set if field is optional. - #[inline] - pub fn optional(mut self, optional: Option) -> Self { - self.optional = optional; - self - } - - /// Set if field is facet. - #[inline] - pub fn facet(mut self, facet: Option) -> Self { - self.facet = facet; - self - } - - /// Set if field is index. - #[inline] - pub fn index(mut self, index: Option) -> Self { - self.index = index; - self - } - - /// Set field locale. - #[inline] - pub fn locale(mut self, locale: Option) -> Self { - self.locale = locale; - self - } - - /// Set sort attribute for field - #[inline] - pub fn sort(mut self, sort: Option) -> Self { - self.sort = sort; - self - } - - /// Set infix attribute for field - #[inline] - pub fn infix(mut self, infix: Option) -> Self { - self.infix = infix; - self - } - - /// Set num_dim attribute for field - #[inline] - pub fn num_dim(mut self, num_dim: Option) -> Self { - self.num_dim = num_dim; - self - } - - /// Set drop attribute for field - #[inline] - pub fn drop(mut self, drop: Option) -> Self { - self.drop = drop; - self - } - - /// Create a `Field` with the current values of the builder, - /// It can fail if the name or the typesense_type are not defined. - #[inline] - pub fn build(self) -> Field { - Field { - name: self.name, - r#type: self.typesense_type, - optional: self.optional, - facet: self.facet, - index: self.index, - locale: self.locale, - sort: self.sort, - infix: self.infix, - num_dim: self.num_dim, - drop: self.drop, - embed: self.embed, - } - } -} diff --git a/typesense/src/keys.rs b/typesense/src/keys.rs deleted file mode 100644 index 0f01e55..0000000 --- a/typesense/src/keys.rs +++ /dev/null @@ -1,83 +0,0 @@ -//! Module containing everything related to Keys API. -//! -//! More info [here](https://typesense.org/docs/0.20.0/api/api-keys.html). - -use base64::{Engine, engine::general_purpose::STANDARD as Base64Engine}; -use core::fmt; -use hmac::{Hmac, Mac}; -use serde::{Deserialize, Serialize}; -use sha2::Sha256; -use typesense_codegen::models::ScopedKeyParameters; - -/// Generate a scoped search API key that can have embedded search parameters in them. -/// -/// More info [here](https://typesense.org/docs/0.20.0/api/api-keys.html#generate-scoped-search-key). -pub async fn generate_scoped_search_key( - key: impl AsRef, - filter_by: impl Into, - expires_at: i64, -) -> anyhow::Result { - let generate_scoped_search_key = ScopedKeyParameters { - filter_by: Some(filter_by.into()), - expires_at: Some(expires_at), - }; - let params = serde_json::to_string(&generate_scoped_search_key)?; - - let mut mac = Hmac::::new_from_slice(key.as_ref().as_bytes())?; - mac.update(params.as_bytes()); - let result = mac.finalize(); - let digest = Base64Engine.encode(result.into_bytes()); - - let key_prefix = &key.as_ref()[0..4]; - let raw_scoped_key = format!("{digest}{key_prefix}{params}"); - - Ok(Base64Engine.encode(raw_scoped_key.as_bytes())) -} - -/// Enum over the possible list of Actions. -/// -/// More info [here](https://typesense.org/docs/0.25.2/api/api-keys.html#sample-actions). -#[derive(Serialize, Deserialize)] -pub enum Actions { - /// Allows only search requests. - #[serde(rename = "documents:search")] - DocumentsSearch, - - /// Allows fetching a single document. - #[serde(rename = "documents:get")] - DocumentsGet, - - /// Allow all kinds of collection related operations. - #[serde(rename = "documents:*")] - DocumentsAll, - - /// Allows a collection to be deleted. - #[serde(rename = "collections:delete")] - CollectionsDelete, - - /// Allows a collection to be created. - #[serde(rename = "collections:create")] - CollectionsCreate, - - /// Allow all kinds of collection related operations. - #[serde(rename = "collections:*")] - CollectionsAll, - - /// Allows all operations. - #[serde(rename = "*")] - All, -} - -impl fmt::Display for Actions { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::DocumentsAll => write!(f, "documents:*"), - Self::DocumentsSearch => write!(f, "documents:search"), - Self::DocumentsGet => write!(f, "documents:get"), - Self::CollectionsAll => write!(f, "collections:*"), - Self::CollectionsDelete => write!(f, "collections:delete"), - Self::CollectionsCreate => write!(f, "collections:create"), - Self::All => write!(f, "*"), - } - } -} diff --git a/typesense/src/lib.rs b/typesense/src/lib.rs index 0e6c763..9afac33 100644 --- a/typesense/src/lib.rs +++ b/typesense/src/lib.rs @@ -3,52 +3,126 @@ //! # Typesense //! -//! Rust client library for Typesense +//! A Rust client library for the Typesense API. +//! +//! This library provides an ergonomic interface for +//! interacting with Typesense. It supports multi-node configuration and WebAssembly. //! //! # Examples //! -//! ``` +//! The following examples demonstrate how to define a collection schema using +//! the Typesense derive macro and create it on the server. +//! +//! --- +//! +//! ### Native (Tokio) +//! +//! This example shows the typical setup for a server-side application using the +//! Tokio runtime. It includes features like connection timeouts and automatic +//! request retries. +//! +//! ```no_run //! #[cfg(not(target_family = "wasm"))] //! { -//! use serde::{Deserialize, Serialize}; -//! use typesense::document::Document; -//! use typesense::Typesense; -//! use typesense::apis::collections_api; -//! use typesense::apis::configuration::{ApiKey, Configuration}; -//! -//! #[derive(Typesense, Serialize, Deserialize)] -//! #[typesense(collection_name = "companies", default_sorting_field = "num_employees")] -//! struct Company { -//! company_name: String, -//! num_employees: i32, -//! #[typesense(facet)] -//! country: String, -//! } +//! use serde::{Deserialize, Serialize}; +//! use typesense::{Client, Typesense, ExponentialBackoff, prelude::*}; +//! use std::time::Duration; +//! +//! /// A struct representing a company document. +//! #[derive(Typesense, Serialize, Deserialize, Debug)] +//! #[typesense( +//! collection_name = "companies", +//! default_sorting_field = "num_employees" +//! )] +//! struct Company { +//! company_name: String, +//! num_employees: i32, +//! #[typesense(facet)] +//! country: String, +//! } +//! +//! #[tokio::main] +//! async fn main() -> Result<(), Box> { +//! let client = Client::builder() +//! .nodes(vec!["http://localhost:8108"]) +//! .api_key("xyz") +//! .healthcheck_interval(Duration::from_secs(60)) +//! .retry_policy(ExponentialBackoff::builder().build_with_max_retries(3)) +//! .connection_timeout(Duration::from_secs(5)) +//! .build()?; +//! +//! // Create the collection in Typesense +//! let collection = client +//! .collections() +//! .create(Company::collection_schema()) +//! .await?; //! -//! #[tokio::main] -//! async fn main() { -//! let config = Configuration { -//! base_path: "http://localhost:5000".to_owned(), -//! api_key: Some(ApiKey { -//! prefix: None, -//! key: "VerySecretKey".to_owned(), -//! }), -//! ..Default::default() -//! }; -//! -//! let collection = collections_api::create_collection(&config, Company::collection_schema()) -//! .await -//! .unwrap(); +//! println!("Created collection: {:?}", collection); +//! Ok(()) +//! } //! } +//! ``` +//! +//! --- +//! +//! ### WebAssembly (Wasm) +//! +//! This example is tailored for a WebAssembly target. +//! Key difference: Tokio-dependent features like `.retry_policy()` and `.connection_timeout()` +//! are disabled. You can still set them in the client builder but it will do nothing. +//! +//! ```no_run +//! #[cfg(target_family = "wasm")] +//! { +//! use serde::{Deserialize, Serialize}; +//! use typesense::{Client, Typesense, prelude::*}; +//! use std::time::Duration; +//! use wasm_bindgen_futures::spawn_local; +//! +//! /// A struct representing a company document. +//! #[derive(Typesense, Serialize, Deserialize, Debug)] +//! #[typesense( +//! collection_name = "companies", +//! default_sorting_field = "num_employees" +//! )] +//! struct Company { +//! company_name: String, +//! num_employees: i32, +//! #[typesense(facet)] +//! country: String, +//! } +//! +//! fn main() { +//! spawn_local(async { +//! let client = Client::builder() +//! .nodes(vec!["http://localhost:8108"]) +//! .api_key("xyz") +//! .healthcheck_interval(Duration::from_secs(60)) +//! // .retry_policy(...) <-- disabled in Wasm +//! // .connection_timeout(...) <-- disabled in Wasm +//! .build() +//! .unwrap(); +//! +//! // Create the collection in Typesense +//! match client.collections().create(Company::collection_schema()).await { +//! Ok(collection) => println!("Created collection: {:?}", collection), +//! Err(e) => eprintln!("Error creating collection: {}", e), +//! } +//! }); +//! } //! } //! ``` +mod client; +mod traits; + +pub mod error; +pub mod models; +pub mod prelude; -pub mod collection_schema; -pub mod document; -pub mod field; -pub mod keys; +pub use client::{Client, ExponentialBackoff}; +pub use error::*; -pub use typesense_codegen::*; +pub use typesense_codegen as legacy; #[cfg(feature = "typesense_derive")] #[doc(hidden)] diff --git a/typesense/src/models/document_index_parameters.rs b/typesense/src/models/document_index_parameters.rs new file mode 100644 index 0000000..cee7a4a --- /dev/null +++ b/typesense/src/models/document_index_parameters.rs @@ -0,0 +1,25 @@ +use serde::{Deserialize, Serialize}; + +/// Parameters for indexing documents into a Typesense collection. +/// +/// These parameters control how Typesense handles special cases such as +/// malformed, invalid, or "dirty" values during indexing. +/// +/// See the official Typesense documentation: +/// +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +pub struct DocumentIndexParameters { + /// Controls how Typesense handles "dirty values" (e.g. invalid dates, + /// numbers where a string is expected, values that don't match the schema). + /// + /// If `None`, Typesense will use the default behavior (rejecting invalid data). + #[serde(rename = "dirty_values", skip_serializing_if = "Option::is_none")] + pub dirty_values: Option, +} + +impl DocumentIndexParameters { + /// Creates a new `DocumentIndexParameters`. + pub fn new() -> DocumentIndexParameters { + DocumentIndexParameters { dirty_values: None } + } +} diff --git a/typesense/src/models/mod.rs b/typesense/src/models/mod.rs new file mode 100644 index 0000000..b41caf3 --- /dev/null +++ b/typesense/src/models/mod.rs @@ -0,0 +1,10 @@ +//! # Typesense generic models +mod document_index_parameters; +mod multi_search; +mod scoped_key_parameters; + +pub use document_index_parameters::*; +pub use scoped_key_parameters::*; +pub use typesense_codegen::models::*; + +pub use multi_search::MultiSearchBody; diff --git a/typesense/src/models/multi_search.rs b/typesense/src/models/multi_search.rs new file mode 100644 index 0000000..4efe08c --- /dev/null +++ b/typesense/src/models/multi_search.rs @@ -0,0 +1,14 @@ +use serde::{Deserialize, Serialize}; +use typesense_codegen::models::MultiSearchCollectionParameters; + +/// Represents the body of a multi-search request. +/// +/// This struct acts as a container for a list of individual search queries that will be +/// sent to the Typesense multi-search endpoint. Each search query is defined in a +/// `MultiSearchCollectionParameters` struct within the `searches` vector. +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, bon::Builder)] +pub struct MultiSearchBody { + /// A vector of individual search queries to be executed. The order of the search results returned by Typesense will match the order of these queries. + #[serde(rename = "searches")] + pub searches: Vec, +} diff --git a/typesense/src/models/scoped_key_parameters.rs b/typesense/src/models/scoped_key_parameters.rs new file mode 100644 index 0000000..0d2e168 --- /dev/null +++ b/typesense/src/models/scoped_key_parameters.rs @@ -0,0 +1,24 @@ +use crate::models::SearchParameters; +use serde::Serialize; + +/// Defines the parameters for generating a scoped API key. +/// +/// A scoped key is a temporary, client-side key that has a specific set of +/// search restrictions and an optional expiration time embedded within it. It allows +/// you to delegate search permissions securely without exposing your main API key. +#[derive(Debug, Clone, Default, Serialize)] +pub struct ScopedKeyParameters { + /// The search parameters to embed in the key. These parameters will be + /// enforced for all searches made with the generated key. + /// For example, you can use `filter_by` to restrict searches to a subset of documents. + #[serde(flatten, skip_serializing_if = "Option::is_none")] + pub search_params: Option, + + /// The number of `multi_search` requests that can be performed using this key. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit_multi_searches: Option, + + /// The Unix timestamp (in seconds) after which the generated key will expire. + #[serde(skip_serializing_if = "Option::is_none")] + pub expires_at: Option, +} diff --git a/typesense/src/prelude.rs b/typesense/src/prelude.rs new file mode 100644 index 0000000..9552070 --- /dev/null +++ b/typesense/src/prelude.rs @@ -0,0 +1,9 @@ +//! The Typesense prelude. +//! +//! This module re-exports the most commonly used traits and types from the library, +//! making them easy to import with a single `use` statement. + +pub use crate::traits::*; + +// pub use crate::error::Error as TypesenseError; +// pub use crate::error::MultiSearchParseError; diff --git a/typesense/src/document.rs b/typesense/src/traits/document.rs similarity index 83% rename from typesense/src/document.rs rename to typesense/src/traits/document.rs index e26a53a..ace35f2 100644 --- a/typesense/src/document.rs +++ b/typesense/src/traits/document.rs @@ -3,12 +3,15 @@ //! In Typesense, documents are each one of the JSON elements that are stored in the collections. //! A document to be indexed in a given collection must conform to the schema of the collection. //! -use crate::collection_schema::CollectionSchema; +use crate::models::CollectionSchema; use serde::{Serialize, de::DeserializeOwned}; /// Trait that should implement every struct that wants to be represented as a Typesense /// Document pub trait Document: DeserializeOwned + Serialize { + /// Collection name + const COLLECTION_NAME: &'static str; + /// Collection schema associated with the document. fn collection_schema() -> CollectionSchema; } diff --git a/typesense/src/field/field_type.rs b/typesense/src/traits/field_type.rs similarity index 95% rename from typesense/src/field/field_type.rs rename to typesense/src/traits/field_type.rs index 3150ad9..9185828 100644 --- a/typesense/src/field/field_type.rs +++ b/typesense/src/traits/field_type.rs @@ -1,5 +1,4 @@ use std::collections::{BTreeMap, HashMap}; - /// Type for a field. Currently it is a wrapping to a `String` but it could be extended to a enum pub type FieldType = String; @@ -14,7 +13,7 @@ pub trait ToTypesenseField { #[macro_export] macro_rules! impl_to_typesense_field ( ($for:ty, $typesense_variant:expr) => { - impl $crate::field::ToTypesenseField for $for { + impl $crate::prelude::ToTypesenseField for $for { #[inline(always)] fn to_typesense_type() -> &'static str { $typesense_variant @@ -22,7 +21,7 @@ macro_rules! impl_to_typesense_field ( } }; ($for:ty, $typesense_variant:expr, $any:ident) => { - impl<$any> $crate::field::ToTypesenseField for $for { + impl<$any> $crate::prelude::ToTypesenseField for $for { #[inline(always)] fn to_typesense_type() -> &'static str { $typesense_variant diff --git a/typesense/src/traits/mod.rs b/typesense/src/traits/mod.rs new file mode 100644 index 0000000..667128e --- /dev/null +++ b/typesense/src/traits/mod.rs @@ -0,0 +1,9 @@ +//! Contains the core traits and extensions for Typesense client operations + +mod document; +mod field_type; +mod multi_search_ext; + +pub use document::Document; +pub use field_type::*; +pub use multi_search_ext::MultiSearchResultExt; diff --git a/typesense/src/traits/multi_search_ext.rs b/typesense/src/traits/multi_search_ext.rs new file mode 100644 index 0000000..7f47cf7 --- /dev/null +++ b/typesense/src/traits/multi_search_ext.rs @@ -0,0 +1,125 @@ +use crate::models::{MultiSearchResult, MultiSearchResultItem, SearchGroupedHit, SearchResultHit}; +use serde::de::DeserializeOwned; +use serde_json::Value; + +use crate::{MultiSearchParseError, models::SearchResult}; + +/// An extension trait for `MultiSearchResult` to provide typed parsing. +pub trait MultiSearchResultExt { + /// Parses the result at a specific index from a multi-search response into a strongly-typed `SearchResult`. + /// + /// # Arguments + /// * `index` - The zero-based index of the search result to parse. + /// + /// # Type Parameters + /// * `D` - The concrete document type to deserialize the hits into. + fn parse_at( + &self, + index: usize, + ) -> Result, MultiSearchParseError>; +} + +/// Small helpers to convert documents stored as `serde_json::Value` into a concrete `D`. +fn deserialize_opt_document( + doc: Option, +) -> Result, serde_json::Error> { + match doc { + Some(v) => Ok(Some(serde_json::from_value(v)?)), + None => Ok(None), + } +} + +fn convert_hit_ref( + raw_hit: &SearchResultHit, +) -> Result, serde_json::Error> { + Ok(SearchResultHit { + document: deserialize_opt_document(raw_hit.document.clone())?, + highlights: raw_hit.highlights.clone(), + highlight: raw_hit.highlight.clone(), + text_match: raw_hit.text_match, + text_match_info: raw_hit.text_match_info.clone(), + geo_distance_meters: raw_hit.geo_distance_meters.clone(), + vector_distance: raw_hit.vector_distance, + hybrid_search_info: raw_hit.hybrid_search_info.clone(), + search_index: raw_hit.search_index, + }) +} + +fn convert_group_ref( + raw_group: &SearchGroupedHit, +) -> Result, serde_json::Error> { + let hits = raw_group + .hits + .iter() + .map(convert_hit_ref::) + .collect::, _>>()?; + + Ok(SearchGroupedHit { + found: raw_group.found, + group_key: raw_group.group_key.clone(), + hits, + }) +} + +/// Convert a single `MultiSearchResultItem` into a strongly-typed `SearchResult`. +fn multi_search_item_to_search_result( + item: &MultiSearchResultItem, +) -> Result, serde_json::Error> { + let typed_hits = match &item.hits { + Some(raw_hits) => Some( + raw_hits + .iter() + .map(convert_hit_ref::) + .collect::, _>>()?, + ), + None => None, + }; + + let typed_grouped_hits = match &item.grouped_hits { + Some(raw_groups) => Some( + raw_groups + .iter() + .map(convert_group_ref::) + .collect::, _>>()?, + ), + None => None, + }; + + Ok(SearchResult { + hits: typed_hits, + grouped_hits: typed_grouped_hits, + facet_counts: item.facet_counts.clone(), + found: item.found, + found_docs: item.found_docs, + out_of: item.out_of, + page: item.page, + search_time_ms: item.search_time_ms, + search_cutoff: item.search_cutoff, + request_params: item.request_params.clone(), + conversation: item.conversation.clone(), + union_request_params: item.union_request_params.clone(), + }) +} + +/// Extension to parse an item out of a `MultiSearchResult` into a typed `SearchResult`. +impl MultiSearchResultExt for MultiSearchResult { + fn parse_at( + &self, + index: usize, + ) -> Result, MultiSearchParseError> { + let raw_item = self + .results + .get(index) + .ok_or(MultiSearchParseError::IndexOutOfBounds(index))?; + + if let Some(error_msg) = &raw_item.error { + return Err(MultiSearchParseError::ApiError { + index, + message: error_msg.clone(), + }); + } + + multi_search_item_to_search_result(raw_item) + .map_err(|source| MultiSearchParseError::Deserialization { index, source }) + } +} diff --git a/typesense/tests/api/collection.rs b/typesense/tests/api/collection.rs deleted file mode 100644 index 23016fd..0000000 --- a/typesense/tests/api/collection.rs +++ /dev/null @@ -1,136 +0,0 @@ -#![allow(dead_code)] - -use super::Config; -use serde::{Deserialize, Serialize}; -use typesense::Typesense; -use typesense::document::Document; -use typesense_codegen::apis::collections_api; -use typesense_codegen::models::{CollectionResponse, CollectionSchema}; - -#[derive(Typesense, Serialize, Deserialize)] -#[typesense(collection_name = "companies", default_sorting_field = "num_employees")] -struct Company { - company_name: String, - num_employees: i32, - #[typesense(facet)] - country: String, -} - -fn schema_to_resp(schema: CollectionSchema, resp: &CollectionResponse) -> CollectionResponse { - CollectionResponse { - name: schema.name, - fields: schema.fields, - default_sorting_field: schema.default_sorting_field, - token_separators: schema.token_separators, - enable_nested_fields: schema.enable_nested_fields, - symbols_to_index: schema.symbols_to_index, - num_documents: resp.num_documents, - created_at: resp.created_at, - } -} - -async fn create_collection() { - let collection_schema_response = - collections_api::create_collection(Config::get(), Company::collection_schema()) - .await - .unwrap(); - - assert_eq!(collection_schema_response.num_documents, 0); - assert_eq!( - schema_to_resp(Company::collection_schema(), &collection_schema_response), - collection_schema_response - ); -} - -async fn get_collection() { - let collection_schema_response = collections_api::get_collection(Config::get(), "companies") - .await - .unwrap(); - - assert_eq!(collection_schema_response.num_documents, 1250); - assert_eq!( - schema_to_resp(Company::collection_schema(), &collection_schema_response), - collection_schema_response - ); -} - -async fn delete_collection() { - let collection_schema_response = collections_api::delete_collection(Config::get(), "companies") - .await - .unwrap(); - - assert_eq!(collection_schema_response.num_documents, 1200); - assert_eq!( - schema_to_resp(Company::collection_schema(), &collection_schema_response), - collection_schema_response - ); -} - -async fn get_collections() { - let collection_schema_response = collections_api::get_collections(Config::get()) - .await - .unwrap(); - - assert_eq!(collection_schema_response.len(), 2); -} - -#[cfg(all(feature = "tokio_test", not(target_arch = "wasm32")))] -mod tokio_test { - use super::*; - - #[tokio::test] - async fn create_collection_tokio() { - create_collection().await - } - - #[tokio::test] - async fn get_collection_tokio() { - get_collection().await - } - - #[tokio::test] - async fn delete_collection_tokio() { - delete_collection().await - } - - #[tokio::test] - async fn get_collections_tokio() { - get_collections().await - } -} - -#[cfg(target_arch = "wasm32")] -mod wasm_test { - use super::*; - use wasm_bindgen_test::wasm_bindgen_test; - - wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); - - #[wasm_bindgen_test] - async fn create_collection_wasm() { - console_error_panic_hook::set_once(); - - create_collection().await - } - - #[wasm_bindgen_test] - async fn get_collection_wasm() { - console_error_panic_hook::set_once(); - - get_collection().await - } - - #[wasm_bindgen_test] - async fn delete_collection_wasm() { - console_error_panic_hook::set_once(); - - delete_collection().await - } - - #[wasm_bindgen_test] - async fn get_collections_wasm() { - console_error_panic_hook::set_once(); - - get_collections().await - } -} diff --git a/typesense/tests/api/documents.rs b/typesense/tests/api/documents.rs deleted file mode 100644 index 8e3b01a..0000000 --- a/typesense/tests/api/documents.rs +++ /dev/null @@ -1,111 +0,0 @@ -#![allow(dead_code)] - -use super::Config; -use serde::{Deserialize, Serialize}; -use typesense::Typesense; -use typesense::document::Document; -use typesense::models::SearchParameters; -use typesense_codegen::apis::documents_api; - -#[derive(Typesense, Serialize, Deserialize)] -#[typesense(collection_name = "companies", default_sorting_field = "num_employees")] -struct Company { - company_name: String, - num_employees: i32, - #[typesense(facet)] - country: String, -} - -async fn import_documents() { - let documents = [ - Company { - company_name: "test".to_owned(), - num_employees: 1, - country: "c1".to_owned(), - }, - Company { - company_name: "test2".to_owned(), - num_employees: 2, - country: "c2".to_owned(), - }, - ] - .map(|c| serde_json::to_string(&c).unwrap()) - .join("\n"); - - let resp = documents_api::import_documents( - Config::get(), - &Company::collection_schema().name, - documents, - None, - ) - .await - .unwrap(); - - assert_eq!(&resp, "{\"success\":true}\n{\"success\":true}"); -} - -async fn search_collection() { - let search = SearchParameters { - q: "test".to_owned(), - query_by: "company_name".to_owned(), - ..Default::default() - }; - - let resp = documents_api::search_collection::( - Config::get(), - &Company::collection_schema().name, - search, - ) - .await - .unwrap(); - - assert_eq!(resp.found, Some(2)); - assert_eq!( - resp.hits - .unwrap() - .first() - .unwrap() - .document - .as_ref() - .unwrap() - .company_name, - "test".to_owned() - ); -} - -#[cfg(all(feature = "tokio_test", not(target_arch = "wasm32")))] -mod tokio_test { - use super::*; - - #[tokio::test] - async fn import_documents_tokio() { - import_documents().await - } - - #[tokio::test] - async fn search_collection_tokio() { - search_collection().await - } -} - -#[cfg(target_arch = "wasm32")] -mod wasm_test { - use super::*; - use wasm_bindgen_test::wasm_bindgen_test; - - wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); - - #[wasm_bindgen_test] - async fn import_documents_wasm() { - console_error_panic_hook::set_once(); - - import_documents().await - } - - #[wasm_bindgen_test] - async fn search_collection_wasm() { - console_error_panic_hook::set_once(); - - search_collection().await - } -} diff --git a/typesense/tests/api/lib.rs b/typesense/tests/api/lib.rs deleted file mode 100644 index 94a3985..0000000 --- a/typesense/tests/api/lib.rs +++ /dev/null @@ -1,41 +0,0 @@ -use std::sync::OnceLock; -use typesense_codegen::apis::configuration::{ApiKey, Configuration}; - -mod collection; -mod documents; - -static CONFIG: OnceLock = OnceLock::new(); - -#[cfg(not(target_arch = "wasm32"))] -fn init() -> Configuration { - let _ = dotenvy::dotenv(); - - let base_path = std::env::var("URL").expect("URL must be present in .env"); - let key = std::env::var("API_KEY").expect("API_KEY must be present in .env"); - - Configuration { - base_path, - api_key: Some(ApiKey { prefix: None, key }), - ..Default::default() - } -} - -#[cfg(target_arch = "wasm32")] -fn init() -> Configuration { - let base_path = "http://localhost:5000".to_owned(); - let key = "VerySecretKey".to_owned(); - - Configuration { - base_path, - api_key: Some(ApiKey { prefix: None, key }), - ..Default::default() - } -} - -pub struct Config; - -impl Config { - pub fn get() -> &'static Configuration { - CONFIG.get_or_init(init) - } -} diff --git a/typesense/tests/client/client_test.rs b/typesense/tests/client/client_test.rs new file mode 100644 index 0000000..05f3883 --- /dev/null +++ b/typesense/tests/client/client_test.rs @@ -0,0 +1,310 @@ +#![cfg(not(target_family = "wasm"))] + +use reqwest_retry::policies::ExponentialBackoff; +use std::time::Duration; +use typesense::{models::CollectionResponse, *}; +use wiremock::{ + Mock, MockServer, ResponseTemplate, + matchers::{header, method, path}, +}; + +// Helper to create a mock Typesense server for a successful collection retrieval. +async fn setup_mock_server_ok(server: &MockServer, collection_name: &str) { + let response_body = CollectionResponse { + name: collection_name.to_owned(), + ..Default::default() + }; + + Mock::given(method("GET")) + .and(path(format!("/collections/{}", collection_name))) + .and(header("X-TYPESENSE-API-KEY", "test-key")) + .respond_with(ResponseTemplate::new(200).set_body_json(response_body)) + .mount(server) + .await; +} + +// Helper to create a mock Typesense server that returns a server error. +async fn setup_mock_server_503(server: &MockServer, collection_name: &str) { + Mock::given(method("GET")) + .and(path(format!("/collections/{}", collection_name))) + .respond_with(ResponseTemplate::new(503)) + .mount(server) + .await; +} + +// Helper to create a mock Typesense server that returns a 404 Not Found error. +async fn setup_mock_server_404(server: &MockServer, collection_name: &str) { + Mock::given(method("GET")) + .and(path(format!("/collections/{}", collection_name))) + .respond_with(ResponseTemplate::new(404)) + .mount(server) + .await; +} + +// Helper function to create a client configuration for tests. +fn get_client(nodes: Vec, nearest_node: Option) -> Client { + Client::builder() + .nodes(nodes) + .maybe_nearest_node(nearest_node) + .api_key("test-key") + .healthcheck_interval(Duration::from_secs(60)) + .retry_policy(ExponentialBackoff::builder().build_with_max_retries(0)) + .connection_timeout(Duration::from_secs(1)) + .build() + .expect("Failed to create client") +} + +#[tokio::test] +async fn test_success_on_first_node() { + let server1 = MockServer::start().await; + setup_mock_server_ok(&server1, "products").await; + + let client = get_client(vec![server1.uri()], None); + + let result = client.collection_schemaless("products").retrieve().await; + + assert!(result.is_ok()); + assert_eq!(result.unwrap().name, "products"); + // Check that the server received exactly one request. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); +} + +#[tokio::test] +async fn test_failover_to_second_node() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + setup_mock_server_503(&server1, "products").await; + setup_mock_server_ok(&server2, "products").await; + + let client = get_client(vec![server1.uri(), server2.uri()], None); + + let result = client.collection_schemaless("products").retrieve().await; + assert!(result.is_ok()); + + // The first server should have been tried and failed. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + // The second server should have been tried and succeeded. + assert_eq!(server2.received_requests().await.unwrap().len(), 1); +} + +#[tokio::test] +async fn test_nearest_node_is_prioritized() { + let nearest_server = MockServer::start().await; + let regular_server = MockServer::start().await; + setup_mock_server_ok(&nearest_server, "products").await; + setup_mock_server_ok(®ular_server, "products").await; + + let client = get_client(vec![regular_server.uri()], Some(nearest_server.uri())); + + let result = client.collection_schemaless("products").retrieve().await; + assert!(result.is_ok()); + + // Only the nearest node should have received a request. + assert_eq!(nearest_server.received_requests().await.unwrap().len(), 1); + assert_eq!(regular_server.received_requests().await.unwrap().len(), 0); +} + +#[tokio::test] +async fn test_failover_from_nearest_to_regular_node() { + let nearest_server = MockServer::start().await; + let regular_server = MockServer::start().await; + setup_mock_server_503(&nearest_server, "products").await; + setup_mock_server_ok(®ular_server, "products").await; + + let client = get_client(vec![regular_server.uri()], Some(nearest_server.uri())); + + let result = client.collection_schemaless("products").retrieve().await; + assert!(result.is_ok()); + + // Nearest node should have failed. + assert_eq!(nearest_server.received_requests().await.unwrap().len(), 1); + // Regular node should have succeeded. + assert_eq!(regular_server.received_requests().await.unwrap().len(), 1); +} + +#[tokio::test] +async fn test_round_robin_failover() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + let server3 = MockServer::start().await; + setup_mock_server_503(&server1, "products").await; + setup_mock_server_503(&server2, "products").await; + setup_mock_server_ok(&server3, "products").await; + + let client = get_client(vec![server1.uri(), server2.uri(), server3.uri()], None); + + // First request should fail over to the third node + assert!( + client + .collection_schemaless("products") + .retrieve() + .await + .is_ok() + ); + + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + assert_eq!(server2.received_requests().await.unwrap().len(), 1); + assert_eq!(server3.received_requests().await.unwrap().len(), 1); + + // The next request should start from the now-healthy 3rd node, but round-robin + // logic will have advanced the internal counter. Let's see it wrap around. + // We expect the next attempt to be on server 3 again, then 1 (if 3 fails). + + // Reset server 3 to also fail + server3.reset().await; + setup_mock_server_503(&server3, "products").await; + // Make server 2 healthy again + server2.reset().await; + setup_mock_server_ok(&server2, "products").await; + + assert!( + client + .collection_schemaless("products") + .retrieve() + .await + .is_ok() + ); + + // Server 3 was tried first and failed. + assert_eq!(server3.received_requests().await.unwrap().len(), 1); + // Server 2 was tried next and succeeded. + assert_eq!(server2.received_requests().await.unwrap().len(), 1); + // Server 1 was not touched this time. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); // Remains 1 from first call +} + +#[tokio::test] +async fn test_health_check_and_node_recovery() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + + setup_mock_server_503(&server1, "products").await; + setup_mock_server_ok(&server2, "products").await; + + let client = Client::builder() + .nodes(vec![server1.uri(), server2.uri()]) + .api_key("test-key") + .healthcheck_interval(Duration::from_millis(500)) // Use a very short healthcheck interval for the test + .retry_policy(ExponentialBackoff::builder().build_with_max_retries(0)) + .connection_timeout(Duration::from_secs(1)) + .build() + .expect("Failed to create client"); + + // 1. First request fails over to server2, marking server1 as unhealthy. + assert!( + client + .collection_schemaless("products") + .retrieve() + .await + .is_ok() + ); + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + assert_eq!(server2.received_requests().await.unwrap().len(), 1); + + // 2. Immediate second request should go directly to server2. + assert!( + client + .collection_schemaless("products") + .retrieve() + .await + .is_ok() + ); + assert_eq!(server1.received_requests().await.unwrap().len(), 1); // No new request + assert_eq!(server2.received_requests().await.unwrap().len(), 2); // Got another request + + // 3. Wait for the healthcheck interval to pass. + tokio::time::sleep(Duration::from_millis(501)).await; + + // 4. Make server1 healthy again. + server1.reset().await; + setup_mock_server_ok(&server1, "products").await; + + // 5. The next request should try server1 again (due to healthcheck expiry) and succeed. + assert!( + client + .collection_schemaless("products") + .retrieve() + .await + .is_ok() + ); + assert_eq!(server1.received_requests().await.unwrap().len(), 1); // Server 1 received its first successful req + assert_eq!(server2.received_requests().await.unwrap().len(), 2); // No new request for server 2 +} + +#[tokio::test] +async fn test_all_nodes_fail() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + setup_mock_server_503(&server1, "products").await; + setup_mock_server_503(&server2, "products").await; + + let client = get_client(vec![server1.uri(), server2.uri()], None); + + let result = client.collection_schemaless("products").retrieve().await; + assert!(result.is_err()); + + match result.err().unwrap() { + Error::AllNodesFailed { .. } => { /* This is the expected outcome */ } + _ => panic!("Expected AllNodesFailed error"), + } + + // Both servers should have been tried. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + assert_eq!(server2.received_requests().await.unwrap().len(), 1); +} + +#[tokio::test] +async fn test_fail_fast_on_non_retriable_error() { + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + + setup_mock_server_404(&server1, "products").await; + setup_mock_server_ok(&server2, "products").await; + + let client = get_client(vec![server1.uri(), server2.uri()], None); + + let result = client.collection_schemaless("products").retrieve().await; + assert!(result.is_err()); + + // Check that the error is the non-retriable API error. + match result.err().unwrap() { + Error::Api(typesense_codegen::apis::Error::ResponseError(content)) => { + assert_eq!(content.status, reqwest::StatusCode::NOT_FOUND); + } + e => panic!("Expected an API error, but got {:?}", e), + } + + // The first server should have been tried. + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + // The second server should NOT have been tried. + assert_eq!(server2.received_requests().await.unwrap().len(), 0); +} + +#[tokio::test] +async fn test_load_balancing_with_healthy_nodes() { + // 1. Setup three healthy mock servers + let server1 = MockServer::start().await; + let server2 = MockServer::start().await; + let server3 = MockServer::start().await; + setup_mock_server_ok(&server1, "products").await; + setup_mock_server_ok(&server2, "products").await; + setup_mock_server_ok(&server3, "products").await; + + // 2. Setup client with the three nodes + let client = get_client(vec![server1.uri(), server2.uri(), server3.uri()], None); + + // 3. Make three consecutive requests + let result1 = client.collection_schemaless("products").retrieve().await; + let result2 = client.collection_schemaless("products").retrieve().await; + let result3 = client.collection_schemaless("products").retrieve().await; + + // 4. Assert all requests were successful + assert!(result1.is_ok()); + assert!(result2.is_ok()); + assert!(result3.is_ok()); + + // 5. Assert that each server received exactly one request, proving round-robin distribution + assert_eq!(server1.received_requests().await.unwrap().len(), 1); + assert_eq!(server2.received_requests().await.unwrap().len(), 1); + assert_eq!(server3.received_requests().await.unwrap().len(), 1); +} diff --git a/typesense/tests/client/collections_test.rs b/typesense/tests/client/collections_test.rs new file mode 100644 index 0000000..70d471c --- /dev/null +++ b/typesense/tests/client/collections_test.rs @@ -0,0 +1,174 @@ +use typesense::models::{ + CollectionSchema, CollectionUpdateSchema, Field, GetCollectionsParameters, +}; + +use super::{get_client, new_id}; + +async fn logic_test_collections_and_collection_lifecycle() { + let client = get_client(); + let collection_name = new_id("products"); + + // --- 1. Create a Collection (via `collections`) --- + let schema = CollectionSchema { + name: collection_name.clone(), + fields: vec![ + Field { + name: "name".to_owned(), + r#type: "string".to_owned(), + ..Default::default() + }, + Field { + name: "price".to_owned(), + r#type: "int32".to_owned(), + ..Default::default() + }, + ], + ..Default::default() + }; + + let create_result = client.collections().create(schema).await; + assert!(create_result.is_ok(), "Failed to create collection"); + let created_collection = create_result.unwrap(); + assert_eq!(created_collection.name, collection_name); + + // --- 2. Retrieve the specific Collection (via `collection`) --- + let retrieve_one_result = client + .collection_schemaless(&collection_name) + .retrieve() + .await; + assert!( + retrieve_one_result.is_ok(), + "Failed to retrieve the newly created collection." + ); + let retrieved_collection = retrieve_one_result.unwrap(); + assert_eq!(retrieved_collection.name, collection_name); + assert_eq!(retrieved_collection.fields.len(), 2); + + // --- 3. Retrieve all collections (via `collections`) --- + let retrieve_all_result = client + .collections() + .retrieve(GetCollectionsParameters::default()) + .await; + assert!( + retrieve_all_result.is_ok(), + "Failed to retrieve the list of collections." + ); + let all_collections = retrieve_all_result.unwrap(); + + // --- 4. Find our specific collection within the list --- + let our_collection = all_collections.iter().find(|c| c.name == collection_name); + assert!( + our_collection.is_some(), + "The newly created collection was not found in the list." + ); + + // --- 5. Update the Collection to add and drop a field (via `collection`) --- + let update_schema = CollectionUpdateSchema { + fields: vec![ + // Add a new field + Field { + name: "description".to_owned(), + r#type: "string".to_owned(), + optional: Some(true), + ..Default::default() + }, + // Drop an existing field + Field { + name: "price".to_owned(), + drop: Some(true), + ..Default::default() + }, + ], + ..Default::default() + }; + + let update_result = client + .collection_schemaless(&collection_name) + .update(update_schema) + .await; + assert!(update_result.is_ok(), "Failed to update collection"); + + // The update response contains the fields that were modified + let updated_fields_response = update_result.unwrap(); + assert_eq!( + updated_fields_response.fields.len(), + 2, + "The update response should contain the two modified fields." + ); + + // --- 6. Verify the update by retrieving the full schema again --- + let retrieve_after_update_result = client + .collection_schemaless(&collection_name) + .retrieve() + .await; + let retrieved_after_update = retrieve_after_update_result.unwrap(); + + // Initial fields: name, price. Update: +description, -price. Final fields: name, description. + assert_eq!( + retrieved_after_update.fields.len(), + 2, + "The number of fields should be 2 after the update." + ); + assert!( + retrieved_after_update + .fields + .iter() + .any(|f| f.name == "name"), + "The 'name' field should still exist." + ); + assert!( + retrieved_after_update + .fields + .iter() + .any(|f| f.name == "description"), + "The 'description' field should have been added." + ); + assert!( + !retrieved_after_update + .fields + .iter() + .any(|f| f.name == "price"), + "The 'price' field should have been dropped." + ); + + // --- 7. Delete the Collection (via `collection`) --- + let delete_result = client + .collection_schemaless(&collection_name) + .delete() + .await; + assert!(delete_result.is_ok(), "Failed to delete collection"); + + // --- 8. Verify Deletion --- + let get_after_delete_result = client + .collection_schemaless(&collection_name) + .retrieve() + .await; + assert!( + get_after_delete_result.is_err(), + "Collection should not exist after deletion" + ); +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tokio_test { + use super::*; + + #[tokio::test] + async fn test_collections_and_collection_lifecycle() { + logic_test_collections_and_collection_lifecycle().await; + } +} + +#[cfg(all(test, target_arch = "wasm32"))] +mod wasm_test { + use super::*; + use wasm_bindgen_test::wasm_bindgen_test; + + wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); + + #[wasm_bindgen_test] + async fn test_collections_and_collection_lifecycle() { + console_error_panic_hook::set_once(); + logic_test_collections_and_collection_lifecycle().await; + } +} diff --git a/typesense/tests/client/documents_test.rs b/typesense/tests/client/documents_test.rs new file mode 100644 index 0000000..04040a6 --- /dev/null +++ b/typesense/tests/client/documents_test.rs @@ -0,0 +1,374 @@ +use serde::{Deserialize, Serialize}; +use serde_json::json; +use typesense::models::{ + CollectionSchema, DeleteDocumentsParameters, DirtyValues, DocumentIndexParameters, + ExportDocumentsParameters, Field, ImportDocumentsParameters, IndexAction, SearchParameters, + UpdateDocumentsParameters, +}; + +use super::{get_client, new_id}; + +async fn run_test_document_lifecycle() { + let client = get_client(); + let collection_name = new_id("books"); + + // --- 1. Setup: Create a Collection --- + let schema = CollectionSchema { + name: collection_name.clone(), + fields: vec![ + Field { + name: "title".to_owned(), + r#type: "string".to_owned(), + ..Default::default() + }, + Field { + name: "author".to_owned(), + r#type: "string".to_owned(), + facet: Some(true), + ..Default::default() + }, + Field { + name: "publication_year".to_owned(), + r#type: "int32".to_owned(), + ..Default::default() + }, + ], + ..Default::default() + }; + + let create_collection_result = client.collections().create(schema).await; + assert!( + create_collection_result.is_ok(), + "Failed to create collection" + ); + + let book_1_id = &new_id("document_1"); + let book_1 = json!({ + "id": book_1_id, + "title": "The Hitchhiker's Guide to the Galaxy", + "author": "Douglas Adams", + "publication_year": 1979 + }); + + let book_2 = json!({ + "title": "The Lord of the Rings", + "author": "J.R.R. Tolkien", + "publication_year": 1954 + }); + let collection_client = client.collection_schemaless(&collection_name); + let documents_client = collection_client.documents(); + + // --- 2. Create a document (via `documents().create()`) --- + let create_res = documents_client.create(&book_1, None).await; + assert!(create_res.is_ok(), "Failed to create document 1"); + + // --- 3. Upsert a document (via `documents().upsert()`) --- + let upsert_res = documents_client.upsert(&book_2, None).await; + assert!(upsert_res.is_ok(), "Failed to upsert document 2"); + + // --- 4. Retrieve a single document (via `document(id).retrieve()`) --- + let retrieve_res = client + .collection_schemaless(&collection_name) + .document(book_1_id) + .retrieve() + .await; + assert!(retrieve_res.is_ok(), "Failed to retrieve document 1"); + assert_eq!(retrieve_res.unwrap(), book_1); + + // --- 5. Search for documents --- + let search_params = SearchParameters::builder() + .q("the") + .query_by("title") + .build(); + let search_res = documents_client.search(search_params).await; + assert!(search_res.is_ok(), "Search failed"); + assert_eq!(search_res.unwrap().found, Some(2)); + + // --- 6. Update a single document --- + let partial_update = json!({ "publication_year": 1980 }); + let update_res = client + .collection_schemaless(&collection_name) + .document(book_1_id) + .update(&partial_update, None) + .await; + assert!(update_res.is_ok(), "Failed to update document 1"); + + // --- 7. Verify the single update --- + let retrieve_after_update_res = client + .collection_schemaless(&collection_name) + .document(book_1_id) + .retrieve() + .await; + let updated_doc = retrieve_after_update_res.unwrap(); + assert_eq!( + updated_doc.get("publication_year").unwrap().as_i64(), + Some(1980) + ); + + // --- 8. Delete a single document --- + let delete_res = client + .collection_schemaless(&collection_name) + .document(book_1_id) + .delete() + .await; + assert!(delete_res.is_ok(), "Failed to delete document 1"); + + // --- 9. Verify single deletion --- + let retrieve_after_delete_res = client + .collection_schemaless(&collection_name) + .document(book_1_id) + .retrieve() + .await; + assert!( + retrieve_after_delete_res.is_err(), + "Document should not exist after deletion" + ); + + // --- 10. Bulk Import --- + let new_books_jsonl = format!( + "{}\n{}", + json!({"title": "Foundation", "author": "Isaac Asimov", "publication_year": 1951}), + json!({"title": "Dune", "author": "Frank Herbert", "publication_year": 1965}) + ); + + let import_params = ImportDocumentsParameters { + action: Some(IndexAction::Create), + ..Default::default() + }; + let import_res = documents_client + .import_jsonl(new_books_jsonl, import_params) + .await; + assert!(import_res.is_ok(), "Bulk import failed"); + + // --- 11. Verify Import via Search --- + let search_after_import_params = SearchParameters { + q: Some("*".to_owned()), + query_by: Some("title".to_owned()), + ..Default::default() + }; + let search_after_import_res = documents_client.search(search_after_import_params).await; + let search_results = search_after_import_res.unwrap(); + // 1 remaining (book_2) + 2 new imports = 3 + assert_eq!(search_results.found, Some(3)); + + // --- 12. Bulk Update (via `documents().update()`) --- + let bulk_update_params = UpdateDocumentsParameters { + filter_by: Some("publication_year:<1960".to_owned()), + }; + let bulk_update_payload = json!({ "author": "Sci-Fi Pioneer" }); + let bulk_update_res = documents_client + .update(bulk_update_payload, bulk_update_params) + .await; + assert!(bulk_update_res.is_ok(), "Bulk update failed"); + // Should update Lord of the Rings (1954) and Foundation (1951) + assert_eq!(bulk_update_res.unwrap().num_updated, 2); + + // --- 13. Export documents (via `documents().export()`) --- + let export_params = ExportDocumentsParameters { + filter_by: Some("author:\"Sci-Fi Pioneer\"".to_owned()), + ..Default::default() + }; + let export_res = documents_client.export(export_params).await; + + assert!(export_res.is_ok(), "Export failed"); + let exported_jsonl = export_res.unwrap(); + + // Verify the exported content is a JSONL string with 2 lines. + let lines: Vec<&str> = exported_jsonl.trim().split('\n').collect(); + assert_eq!(lines.len(), 2, "Exported JSONL should have 2 lines"); + let exported_doc_1: serde_json::Value = serde_json::from_str(lines[0]).unwrap(); + assert_eq!(exported_doc_1["author"], "Sci-Fi Pioneer"); + + // --- 14. Bulk Delete --- + let delete_params = DeleteDocumentsParameters { + filter_by: "publication_year:>1960".to_owned(), + ..Default::default() + }; + let bulk_delete_res = documents_client.delete(delete_params).await; + assert!(bulk_delete_res.is_ok(), "Bulk delete failed"); + // Only "Dune" (1965) should be deleted + assert_eq!(bulk_delete_res.unwrap().num_deleted, 1); +} + +// --- TESTS FOR GENERIC FEATURES --- + +/// A strongly-typed representation of a book document. +#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] +struct Book { + id: String, + title: String, + author: String, + publication_year: i32, + #[serde(default, skip_serializing_if = "Option::is_none")] + in_stock: Option, +} + +async fn run_test_generic_document_lifecycle() { + let client = get_client(); + let collection_name = new_id("generic_books"); + + // --- 1. Setup: Create a Collection matching the Book struct --- + let schema = CollectionSchema { + name: collection_name.clone(), + fields: vec![ + Field { + name: "title".to_owned(), + r#type: "string".to_owned(), + ..Default::default() + }, + Field { + name: "author".to_owned(), + r#type: "string".to_owned(), + facet: Some(true), + ..Default::default() + }, + Field { + name: "publication_year".to_owned(), + r#type: "int32".to_owned(), + ..Default::default() + }, + Field { + name: "in_stock".to_owned(), + r#type: "bool".to_owned(), + optional: Some(true), + ..Default::default() + }, + ], + ..Default::default() + }; + + let create_collection_result = client.collections().create(schema).await; + assert!( + create_collection_result.is_ok(), + "Failed to create collection for generic test" + ); + + // Use the strongly-typed collection client + let typed_collection = client.collection_named::(&collection_name); + + let book_1 = Book { + id: new_id("book_1"), + title: "Dune".to_owned(), + author: "Frank Herbert".to_owned(), + publication_year: 1965, + in_stock: Some(true), + }; + + let book_2 = Book { + id: new_id("book_2"), + title: "Foundation".to_owned(), + author: "Isaac Asimov".to_owned(), + publication_year: 1951, + in_stock: Some(false), + }; + + // --- 2. Create a document using a typed struct --- + let create_res = typed_collection.documents().create(&book_1, None).await; + assert!(create_res.is_ok(), "Failed to create typed document"); + // The created document should be returned and be equal to the input + assert_eq!(create_res.unwrap(), book_1); + + // --- 3. Upsert a document using a typed struct --- + let upsert_res = typed_collection.documents().upsert(&book_2, None).await; + assert!(upsert_res.is_ok(), "Failed to upsert typed document"); + assert_eq!(upsert_res.unwrap(), book_2); + + // --- 4. Retrieve a single document and deserialize into a struct --- + let retrieve_res = typed_collection.document(&book_1.id).retrieve().await; + assert!(retrieve_res.is_ok(), "Failed to retrieve typed document"); + assert_eq!(retrieve_res.unwrap(), book_1); + + // --- 5. Search for documents with strongly-typed results --- + let search_params = SearchParameters { + q: Some("dune".to_owned()), + query_by: Some("title".to_owned()), + ..Default::default() + }; + let search_res = typed_collection.documents().search(search_params).await; + assert!(search_res.is_ok(), "Typed search failed"); + let search_results = search_res.unwrap(); + + assert_eq!(search_results.found, Some(1)); + let hits = search_results.hits.expect("Search should have hits"); + assert_eq!(hits.len(), 1); + // The document within the hit should be the deserialized Book struct + let hit_doc = hits[0] + .document + .as_ref() + .expect("Hit should contain a document"); + assert_eq!(hit_doc, &book_1); + + // --- 6. Update a single document with a partial payload --- + #[derive(Serialize)] + struct BookUpdate { + publication_year: i32, + in_stock: bool, + } + let partial_update_struct = BookUpdate { + publication_year: 1966, + in_stock: false, + }; + let index_params = DocumentIndexParameters { + dirty_values: Some(DirtyValues::CoerceOrReject), + }; + let update_res = typed_collection + .document(&book_1.id) + .update(&partial_update_struct, Some(index_params)) + .await; + assert!(update_res.is_ok(), "Failed to update typed document"); + + // The returned document should be the full, updated Book struct + let updated_book = update_res.unwrap(); + assert_eq!(updated_book.publication_year, 1966); + assert_eq!(updated_book.in_stock, Some(false)); + assert_eq!(updated_book.title, book_1.title); // Other fields are preserved + + // --- 7. Delete a single document, receiving the typed struct back --- + let delete_res = typed_collection.document(&book_1.id).delete().await; + assert!(delete_res.is_ok(), "Failed to delete typed document"); + // The deleted document (in its state just before deletion) is returned + let deleted_book = delete_res.unwrap(); + assert_eq!(deleted_book.id, book_1.id); + assert_eq!(deleted_book.publication_year, 1966); // It was the updated version + + // --- 8. Verify single deletion --- + let retrieve_after_delete_res = typed_collection.document(&book_1.id).retrieve().await; + assert!( + retrieve_after_delete_res.is_err(), + "Typed document should not exist after deletion" + ); +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tokio_test { + use super::*; + + #[tokio::test] + async fn test_document_lifecycle() { + run_test_document_lifecycle().await; + } + #[tokio::test] + async fn test_generic_document_lifecycle() { + run_test_generic_document_lifecycle().await; + } +} + +#[cfg(all(test, target_arch = "wasm32"))] +mod wasm_test { + use super::*; + use wasm_bindgen_test::wasm_bindgen_test; + + wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); + + #[wasm_bindgen_test] + async fn test_document_lifecycle() { + console_error_panic_hook::set_once(); + run_test_document_lifecycle().await; + } + + #[wasm_bindgen_test] + async fn test_generic_document_lifecycle() { + console_error_panic_hook::set_once(); + run_test_generic_document_lifecycle().await; + } +} diff --git a/typesense/tests/client/keys_test.rs b/typesense/tests/client/keys_test.rs new file mode 100644 index 0000000..a2f4a21 --- /dev/null +++ b/typesense/tests/client/keys_test.rs @@ -0,0 +1,144 @@ +use super::get_client; +use typesense::models::{ApiKeySchema, ScopedKeyParameters, SearchParameters}; + +async fn run_test_keys_lifecycle() { + let client = get_client(); + let key_description = "A test search-only key."; + + // --- 1. Create a new API Key (via `keys`) --- + let key_schema = ApiKeySchema { + description: key_description.to_owned(), + actions: vec!["documents:search".to_owned()], // Grant only search permissions + collections: vec!["*".to_owned()], // For all collections + ..Default::default() + }; + + let create_result = client.keys().create(key_schema).await; + assert!(create_result.is_ok(), "Failed to create the API key."); + let created_key = create_result.unwrap(); + + // The full key value is only returned on creation + assert!( + created_key.value.is_some(), + "The full API key value should be present upon creation." + ); + assert_eq!(created_key.description, key_description.to_owned()); + + let key_id = created_key.id.unwrap(); + + // --- 2. Retrieve the specific key (via `key`) --- + let retrieve_one_result = client.key(key_id).retrieve().await; + assert!( + retrieve_one_result.is_ok(), + "Failed to retrieve the specific API key." + ); + let retrieved_key = retrieve_one_result.unwrap(); + + // On retrieval, the value should be None and the prefix should be present + assert_eq!(retrieved_key.id.unwrap(), key_id); + assert!( + retrieved_key.value.is_none(), + "The retrieved key should not contain the full value." + ); + assert!( + retrieved_key.value_prefix.is_some(), + "The retrieved key should have a value prefix." + ); + + // --- 3. Retrieve all keys (via `keys`) --- + let retrieve_all_result = client.keys().retrieve().await; + assert!( + retrieve_all_result.is_ok(), + "Failed to retrieve the list of keys." + ); + let all_keys_response = retrieve_all_result.unwrap(); + + // --- 4. Find our specific key within the list --- + let our_key = all_keys_response + .keys + .iter() + .find(|k| k.id.unwrap() == (key_id)); + assert!( + our_key.is_some(), + "The newly created key was not found in the list." + ); + + // --- 5. Delete the key (via `key`) --- + let delete_result = client.key(key_id).delete().await; + assert!(delete_result.is_ok(), "Failed to delete the API key."); + let delete_response = delete_result.unwrap(); + assert_eq!( + delete_response.id, key_id, + "The response from delete should contain the correct key ID." + ); + + // --- 6. Verify Deletion --- + let get_after_delete_result = client.key(key_id).retrieve().await; + assert!( + get_after_delete_result.is_err(), + "API key should not exist after deletion." + ); +} + +#[test] +fn test_generate_scoped_search_key_with_example_values() { + // The parent key with `documents:search` permissions. + let search_only_api_key = "RN23GFr1s6jQ9kgSNg2O7fYcAUXU7127"; + + // The parameters to be embedded in the new scoped key. + let params = ScopedKeyParameters { + search_params: Some(SearchParameters { + filter_by: Some("company_id:124".to_owned()), + ..Default::default() + }), + expires_at: Some(1906054106), + ..Default::default() + }; + + // The known correct output from the Typesense documentation. + let expected_scoped_key = "OW9DYWZGS1Q1RGdSbmo0S1QrOWxhbk9PL2kxbTU1eXA3bCthdmE5eXJKRT1STjIzeyJmaWx0ZXJfYnkiOiJjb21wYW55X2lkOjEyNCIsImV4cGlyZXNfYXQiOjE5MDYwNTQxMDZ9"; + + let client = get_client(); + + let generated_key_result = client + .keys() + .generate_scoped_search_key(search_only_api_key, ¶ms); + + // First, ensure the function returned an Ok result. + assert!( + generated_key_result.is_ok(), + "Function returned an error: {:?}", + generated_key_result.err() + ); + + // Unwrap the result and compare it with the expected output. + let generated_key = generated_key_result.unwrap(); + assert_eq!( + generated_key, expected_scoped_key, + "The generated key does not match the expected key." + ); +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tokio_test { + use super::*; + + #[tokio::test] + async fn test_keys_lifecycle() { + run_test_keys_lifecycle().await; + } +} + +#[cfg(all(test, target_arch = "wasm32"))] +mod wasm_test { + use super::*; + use wasm_bindgen_test::wasm_bindgen_test; + + wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); + + #[wasm_bindgen_test] + async fn test_keys_lifecycle() { + console_error_panic_hook::set_once(); + run_test_keys_lifecycle().await; + } +} diff --git a/typesense/tests/client/mod.rs b/typesense/tests/client/mod.rs new file mode 100644 index 0000000..b466f03 --- /dev/null +++ b/typesense/tests/client/mod.rs @@ -0,0 +1,36 @@ +mod client_test; +mod collections_test; + +mod documents_test; +mod keys_test; +mod multi_search_test; + +use reqwest_retry::policies::ExponentialBackoff; +use std::time::Duration; +use typesense::Client; +use web_time::{SystemTime, UNIX_EPOCH}; + +/// Helper function to create a new client for all tests in this suite. +pub fn get_client() -> Client { + Client::builder() + .nodes(vec!["http://localhost:8108"]) + .api_key("xyz") + .healthcheck_interval(Duration::from_secs(5)) + .retry_policy(ExponentialBackoff::builder().build_with_max_retries(0)) + .connection_timeout(Duration::from_secs(3)) + .build() + .expect("Failed to create Typesense client") +} + +/// Generates a unique name for a test resource by combining a prefix, +/// a timestamp, and a nano id. +/// e.g., "test_collection_123456789_aB1cD2eF" +pub fn new_id(prefix: &str) -> String { + let random_part = nanoid::nanoid!(8); + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis(); + + format!("test_{}_{}_{}", prefix, timestamp, random_part) +} diff --git a/typesense/tests/client/multi_search_test.rs b/typesense/tests/client/multi_search_test.rs new file mode 100644 index 0000000..643ff45 --- /dev/null +++ b/typesense/tests/client/multi_search_test.rs @@ -0,0 +1,524 @@ +use serde::Deserialize; +use typesense::{ + models::{ + CollectionSchema, Field, ImportDocumentsParameters, MultiSearchBody, + MultiSearchCollectionParameters, MultiSearchParameters, SearchResult, + }, + prelude::*, +}; + +use super::{get_client, new_id}; + +async fn setup_multi_search_tests( + client: &typesense::Client, + products_collection_name: &str, + brands_collection_name: &str, +) { + // --- Create collections --- + let products_schema = CollectionSchema { + name: products_collection_name.to_owned(), + fields: vec![ + Field::new("name".to_owned(), "string".to_owned()), + Field::new("price".to_owned(), "int32".to_owned()), + ], + ..Default::default() + }; + client.collections().create(products_schema).await.unwrap(); + + let brands_schema = CollectionSchema { + name: brands_collection_name.to_owned(), + fields: vec![ + Field::new("company_name".to_owned(), "string".to_owned()), + Field::new("country".to_owned(), "string".to_owned()), + ], + ..Default::default() + }; + client.collections().create(brands_schema).await.unwrap(); + + // --- Index documents --- + let product_docs = r#" + {"id": "p1", "name": "iPhone 15", "price": 999} + {"id": "p2", "name": "MacBook Pro", "price": 1999} + "# + .trim() + .lines() + .map(|s| s.trim()) + .collect::>() + .join("\n"); + + client + .collection_schemaless(products_collection_name) + .documents() + .import_jsonl( + product_docs, + ImportDocumentsParameters { + action: Some(typesense::models::IndexAction::Create), + ..Default::default() + }, + ) + .await + .unwrap(); + + let brand_docs = r#" + {"id": "b1", "company_name": "Apple Inc.", "country": "USA"} + {"id": "b2", "company_name": "Samsung", "country": "South Korea"} + "# + .trim() + .lines() + .map(|s| s.trim()) + .collect::>() + .join("\n"); + + client + .collection_schemaless(brands_collection_name) + .documents() + .import_jsonl( + brand_docs, + ImportDocumentsParameters { + action: Some(typesense::models::IndexAction::Create), + ..Default::default() + }, + ) + .await + .unwrap(); +} + +async fn run_test_multi_search_federated() { + let client = get_client(); + let products_collection_name = new_id("products"); + let brands_collection_name = new_id("brands"); + setup_multi_search_tests(&client, &products_collection_name, &brands_collection_name).await; + + let search_requests = MultiSearchBody { + searches: vec![ + MultiSearchCollectionParameters { + q: Some("pro".into()), + query_by: Some("name".into()), + collection: Some(products_collection_name.clone()), + ..Default::default() + }, + MultiSearchCollectionParameters { + q: Some("USA".into()), + query_by: Some("country".into()), + collection: Some(brands_collection_name.clone()), + ..Default::default() + }, + ], + }; + + let common_params = MultiSearchParameters::default(); + + let result = client + .multi_search() + .perform(search_requests, common_params) + .await; + + assert!(result.is_ok(), "Multi-search request failed"); + let response = result.unwrap(); + + assert_eq!( + response.results.len(), + 2, + "Expected 2 sets of search results" + ); + + // --- Assert products result --- + let products_result = &response.results[0]; + assert!( + products_result.error.is_none(), + "First search returned an error" + ); + assert_eq!(products_result.found, Some(1)); + let product_hit = &products_result.hits.as_ref().unwrap()[0]; + let product_doc = product_hit.document.as_ref().unwrap().as_object().unwrap(); + assert_eq!( + product_doc.get("name").unwrap().as_str(), + Some("MacBook Pro") + ); + + // --- Assert brands result --- + let brands_result = &response.results[1]; + assert!( + brands_result.error.is_none(), + "Second search returned an error" + ); + assert_eq!(brands_result.found, Some(1)); + let brand_hit = &brands_result.hits.as_ref().unwrap()[0]; + let brand_doc = brand_hit.document.as_ref().unwrap().as_object().unwrap(); + assert_eq!( + brand_doc.get("company_name").unwrap().as_str(), + Some("Apple Inc.") + ); +} + +async fn run_test_multi_search_with_common_params() { + let client = get_client(); + let products_collection_name = new_id("products_common"); + let brands_collection_name = new_id("brands_common"); + setup_multi_search_tests(&client, &products_collection_name, &brands_collection_name).await; + + // Define individual searches, each with the correct `query_by` for its schema. + let search_requests = MultiSearchBody { + searches: vec![ + MultiSearchCollectionParameters { + collection: Some(products_collection_name.clone()), + q: Some("pro".into()), // This should find "Macbook Pro" + query_by: Some("name".into()), // Specific to the products schema + ..Default::default() + }, + MultiSearchCollectionParameters { + collection: Some(brands_collection_name.clone()), + q: Some("inc".into()), // This should find "Apple Inc." + query_by: Some("company_name".into()), // Specific to the brands schema + ..Default::default() + }, + ], + }; + + let common_params = MultiSearchParameters { + limit: Some(1), + ..Default::default() + }; + + let result = client + .multi_search() + .perform(search_requests, common_params) + .await; + + assert!( + result.is_ok(), + "Multi-search request failed: {:?}", + result.err() + ); + let response = result.unwrap(); + + assert_eq!(response.results.len(), 2); + + // --- Assert products result --- + let products_result = &response.results[0]; + assert!( + products_result.error.is_none(), + "Products search returned an error: {:?}", + products_result.error + ); + assert_eq!(products_result.found, Some(1)); + let product_hit = &products_result.hits.as_ref().unwrap()[0]; + assert_eq!( + product_hit.document.as_ref().unwrap()["name"], + "MacBook Pro" + ); + + // --- Assert brands result --- + let brands_result = &response.results[1]; + assert!( + brands_result.error.is_none(), + "Brands search returned an error: {:?}", + brands_result.error + ); + assert_eq!(brands_result.found, Some(1)); + let brand_hit = &brands_result.hits.as_ref().unwrap()[0]; + assert_eq!( + brand_hit.document.as_ref().unwrap()["company_name"], + "Apple Inc." + ); +} + +#[derive(Debug, Deserialize, PartialEq)] +struct Product { + id: String, + name: String, + price: i32, +} + +#[derive(Debug, Deserialize, PartialEq)] +struct Brand { + id: String, + company_name: String, + country: String, +} + +async fn run_test_multi_search_generic_parsing() { + let client = get_client(); + let products_collection_name = new_id("products_generic"); + let brands_collection_name = new_id("brands_generic"); + setup_multi_search_tests(&client, &products_collection_name, &brands_collection_name).await; + + let search_requests = MultiSearchBody { + searches: vec![ + // Search #0 for products + MultiSearchCollectionParameters { + q: Some("pro".into()), + query_by: Some("name".into()), + collection: Some(products_collection_name.clone()), + ..Default::default() + }, + // Search #1 for brands + MultiSearchCollectionParameters { + q: Some("USA".into()), + query_by: Some("country".into()), + collection: Some(brands_collection_name.clone()), + ..Default::default() + }, + ], + ..Default::default() + }; + + let common_params = MultiSearchParameters::default(); + + // Perform the search and get the raw, untyped response + let raw_response = client + .multi_search() + .perform(search_requests, common_params) + .await + .unwrap(); + + // --- Use the new generic parsing feature --- + + // Parse the first result set (index 0) into SearchResult + let products_result: SearchResult = + raw_response.parse_at(0).expect("Parsing products failed"); + + // Parse the second result set (index 1) into SearchResult + let brands_result: SearchResult = + raw_response.parse_at(1).expect("Parsing brands failed"); + + // --- Assert the strongly-typed results --- + + // Assert products result + assert_eq!(products_result.found, Some(1), "Expected to find 1 product"); + let product_hit = &products_result + .hits + .as_ref() + .unwrap() + .get(0) + .expect("No product hits found"); + let product_doc = product_hit + .document + .as_ref() + .expect("Product hit has no document"); + + assert_eq!(product_doc.name, "MacBook Pro"); + assert_eq!(product_doc.price, 1999); + assert_eq!( + *product_doc, + Product { + id: "p2".to_owned(), + name: "MacBook Pro".to_owned(), + price: 1999, + } + ); + + // Assert brands result + assert_eq!(brands_result.found, Some(1), "Expected to find 1 brand"); + let brand_hit = &brands_result + .hits + .as_ref() + .unwrap() + .get(0) + .expect("No brand hits found"); + let brand_doc = brand_hit + .document + .as_ref() + .expect("Brand hit has no document"); + + assert_eq!(brand_doc.company_name, "Apple Inc."); + assert_eq!( + *brand_doc, + Brand { + id: "b1".to_owned(), + company_name: "Apple Inc.".to_owned(), + country: "USA".to_owned(), + } + ); +} + +async fn run_test_multi_search_union_heterogeneous() { + let client = get_client(); + let products_collection_name = new_id("products_union"); + let brands_collection_name = new_id("brands_union"); + setup_multi_search_tests(&client, &products_collection_name, &brands_collection_name).await; + + // We will search for "pro" in products and "samsung" in brands. + // This should yield one hit from each collection. + let search_requests = MultiSearchBody { + searches: vec![ + MultiSearchCollectionParameters { + q: Some("pro".into()), + query_by: Some("name".into()), + collection: Some(products_collection_name.clone()), + ..Default::default() + }, + MultiSearchCollectionParameters { + q: Some("samsung".into()), + query_by: Some("company_name".into()), + collection: Some(brands_collection_name.clone()), + ..Default::default() + }, + ], + }; + + let common_params = MultiSearchParameters::default(); + + // Call the new union function + let result = client + .multi_search() + .perform_union::(search_requests, common_params) + .await; + + assert!( + result.is_ok(), + "Union multi-search request failed: {:?}", + result.err() + ); + let response = result.unwrap(); + + // In a union search, we expect a single merged result set. + // We found "MacBook Pro" and "Samsung". + assert_eq!(response.found, Some(2)); + let hits = response.hits.expect("Expected to find hits"); + assert_eq!(hits.len(), 2); + + // --- Process the heterogeneous hits --- + // This demonstrates how a user would handle the `serde_json::Value` documents. + let mut product_count = 0; + let mut brand_count = 0; + + for hit in hits { + let document = hit.document.as_ref().unwrap(); + + // Check for a field unique to the Product schema to identify the document type. + if document.get("price").is_some() { + let product: Product = + serde_json::from_value(document.clone()).expect("Failed to parse Product"); + assert_eq!(product.name, "MacBook Pro"); + product_count += 1; + } + // Check for a field unique to the Brand schema. + else if document.get("company_name").is_some() { + let brand: Brand = + serde_json::from_value(document.clone()).expect("Failed to parse Brand"); + assert_eq!(brand.company_name, "Samsung"); + brand_count += 1; + } + } + + // Verify that we correctly identified one of each type from the merged results. + assert_eq!( + product_count, 1, + "Expected to find 1 product in the union result" + ); + assert_eq!( + brand_count, 1, + "Expected to find 1 brand in the union result" + ); +} + +async fn run_test_multi_search_union_homogeneous_and_typed_conversion() { + let client = get_client(); + let products_collection_name = new_id("products_union_homo"); + // We only need one collection for this test, but the setup creates two. + let brands_collection_name = new_id("brands_union_homo_unused"); + setup_multi_search_tests(&client, &products_collection_name, &brands_collection_name).await; + + // Both search queries target the *same* products collection. + let search_requests = MultiSearchBody { + searches: vec![ + // This query should find "iPhone 15" + MultiSearchCollectionParameters { + q: Some("iphone".into()), + query_by: Some("name".into()), + collection: Some(products_collection_name.clone()), + ..Default::default() + }, + // This query should find "MacBook Pro" + MultiSearchCollectionParameters { + q: Some("macbook".into()), + query_by: Some("name".into()), + collection: Some(products_collection_name.clone()), + ..Default::default() + }, + ], + }; + + let typed_result: SearchResult = client + .multi_search() + .perform_union(search_requests, MultiSearchParameters::default()) + .await + .expect("Union search failed"); + + assert_eq!(typed_result.found, Some(2)); + let mut hits = typed_result.hits.expect("Expected hits"); + + // Sort by price to have a predictable order for assertions. + hits.sort_by_key(|h| h.document.as_ref().unwrap().price); + + // Assert the first hit (iPhone) + let iphone = &hits[0].document.as_ref().unwrap(); + assert_eq!(iphone.name, "iPhone 15"); + assert_eq!(iphone.price, 999); + + // Assert the second hit (MacBook Pro) + let macbook = &hits[1].document.as_ref().unwrap(); + assert_eq!(macbook.name, "MacBook Pro"); + assert_eq!(macbook.price, 1999); +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tokio_test { + use super::*; + + #[tokio::test] + async fn test_multi_search_federated() { + run_test_multi_search_federated().await; + } + #[tokio::test] + async fn test_multi_search_with_common_params() { + run_test_multi_search_with_common_params().await; + } + #[tokio::test] + async fn test_multi_search_generic_parsing() { + run_test_multi_search_generic_parsing().await; + } + #[tokio::test] + async fn test_multi_search_union_heterogeneous() { + run_test_multi_search_union_heterogeneous().await; + } + #[tokio::test] + async fn test_multi_search_union_homogeneous_and_typed_conversion() { + run_test_multi_search_union_homogeneous_and_typed_conversion().await; + } +} + +#[cfg(all(test, target_arch = "wasm32"))] +mod wasm_test { + use super::*; + use wasm_bindgen_test::wasm_bindgen_test; + + wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); + + #[wasm_bindgen_test] + async fn test_multi_search_federated() { + console_error_panic_hook::set_once(); + run_test_multi_search_federated().await; + } + #[wasm_bindgen_test] + async fn test_multi_search_with_common_params() { + console_error_panic_hook::set_once(); + run_test_multi_search_with_common_params().await; + } + #[wasm_bindgen_test] + async fn test_multi_search_generic_parsing() { + console_error_panic_hook::set_once(); + run_test_multi_search_generic_parsing().await; + } + #[wasm_bindgen_test] + async fn test_multi_search_union_heterogeneous() { + console_error_panic_hook::set_once(); + run_test_multi_search_union_heterogeneous().await; + } + #[wasm_bindgen_test] + async fn test_multi_search_union_homogeneous_and_typed_conversion() { + console_error_panic_hook::set_once(); + run_test_multi_search_union_homogeneous_and_typed_conversion().await; + } +} diff --git a/typesense/tests/derive/collection.rs b/typesense/tests/derive/collection.rs index f4e8da2..71dcd91 100644 --- a/typesense/tests/derive/collection.rs +++ b/typesense/tests/derive/collection.rs @@ -1,6 +1,5 @@ use serde::{Deserialize, Serialize}; -use typesense::Typesense; -use typesense::document::Document; +use typesense::{Typesense, prelude::Document}; #[test] fn derived_document_generates_schema() { diff --git a/typesense/tests/derive/ui/wrong_sorting_field.stderr b/typesense/tests/derive/ui/wrong_sorting_field.stderr index f8d61f5..919a41a 100644 --- a/typesense/tests/derive/ui/wrong_sorting_field.stderr +++ b/typesense/tests/derive/ui/wrong_sorting_field.stderr @@ -1,10 +1,10 @@ error: defined default_sorting_field = "wrong_field" does not match with any field. --> $DIR/wrong_sorting_field.rs:5:1 | -5 | / #[typesense(default_sorting_field = "wrong_field")] -6 | | struct Company { -7 | | company_name: String, -8 | | num_employees: i32, -9 | | country: String, + 5 | / #[typesense(default_sorting_field = "wrong_field")] + 6 | | struct Company { + 7 | | company_name: String, + 8 | | num_employees: i32, + 9 | | country: String, 10 | | } | |_^ diff --git a/typesense_codegen/.openapi-generator-ignore b/typesense_codegen/.openapi-generator-ignore index 7484ee5..3eed36b 100644 --- a/typesense_codegen/.openapi-generator-ignore +++ b/typesense_codegen/.openapi-generator-ignore @@ -21,3 +21,10 @@ #docs/*.md # Then explicitly reverse the ignore rule for a single file: #!docs/README.md + +Cargo.toml +src/apis/configuration.rs + +.gitignore +.travis.yml +git_push.sh \ No newline at end of file diff --git a/typesense_codegen/.openapi-generator/FILES b/typesense_codegen/.openapi-generator/FILES index 2e9cc88..2a46e2a 100644 --- a/typesense_codegen/.openapi-generator/FILES +++ b/typesense_codegen/.openapi-generator/FILES @@ -1,18 +1,21 @@ -.gitignore -.openapi-generator-ignore -.travis.yml -Cargo.toml README.md docs/AnalyticsApi.md -docs/AnalyticsRuleParameters.md -docs/AnalyticsRuleParametersDestination.md -docs/AnalyticsRuleParametersSource.md -docs/AnalyticsRuleSchema.md -docs/AnalyticsRulesRetrieveSchema.md +docs/AnalyticsEvent.md +docs/AnalyticsEventCreateResponse.md +docs/AnalyticsEventData.md +docs/AnalyticsEventsResponse.md +docs/AnalyticsEventsResponseEventsInner.md +docs/AnalyticsRule.md +docs/AnalyticsRuleCreate.md +docs/AnalyticsRuleCreateParams.md +docs/AnalyticsRuleUpdate.md +docs/AnalyticsStatus.md docs/ApiKey.md +docs/ApiKeyDeleteResponse.md docs/ApiKeySchema.md docs/ApiKeysResponse.md docs/ApiResponse.md +docs/ApiStatsResponse.md docs/CollectionAlias.md docs/CollectionAliasSchema.md docs/CollectionAliasesResponse.md @@ -20,113 +23,210 @@ docs/CollectionResponse.md docs/CollectionSchema.md docs/CollectionUpdateSchema.md docs/CollectionsApi.md +docs/ConversationModelCreateSchema.md +docs/ConversationModelSchema.md +docs/ConversationModelUpdateSchema.md +docs/ConversationsApi.md +docs/CreateAnalyticsRule200Response.md +docs/CreateAnalyticsRule200ResponseOneOfInner.md +docs/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.md +docs/CreateAnalyticsRuleRequest.md +docs/CurationApi.md docs/Debug200Response.md docs/DebugApi.md docs/DeleteDocuments200Response.md -docs/DeleteDocumentsDeleteDocumentsParametersParameter.md +docs/DeleteDocumentsParameters.md +docs/DeleteStopwordsSet200Response.md +docs/DirtyValues.md docs/DocumentsApi.md -docs/ErrorResponse.md -docs/ExportDocumentsExportDocumentsParametersParameter.md +docs/DropTokensMode.md +docs/ExportDocumentsParameters.md docs/FacetCounts.md docs/FacetCountsCountsInner.md docs/FacetCountsStats.md docs/Field.md docs/FieldEmbed.md docs/FieldEmbedModelConfig.md +docs/GetCollectionsParameters.md docs/HealthApi.md docs/HealthStatus.md -docs/ImportDocumentsImportDocumentsParametersParameter.md +docs/ImportDocumentsParameters.md +docs/IndexAction.md docs/KeysApi.md +docs/ListStemmingDictionaries200Response.md docs/MultiSearchCollectionParameters.md docs/MultiSearchParameters.md docs/MultiSearchResult.md +docs/MultiSearchResultItem.md docs/MultiSearchSearchesParameter.md +docs/NlSearchModelBase.md +docs/NlSearchModelCreateSchema.md +docs/NlSearchModelDeleteSchema.md +docs/NlSearchModelSchema.md +docs/NlSearchModelsApi.md docs/OperationsApi.md docs/OverrideApi.md -docs/PromoteApi.md -docs/ScopedKeyParameters.md +docs/PresetDeleteSchema.md +docs/PresetSchema.md +docs/PresetUpsertSchema.md +docs/PresetUpsertSchemaValue.md +docs/PresetsApi.md +docs/PresetsRetrieveSchema.md +docs/SchemaChangeStatus.md docs/SearchGroupedHit.md docs/SearchHighlight.md docs/SearchOverride.md +docs/SearchOverrideDeleteResponse.md docs/SearchOverrideExclude.md docs/SearchOverrideInclude.md docs/SearchOverrideRule.md docs/SearchOverrideSchema.md docs/SearchOverridesResponse.md docs/SearchParameters.md +docs/SearchRequestParams.md +docs/SearchRequestParamsVoiceQuery.md docs/SearchResult.md +docs/SearchResultConversation.md docs/SearchResultHit.md -docs/SearchResultRequestParams.md +docs/SearchResultHitHybridSearchInfo.md +docs/SearchResultHitTextMatchInfo.md docs/SearchSynonym.md +docs/SearchSynonymDeleteResponse.md docs/SearchSynonymSchema.md docs/SearchSynonymsResponse.md -docs/SnapshotParameters.md +docs/StemmingApi.md +docs/StemmingDictionary.md +docs/StemmingDictionaryWordsInner.md +docs/StopwordsApi.md +docs/StopwordsSetRetrieveSchema.md +docs/StopwordsSetSchema.md +docs/StopwordsSetUpsertSchema.md +docs/StopwordsSetsRetrieveAllSchema.md docs/SuccessStatus.md +docs/SynonymItemSchema.md +docs/SynonymSetCreateSchema.md +docs/SynonymSetDeleteSchema.md +docs/SynonymSetSchema.md +docs/SynonymSetsRetrieveSchema.md +docs/SynonymsApi.md +docs/ToggleSlowRequestLogRequest.md docs/UpdateDocuments200Response.md -docs/UpdateDocumentsUpdateDocumentsParametersParameter.md -git_push.sh +docs/UpdateDocumentsParameters.md +docs/VoiceQueryModelCollectionConfig.md src/apis/analytics_api.rs src/apis/collections_api.rs -src/apis/configuration.rs +src/apis/conversations_api.rs +src/apis/curation_api.rs src/apis/debug_api.rs src/apis/documents_api.rs src/apis/health_api.rs src/apis/keys_api.rs src/apis/mod.rs +src/apis/nl_search_models_api.rs src/apis/operations_api.rs src/apis/override_api.rs -src/apis/promote_api.rs +src/apis/presets_api.rs +src/apis/stemming_api.rs +src/apis/stopwords_api.rs +src/apis/synonyms_api.rs src/lib.rs -src/models/analytics_rule_parameters.rs -src/models/analytics_rule_parameters_destination.rs -src/models/analytics_rule_parameters_source.rs -src/models/analytics_rule_schema.rs -src/models/analytics_rules_retrieve_schema.rs +src/models/analytics_event.rs +src/models/analytics_event_create_response.rs +src/models/analytics_event_data.rs +src/models/analytics_events_response.rs +src/models/analytics_events_response_events_inner.rs +src/models/analytics_rule.rs +src/models/analytics_rule_create.rs +src/models/analytics_rule_create_params.rs +src/models/analytics_rule_update.rs +src/models/analytics_status.rs src/models/api_key.rs +src/models/api_key_delete_response.rs src/models/api_key_schema.rs src/models/api_keys_response.rs src/models/api_response.rs +src/models/api_stats_response.rs src/models/collection_alias.rs src/models/collection_alias_schema.rs src/models/collection_aliases_response.rs src/models/collection_response.rs src/models/collection_schema.rs src/models/collection_update_schema.rs +src/models/conversation_model_create_schema.rs +src/models/conversation_model_schema.rs +src/models/conversation_model_update_schema.rs +src/models/create_analytics_rule_200_response.rs +src/models/create_analytics_rule_200_response_one_of_inner.rs +src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs +src/models/create_analytics_rule_request.rs src/models/debug_200_response.rs src/models/delete_documents_200_response.rs -src/models/delete_documents_delete_documents_parameters_parameter.rs -src/models/error_response.rs -src/models/export_documents_export_documents_parameters_parameter.rs +src/models/delete_documents_parameters.rs +src/models/delete_stopwords_set_200_response.rs +src/models/dirty_values.rs +src/models/drop_tokens_mode.rs +src/models/export_documents_parameters.rs src/models/facet_counts.rs src/models/facet_counts_counts_inner.rs src/models/facet_counts_stats.rs src/models/field.rs src/models/field_embed.rs src/models/field_embed_model_config.rs +src/models/get_collections_parameters.rs src/models/health_status.rs -src/models/import_documents_import_documents_parameters_parameter.rs +src/models/import_documents_parameters.rs +src/models/index_action.rs +src/models/list_stemming_dictionaries_200_response.rs src/models/mod.rs src/models/multi_search_collection_parameters.rs src/models/multi_search_parameters.rs src/models/multi_search_result.rs +src/models/multi_search_result_item.rs src/models/multi_search_searches_parameter.rs -src/models/scoped_key_parameters.rs +src/models/nl_search_model_base.rs +src/models/nl_search_model_create_schema.rs +src/models/nl_search_model_delete_schema.rs +src/models/nl_search_model_schema.rs +src/models/preset_delete_schema.rs +src/models/preset_schema.rs +src/models/preset_upsert_schema.rs +src/models/preset_upsert_schema_value.rs +src/models/presets_retrieve_schema.rs +src/models/schema_change_status.rs src/models/search_grouped_hit.rs src/models/search_highlight.rs src/models/search_override.rs +src/models/search_override_delete_response.rs src/models/search_override_exclude.rs src/models/search_override_include.rs src/models/search_override_rule.rs src/models/search_override_schema.rs src/models/search_overrides_response.rs src/models/search_parameters.rs +src/models/search_request_params.rs +src/models/search_request_params_voice_query.rs src/models/search_result.rs +src/models/search_result_conversation.rs src/models/search_result_hit.rs -src/models/search_result_request_params.rs +src/models/search_result_hit_hybrid_search_info.rs +src/models/search_result_hit_text_match_info.rs src/models/search_synonym.rs +src/models/search_synonym_delete_response.rs src/models/search_synonym_schema.rs src/models/search_synonyms_response.rs -src/models/snapshot_parameters.rs +src/models/stemming_dictionary.rs +src/models/stemming_dictionary_words_inner.rs +src/models/stopwords_set_retrieve_schema.rs +src/models/stopwords_set_schema.rs +src/models/stopwords_set_upsert_schema.rs +src/models/stopwords_sets_retrieve_all_schema.rs src/models/success_status.rs +src/models/synonym_item_schema.rs +src/models/synonym_set_create_schema.rs +src/models/synonym_set_delete_schema.rs +src/models/synonym_set_schema.rs +src/models/synonym_sets_retrieve_schema.rs +src/models/toggle_slow_request_log_request.rs src/models/update_documents_200_response.rs -src/models/update_documents_update_documents_parameters_parameter.rs +src/models/update_documents_parameters.rs +src/models/voice_query_model_collection_config.rs diff --git a/typesense_codegen/.openapi-generator/VERSION b/typesense_codegen/.openapi-generator/VERSION index c9e125b..5e52829 100644 --- a/typesense_codegen/.openapi-generator/VERSION +++ b/typesense_codegen/.openapi-generator/VERSION @@ -1 +1 @@ -7.4.0-SNAPSHOT +7.16.0-SNAPSHOT diff --git a/typesense_codegen/.travis.yml b/typesense_codegen/.travis.yml deleted file mode 100644 index 22761ba..0000000 --- a/typesense_codegen/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: rust diff --git a/typesense_codegen/Cargo.toml b/typesense_codegen/Cargo.toml index 8b1aefb..ff2a22d 100644 --- a/typesense_codegen/Cargo.toml +++ b/typesense_codegen/Cargo.toml @@ -8,12 +8,17 @@ edition.workspace = true license.workspace = true [dependencies] -serde = "^1.0" -serde_derive = "^1.0" -serde_json = "^1.0" -url = "^2.2" -uuid = { version = "^1.0", features = ["serde", "v4", "js"] } +bon = { workspace = true } +reqwest = { version = "0.12", default-features = false, features = ["json"] } +serde = { workspace = true } +serde_json = { workspace = true } +serde_repr = { workspace = true } +url = { workspace = true } -[dependencies.reqwest] -version = "^0.12" -features = ["json", "multipart"] +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +reqwest-middleware = { version = "0.4", features = ["json"] } + +[features] +default = ["native-tls"] +native-tls = ["reqwest/native-tls"] +rustls = ["reqwest/rustls-tls"] diff --git a/typesense_codegen/README.md b/typesense_codegen/README.md index c634c1d..768dcfa 100644 --- a/typesense_codegen/README.md +++ b/typesense_codegen/README.md @@ -7,8 +7,9 @@ An open source search engine for building delightful search experiences. This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client. -- API version: 0.25.0 -- Package version: 0.25.0 +- API version: 30.0 +- Package version: 30.0 +- Generator version: 7.16.0-SNAPSHOT - Build package: `org.openapitools.codegen.languages.RustClientCodegen` ## Installation @@ -21,14 +22,19 @@ openapi = { path = "./openapi" } ## Documentation for API Endpoints -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*AnalyticsApi* | [**create_analytics_rule**](docs/AnalyticsApi.md#create_analytics_rule) | **POST** /analytics/rules | Creates an analytics rule +*AnalyticsApi* | [**create_analytics_event**](docs/AnalyticsApi.md#create_analytics_event) | **POST** /analytics/events | Create an analytics event +*AnalyticsApi* | [**create_analytics_rule**](docs/AnalyticsApi.md#create_analytics_rule) | **POST** /analytics/rules | Create analytics rule(s) *AnalyticsApi* | [**delete_analytics_rule**](docs/AnalyticsApi.md#delete_analytics_rule) | **DELETE** /analytics/rules/{ruleName} | Delete an analytics rule +*AnalyticsApi* | [**flush_analytics**](docs/AnalyticsApi.md#flush_analytics) | **POST** /analytics/flush | Flush in-memory analytics to disk +*AnalyticsApi* | [**get_analytics_events**](docs/AnalyticsApi.md#get_analytics_events) | **GET** /analytics/events | Retrieve analytics events +*AnalyticsApi* | [**get_analytics_status**](docs/AnalyticsApi.md#get_analytics_status) | **GET** /analytics/status | Get analytics subsystem status *AnalyticsApi* | [**retrieve_analytics_rule**](docs/AnalyticsApi.md#retrieve_analytics_rule) | **GET** /analytics/rules/{ruleName} | Retrieves an analytics rule -*AnalyticsApi* | [**retrieve_analytics_rules**](docs/AnalyticsApi.md#retrieve_analytics_rules) | **GET** /analytics/rules | Retrieves all analytics rules +*AnalyticsApi* | [**retrieve_analytics_rules**](docs/AnalyticsApi.md#retrieve_analytics_rules) | **GET** /analytics/rules | Retrieve analytics rules +*AnalyticsApi* | [**upsert_analytics_rule**](docs/AnalyticsApi.md#upsert_analytics_rule) | **PUT** /analytics/rules/{ruleName} | Upserts an analytics rule *CollectionsApi* | [**create_collection**](docs/CollectionsApi.md#create_collection) | **POST** /collections | Create a new collection *CollectionsApi* | [**delete_alias**](docs/CollectionsApi.md#delete_alias) | **DELETE** /aliases/{aliasName} | Delete an alias *CollectionsApi* | [**delete_collection**](docs/CollectionsApi.md#delete_collection) | **DELETE** /collections/{collectionName} | Delete a collection @@ -38,17 +44,22 @@ Class | Method | HTTP request | Description *CollectionsApi* | [**get_collections**](docs/CollectionsApi.md#get_collections) | **GET** /collections | List all collections *CollectionsApi* | [**update_collection**](docs/CollectionsApi.md#update_collection) | **PATCH** /collections/{collectionName} | Update a collection *CollectionsApi* | [**upsert_alias**](docs/CollectionsApi.md#upsert_alias) | **PUT** /aliases/{aliasName} | Create or update a collection alias +*ConversationsApi* | [**create_conversation_model**](docs/ConversationsApi.md#create_conversation_model) | **POST** /conversations/models | Create a conversation model +*ConversationsApi* | [**delete_conversation_model**](docs/ConversationsApi.md#delete_conversation_model) | **DELETE** /conversations/models/{modelId} | Delete a conversation model +*ConversationsApi* | [**retrieve_all_conversation_models**](docs/ConversationsApi.md#retrieve_all_conversation_models) | **GET** /conversations/models | List all conversation models +*ConversationsApi* | [**retrieve_conversation_model**](docs/ConversationsApi.md#retrieve_conversation_model) | **GET** /conversations/models/{modelId} | Retrieve a conversation model +*ConversationsApi* | [**update_conversation_model**](docs/ConversationsApi.md#update_conversation_model) | **PUT** /conversations/models/{modelId} | Update a conversation model +*CurationApi* | [**delete_search_override**](docs/CurationApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection +*CurationApi* | [**get_search_overrides**](docs/CurationApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides +*CurationApi* | [**upsert_search_override**](docs/CurationApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others *DebugApi* | [**debug**](docs/DebugApi.md#debug) | **GET** /debug | Print debugging information *DocumentsApi* | [**delete_document**](docs/DocumentsApi.md#delete_document) | **DELETE** /collections/{collectionName}/documents/{documentId} | Delete a document *DocumentsApi* | [**delete_documents**](docs/DocumentsApi.md#delete_documents) | **DELETE** /collections/{collectionName}/documents | Delete a bunch of documents *DocumentsApi* | [**delete_search_override**](docs/DocumentsApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection -*DocumentsApi* | [**delete_search_synonym**](docs/DocumentsApi.md#delete_search_synonym) | **DELETE** /collections/{collectionName}/synonyms/{synonymId} | Delete a synonym associated with a collection *DocumentsApi* | [**export_documents**](docs/DocumentsApi.md#export_documents) | **GET** /collections/{collectionName}/documents/export | Export all documents in a collection -*DocumentsApi* | [**get_document**](docs/DocumentsApi.md#get_document) | **GET** /collections/{collectionName}/documents/{documentId} | Retreive a document +*DocumentsApi* | [**get_document**](docs/DocumentsApi.md#get_document) | **GET** /collections/{collectionName}/documents/{documentId} | Retrieve a document *DocumentsApi* | [**get_search_override**](docs/DocumentsApi.md#get_search_override) | **GET** /collections/{collectionName}/overrides/{overrideId} | Retrieve a single search override *DocumentsApi* | [**get_search_overrides**](docs/DocumentsApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides -*DocumentsApi* | [**get_search_synonym**](docs/DocumentsApi.md#get_search_synonym) | **GET** /collections/{collectionName}/synonyms/{synonymId} | Retrieve a single search synonym -*DocumentsApi* | [**get_search_synonyms**](docs/DocumentsApi.md#get_search_synonyms) | **GET** /collections/{collectionName}/synonyms | List all collection synonyms *DocumentsApi* | [**import_documents**](docs/DocumentsApi.md#import_documents) | **POST** /collections/{collectionName}/documents/import | Import documents into a collection *DocumentsApi* | [**index_document**](docs/DocumentsApi.md#index_document) | **POST** /collections/{collectionName}/documents | Index a document *DocumentsApi* | [**multi_search**](docs/DocumentsApi.md#multi_search) | **POST** /multi_search | send multiple search requests in a single HTTP request @@ -56,74 +67,143 @@ Class | Method | HTTP request | Description *DocumentsApi* | [**update_document**](docs/DocumentsApi.md#update_document) | **PATCH** /collections/{collectionName}/documents/{documentId} | Update a document *DocumentsApi* | [**update_documents**](docs/DocumentsApi.md#update_documents) | **PATCH** /collections/{collectionName}/documents | Update documents with conditional query *DocumentsApi* | [**upsert_search_override**](docs/DocumentsApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others -*DocumentsApi* | [**upsert_search_synonym**](docs/DocumentsApi.md#upsert_search_synonym) | **PUT** /collections/{collectionName}/synonyms/{synonymId} | Create or update a synonym *HealthApi* | [**health**](docs/HealthApi.md#health) | **GET** /health | Checks if Typesense server is ready to accept requests. *KeysApi* | [**create_key**](docs/KeysApi.md#create_key) | **POST** /keys | Create an API Key *KeysApi* | [**delete_key**](docs/KeysApi.md#delete_key) | **DELETE** /keys/{keyId} | Delete an API key given its ID. *KeysApi* | [**get_key**](docs/KeysApi.md#get_key) | **GET** /keys/{keyId} | Retrieve (metadata about) a key *KeysApi* | [**get_keys**](docs/KeysApi.md#get_keys) | **GET** /keys | Retrieve (metadata about) all keys. +*NlSearchModelsApi* | [**create_nl_search_model**](docs/NlSearchModelsApi.md#create_nl_search_model) | **POST** /nl_search_models | Create a NL search model +*NlSearchModelsApi* | [**delete_nl_search_model**](docs/NlSearchModelsApi.md#delete_nl_search_model) | **DELETE** /nl_search_models/{modelId} | Delete a NL search model +*NlSearchModelsApi* | [**retrieve_all_nl_search_models**](docs/NlSearchModelsApi.md#retrieve_all_nl_search_models) | **GET** /nl_search_models | List all NL search models +*NlSearchModelsApi* | [**retrieve_nl_search_model**](docs/NlSearchModelsApi.md#retrieve_nl_search_model) | **GET** /nl_search_models/{modelId} | Retrieve a NL search model +*NlSearchModelsApi* | [**update_nl_search_model**](docs/NlSearchModelsApi.md#update_nl_search_model) | **PUT** /nl_search_models/{modelId} | Update a NL search model +*OperationsApi* | [**clear_cache**](docs/OperationsApi.md#clear_cache) | **POST** /operations/cache/clear | Clear the cached responses of search requests in the LRU cache. +*OperationsApi* | [**compact_db**](docs/OperationsApi.md#compact_db) | **POST** /operations/db/compact | Compacting the on-disk database +*OperationsApi* | [**get_schema_changes**](docs/OperationsApi.md#get_schema_changes) | **GET** /operations/schema_changes | Get the status of in-progress schema change operations +*OperationsApi* | [**retrieve_api_stats**](docs/OperationsApi.md#retrieve_api_stats) | **GET** /stats.json | Get stats about API endpoints. +*OperationsApi* | [**retrieve_metrics**](docs/OperationsApi.md#retrieve_metrics) | **GET** /metrics.json | Get current RAM, CPU, Disk & Network usage metrics. *OperationsApi* | [**take_snapshot**](docs/OperationsApi.md#take_snapshot) | **POST** /operations/snapshot | Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. +*OperationsApi* | [**toggle_slow_request_log**](docs/OperationsApi.md#toggle_slow_request_log) | **POST** /config | Toggle Slow Request Log *OperationsApi* | [**vote**](docs/OperationsApi.md#vote) | **POST** /operations/vote | Triggers a follower node to initiate the raft voting process, which triggers leader re-election. *OverrideApi* | [**get_search_override**](docs/OverrideApi.md#get_search_override) | **GET** /collections/{collectionName}/overrides/{overrideId} | Retrieve a single search override -*PromoteApi* | [**delete_search_override**](docs/PromoteApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection -*PromoteApi* | [**get_search_overrides**](docs/PromoteApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides -*PromoteApi* | [**upsert_search_override**](docs/PromoteApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others +*PresetsApi* | [**delete_preset**](docs/PresetsApi.md#delete_preset) | **DELETE** /presets/{presetId} | Delete a preset. +*PresetsApi* | [**retrieve_all_presets**](docs/PresetsApi.md#retrieve_all_presets) | **GET** /presets | Retrieves all presets. +*PresetsApi* | [**retrieve_preset**](docs/PresetsApi.md#retrieve_preset) | **GET** /presets/{presetId} | Retrieves a preset. +*PresetsApi* | [**upsert_preset**](docs/PresetsApi.md#upsert_preset) | **PUT** /presets/{presetId} | Upserts a preset. +*StemmingApi* | [**get_stemming_dictionary**](docs/StemmingApi.md#get_stemming_dictionary) | **GET** /stemming/dictionaries/{dictionaryId} | Retrieve a stemming dictionary +*StemmingApi* | [**import_stemming_dictionary**](docs/StemmingApi.md#import_stemming_dictionary) | **POST** /stemming/dictionaries/import | Import a stemming dictionary +*StemmingApi* | [**list_stemming_dictionaries**](docs/StemmingApi.md#list_stemming_dictionaries) | **GET** /stemming/dictionaries | List all stemming dictionaries +*StopwordsApi* | [**delete_stopwords_set**](docs/StopwordsApi.md#delete_stopwords_set) | **DELETE** /stopwords/{setId} | Delete a stopwords set. +*StopwordsApi* | [**retrieve_stopwords_set**](docs/StopwordsApi.md#retrieve_stopwords_set) | **GET** /stopwords/{setId} | Retrieves a stopwords set. +*StopwordsApi* | [**retrieve_stopwords_sets**](docs/StopwordsApi.md#retrieve_stopwords_sets) | **GET** /stopwords | Retrieves all stopwords sets. +*StopwordsApi* | [**upsert_stopwords_set**](docs/StopwordsApi.md#upsert_stopwords_set) | **PUT** /stopwords/{setId} | Upserts a stopwords set. +*SynonymsApi* | [**delete_synonym_set**](docs/SynonymsApi.md#delete_synonym_set) | **DELETE** /synonym_sets/{synonymSetName} | Delete a synonym set +*SynonymsApi* | [**retrieve_synonym_set**](docs/SynonymsApi.md#retrieve_synonym_set) | **GET** /synonym_sets/{synonymSetName} | Retrieve a synonym set +*SynonymsApi* | [**retrieve_synonym_sets**](docs/SynonymsApi.md#retrieve_synonym_sets) | **GET** /synonym_sets | List all synonym sets +*SynonymsApi* | [**upsert_synonym_set**](docs/SynonymsApi.md#upsert_synonym_set) | **PUT** /synonym_sets/{synonymSetName} | Create or update a synonym set ## Documentation For Models - - [AnalyticsRuleParameters](docs/AnalyticsRuleParameters.md) - - [AnalyticsRuleParametersDestination](docs/AnalyticsRuleParametersDestination.md) - - [AnalyticsRuleParametersSource](docs/AnalyticsRuleParametersSource.md) - - [AnalyticsRuleSchema](docs/AnalyticsRuleSchema.md) - - [AnalyticsRulesRetrieveSchema](docs/AnalyticsRulesRetrieveSchema.md) + - [AnalyticsEvent](docs/AnalyticsEvent.md) + - [AnalyticsEventCreateResponse](docs/AnalyticsEventCreateResponse.md) + - [AnalyticsEventData](docs/AnalyticsEventData.md) + - [AnalyticsEventsResponse](docs/AnalyticsEventsResponse.md) + - [AnalyticsEventsResponseEventsInner](docs/AnalyticsEventsResponseEventsInner.md) + - [AnalyticsRule](docs/AnalyticsRule.md) + - [AnalyticsRuleCreate](docs/AnalyticsRuleCreate.md) + - [AnalyticsRuleCreateParams](docs/AnalyticsRuleCreateParams.md) + - [AnalyticsRuleUpdate](docs/AnalyticsRuleUpdate.md) + - [AnalyticsStatus](docs/AnalyticsStatus.md) - [ApiKey](docs/ApiKey.md) + - [ApiKeyDeleteResponse](docs/ApiKeyDeleteResponse.md) - [ApiKeySchema](docs/ApiKeySchema.md) - [ApiKeysResponse](docs/ApiKeysResponse.md) - [ApiResponse](docs/ApiResponse.md) + - [ApiStatsResponse](docs/ApiStatsResponse.md) - [CollectionAlias](docs/CollectionAlias.md) - [CollectionAliasSchema](docs/CollectionAliasSchema.md) - [CollectionAliasesResponse](docs/CollectionAliasesResponse.md) - [CollectionResponse](docs/CollectionResponse.md) - [CollectionSchema](docs/CollectionSchema.md) - [CollectionUpdateSchema](docs/CollectionUpdateSchema.md) + - [ConversationModelCreateSchema](docs/ConversationModelCreateSchema.md) + - [ConversationModelSchema](docs/ConversationModelSchema.md) + - [ConversationModelUpdateSchema](docs/ConversationModelUpdateSchema.md) + - [CreateAnalyticsRule200Response](docs/CreateAnalyticsRule200Response.md) + - [CreateAnalyticsRule200ResponseOneOfInner](docs/CreateAnalyticsRule200ResponseOneOfInner.md) + - [CreateAnalyticsRule200ResponseOneOfInnerAnyOf](docs/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.md) + - [CreateAnalyticsRuleRequest](docs/CreateAnalyticsRuleRequest.md) - [Debug200Response](docs/Debug200Response.md) - [DeleteDocuments200Response](docs/DeleteDocuments200Response.md) - - [DeleteDocumentsDeleteDocumentsParametersParameter](docs/DeleteDocumentsDeleteDocumentsParametersParameter.md) - - [ErrorResponse](docs/ErrorResponse.md) - - [ExportDocumentsExportDocumentsParametersParameter](docs/ExportDocumentsExportDocumentsParametersParameter.md) + - [DeleteDocumentsParameters](docs/DeleteDocumentsParameters.md) + - [DeleteStopwordsSet200Response](docs/DeleteStopwordsSet200Response.md) + - [DirtyValues](docs/DirtyValues.md) + - [DropTokensMode](docs/DropTokensMode.md) + - [ExportDocumentsParameters](docs/ExportDocumentsParameters.md) - [FacetCounts](docs/FacetCounts.md) - [FacetCountsCountsInner](docs/FacetCountsCountsInner.md) - [FacetCountsStats](docs/FacetCountsStats.md) - [Field](docs/Field.md) - [FieldEmbed](docs/FieldEmbed.md) - [FieldEmbedModelConfig](docs/FieldEmbedModelConfig.md) + - [GetCollectionsParameters](docs/GetCollectionsParameters.md) - [HealthStatus](docs/HealthStatus.md) - - [ImportDocumentsImportDocumentsParametersParameter](docs/ImportDocumentsImportDocumentsParametersParameter.md) + - [ImportDocumentsParameters](docs/ImportDocumentsParameters.md) + - [IndexAction](docs/IndexAction.md) + - [ListStemmingDictionaries200Response](docs/ListStemmingDictionaries200Response.md) - [MultiSearchCollectionParameters](docs/MultiSearchCollectionParameters.md) - [MultiSearchParameters](docs/MultiSearchParameters.md) - [MultiSearchResult](docs/MultiSearchResult.md) + - [MultiSearchResultItem](docs/MultiSearchResultItem.md) - [MultiSearchSearchesParameter](docs/MultiSearchSearchesParameter.md) - - [ScopedKeyParameters](docs/ScopedKeyParameters.md) + - [NlSearchModelBase](docs/NlSearchModelBase.md) + - [NlSearchModelCreateSchema](docs/NlSearchModelCreateSchema.md) + - [NlSearchModelDeleteSchema](docs/NlSearchModelDeleteSchema.md) + - [NlSearchModelSchema](docs/NlSearchModelSchema.md) + - [PresetDeleteSchema](docs/PresetDeleteSchema.md) + - [PresetSchema](docs/PresetSchema.md) + - [PresetUpsertSchema](docs/PresetUpsertSchema.md) + - [PresetUpsertSchemaValue](docs/PresetUpsertSchemaValue.md) + - [PresetsRetrieveSchema](docs/PresetsRetrieveSchema.md) + - [SchemaChangeStatus](docs/SchemaChangeStatus.md) - [SearchGroupedHit](docs/SearchGroupedHit.md) - [SearchHighlight](docs/SearchHighlight.md) - [SearchOverride](docs/SearchOverride.md) + - [SearchOverrideDeleteResponse](docs/SearchOverrideDeleteResponse.md) - [SearchOverrideExclude](docs/SearchOverrideExclude.md) - [SearchOverrideInclude](docs/SearchOverrideInclude.md) - [SearchOverrideRule](docs/SearchOverrideRule.md) - [SearchOverrideSchema](docs/SearchOverrideSchema.md) - [SearchOverridesResponse](docs/SearchOverridesResponse.md) - [SearchParameters](docs/SearchParameters.md) + - [SearchRequestParams](docs/SearchRequestParams.md) + - [SearchRequestParamsVoiceQuery](docs/SearchRequestParamsVoiceQuery.md) - [SearchResult](docs/SearchResult.md) + - [SearchResultConversation](docs/SearchResultConversation.md) - [SearchResultHit](docs/SearchResultHit.md) - - [SearchResultRequestParams](docs/SearchResultRequestParams.md) + - [SearchResultHitHybridSearchInfo](docs/SearchResultHitHybridSearchInfo.md) + - [SearchResultHitTextMatchInfo](docs/SearchResultHitTextMatchInfo.md) - [SearchSynonym](docs/SearchSynonym.md) + - [SearchSynonymDeleteResponse](docs/SearchSynonymDeleteResponse.md) - [SearchSynonymSchema](docs/SearchSynonymSchema.md) - [SearchSynonymsResponse](docs/SearchSynonymsResponse.md) - - [SnapshotParameters](docs/SnapshotParameters.md) + - [StemmingDictionary](docs/StemmingDictionary.md) + - [StemmingDictionaryWordsInner](docs/StemmingDictionaryWordsInner.md) + - [StopwordsSetRetrieveSchema](docs/StopwordsSetRetrieveSchema.md) + - [StopwordsSetSchema](docs/StopwordsSetSchema.md) + - [StopwordsSetUpsertSchema](docs/StopwordsSetUpsertSchema.md) + - [StopwordsSetsRetrieveAllSchema](docs/StopwordsSetsRetrieveAllSchema.md) - [SuccessStatus](docs/SuccessStatus.md) + - [SynonymItemSchema](docs/SynonymItemSchema.md) + - [SynonymSetCreateSchema](docs/SynonymSetCreateSchema.md) + - [SynonymSetDeleteSchema](docs/SynonymSetDeleteSchema.md) + - [SynonymSetSchema](docs/SynonymSetSchema.md) + - [SynonymSetsRetrieveSchema](docs/SynonymSetsRetrieveSchema.md) + - [ToggleSlowRequestLogRequest](docs/ToggleSlowRequestLogRequest.md) - [UpdateDocuments200Response](docs/UpdateDocuments200Response.md) - - [UpdateDocumentsUpdateDocumentsParametersParameter](docs/UpdateDocumentsUpdateDocumentsParametersParameter.md) + - [UpdateDocumentsParameters](docs/UpdateDocumentsParameters.md) + - [VoiceQueryModelCollectionConfig](docs/VoiceQueryModelCollectionConfig.md) To get access to the crate's generated documentation, use: diff --git a/typesense_codegen/docs/AnalyticsApi.md b/typesense_codegen/docs/AnalyticsApi.md index 7b6b7d0..b69fc6e 100644 --- a/typesense_codegen/docs/AnalyticsApi.md +++ b/typesense_codegen/docs/AnalyticsApi.md @@ -1,33 +1,68 @@ # \AnalyticsApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- -[**create_analytics_rule**](AnalyticsApi.md#create_analytics_rule) | **POST** /analytics/rules | Creates an analytics rule +[**create_analytics_event**](AnalyticsApi.md#create_analytics_event) | **POST** /analytics/events | Create an analytics event +[**create_analytics_rule**](AnalyticsApi.md#create_analytics_rule) | **POST** /analytics/rules | Create analytics rule(s) [**delete_analytics_rule**](AnalyticsApi.md#delete_analytics_rule) | **DELETE** /analytics/rules/{ruleName} | Delete an analytics rule +[**flush_analytics**](AnalyticsApi.md#flush_analytics) | **POST** /analytics/flush | Flush in-memory analytics to disk +[**get_analytics_events**](AnalyticsApi.md#get_analytics_events) | **GET** /analytics/events | Retrieve analytics events +[**get_analytics_status**](AnalyticsApi.md#get_analytics_status) | **GET** /analytics/status | Get analytics subsystem status [**retrieve_analytics_rule**](AnalyticsApi.md#retrieve_analytics_rule) | **GET** /analytics/rules/{ruleName} | Retrieves an analytics rule -[**retrieve_analytics_rules**](AnalyticsApi.md#retrieve_analytics_rules) | **GET** /analytics/rules | Retrieves all analytics rules +[**retrieve_analytics_rules**](AnalyticsApi.md#retrieve_analytics_rules) | **GET** /analytics/rules | Retrieve analytics rules +[**upsert_analytics_rule**](AnalyticsApi.md#upsert_analytics_rule) | **PUT** /analytics/rules/{ruleName} | Upserts an analytics rule +## create_analytics_event + +> models::AnalyticsEventCreateResponse create_analytics_event(analytics_event) +Create an analytics event + +Submit a single analytics event. The event must correspond to an existing analytics rule by name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**analytics_event** | [**AnalyticsEvent**](AnalyticsEvent.md) | The analytics event to be created | [required] | + +### Return type + +[**models::AnalyticsEventCreateResponse**](AnalyticsEventCreateResponse.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + ## create_analytics_rule -> crate::models::AnalyticsRuleSchema create_analytics_rule(analytics_rule_schema) -Creates an analytics rule +> models::CreateAnalyticsRule200Response create_analytics_rule(create_analytics_rule_request) +Create analytics rule(s) -When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. +Create one or more analytics rules. You can send a single rule object or an array of rule objects. ### Parameters Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- -**analytics_rule_schema** | [**AnalyticsRuleSchema**](AnalyticsRuleSchema.md) | The Analytics rule to be created | [required] | +**create_analytics_rule_request** | [**CreateAnalyticsRuleRequest**](CreateAnalyticsRuleRequest.md) | The analytics rule(s) to be created | [required] | ### Return type -[**crate::models::AnalyticsRuleSchema**](AnalyticsRuleSchema.md) +[**models::CreateAnalyticsRule200Response**](createAnalyticsRule_200_response.md) ### Authorization @@ -43,7 +78,7 @@ Name | Type | Description | Required | Notes ## delete_analytics_rule -> crate::models::AnalyticsRuleSchema delete_analytics_rule(rule_name) +> models::AnalyticsRule delete_analytics_rule(rule_name) Delete an analytics rule Permanently deletes an analytics rule, given it's name @@ -57,7 +92,93 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::AnalyticsRuleSchema**](AnalyticsRuleSchema.md) +[**models::AnalyticsRule**](AnalyticsRule.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## flush_analytics + +> models::AnalyticsEventCreateResponse flush_analytics() +Flush in-memory analytics to disk + +Triggers a flush of analytics data to persistent storage. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::AnalyticsEventCreateResponse**](AnalyticsEventCreateResponse.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## get_analytics_events + +> models::AnalyticsEventsResponse get_analytics_events(user_id, name, n) +Retrieve analytics events + +Retrieve the most recent events for a user and rule. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**user_id** | **String** | | [required] | +**name** | **String** | Analytics rule name | [required] | +**n** | **i32** | Number of events to return (max 1000) | [required] | + +### Return type + +[**models::AnalyticsEventsResponse**](AnalyticsEventsResponse.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## get_analytics_status + +> models::AnalyticsStatus get_analytics_status() +Get analytics subsystem status + +Returns sizes of internal analytics buffers and queues. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::AnalyticsStatus**](AnalyticsStatus.md) ### Authorization @@ -73,7 +194,7 @@ Name | Type | Description | Required | Notes ## retrieve_analytics_rule -> crate::models::AnalyticsRuleSchema retrieve_analytics_rule(rule_name) +> models::AnalyticsRule retrieve_analytics_rule(rule_name) Retrieves an analytics rule Retrieve the details of an analytics rule, given it's name @@ -87,7 +208,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::AnalyticsRuleSchema**](AnalyticsRuleSchema.md) +[**models::AnalyticsRule**](AnalyticsRule.md) ### Authorization @@ -103,18 +224,21 @@ Name | Type | Description | Required | Notes ## retrieve_analytics_rules -> crate::models::AnalyticsRulesRetrieveSchema retrieve_analytics_rules() -Retrieves all analytics rules +> Vec retrieve_analytics_rules(rule_tag) +Retrieve analytics rules -Retrieve the details of all analytics rules +Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. ### Parameters -This endpoint does not need any parameter. + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**rule_tag** | Option<**String**> | Filter rules by rule_tag | | ### Return type -[**crate::models::AnalyticsRulesRetrieveSchema**](AnalyticsRulesRetrieveSchema.md) +[**Vec**](AnalyticsRule.md) ### Authorization @@ -127,3 +251,34 @@ This endpoint does not need any parameter. [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +## upsert_analytics_rule + +> models::AnalyticsRule upsert_analytics_rule(rule_name, analytics_rule_update) +Upserts an analytics rule + +Upserts an analytics rule with the given name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**rule_name** | **String** | The name of the analytics rule to upsert | [required] | +**analytics_rule_update** | [**AnalyticsRuleUpdate**](AnalyticsRuleUpdate.md) | The Analytics rule to be upserted | [required] | + +### Return type + +[**models::AnalyticsRule**](AnalyticsRule.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/AnalyticsEvent.md b/typesense_codegen/docs/AnalyticsEvent.md new file mode 100644 index 0000000..9fdacec --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEvent.md @@ -0,0 +1,13 @@ +# AnalyticsEvent + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | Name of the analytics rule this event corresponds to | +**event_type** | **String** | Type of event (e.g., click, conversion, query, visit) | +**data** | [**models::AnalyticsEventData**](AnalyticsEvent_data.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsEventCreateResponse.md b/typesense_codegen/docs/AnalyticsEventCreateResponse.md new file mode 100644 index 0000000..321be7b --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEventCreateResponse.md @@ -0,0 +1,11 @@ +# AnalyticsEventCreateResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ok** | **bool** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsEventCreateSchema.md b/typesense_codegen/docs/AnalyticsEventCreateSchema.md new file mode 100644 index 0000000..97c07cc --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEventCreateSchema.md @@ -0,0 +1,13 @@ +# AnalyticsEventCreateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | **String** | | +**name** | **String** | | +**data** | [**serde_json::Value**](.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsEventData.md b/typesense_codegen/docs/AnalyticsEventData.md new file mode 100644 index 0000000..22c8b02 --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEventData.md @@ -0,0 +1,15 @@ +# AnalyticsEventData + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**user_id** | Option<**String**> | | [optional] +**doc_id** | Option<**String**> | | [optional] +**doc_ids** | Option<**Vec**> | | [optional] +**q** | Option<**String**> | | [optional] +**analytics_tag** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsEventsResponse.md b/typesense_codegen/docs/AnalyticsEventsResponse.md new file mode 100644 index 0000000..ff6dbba --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEventsResponse.md @@ -0,0 +1,11 @@ +# AnalyticsEventsResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**events** | [**Vec**](AnalyticsEventsResponse_events_inner.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsEventsResponseEventsInner.md b/typesense_codegen/docs/AnalyticsEventsResponseEventsInner.md new file mode 100644 index 0000000..1d65b60 --- /dev/null +++ b/typesense_codegen/docs/AnalyticsEventsResponseEventsInner.md @@ -0,0 +1,18 @@ +# AnalyticsEventsResponseEventsInner + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | Option<**String**> | | [optional] +**event_type** | Option<**String**> | | [optional] +**collection** | Option<**String**> | | [optional] +**timestamp** | Option<**i64**> | | [optional] +**user_id** | Option<**String**> | | [optional] +**doc_id** | Option<**String**> | | [optional] +**doc_ids** | Option<**Vec**> | | [optional] +**query** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRule.md b/typesense_codegen/docs/AnalyticsRule.md new file mode 100644 index 0000000..3e28b5c --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRule.md @@ -0,0 +1,16 @@ +# AnalyticsRule + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | +**r#type** | **String** | | +**collection** | **String** | | +**event_type** | **String** | | +**rule_tag** | Option<**String**> | | [optional] +**params** | Option<[**models::AnalyticsRuleCreateParams**](AnalyticsRuleCreate_params.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleCreate.md b/typesense_codegen/docs/AnalyticsRuleCreate.md new file mode 100644 index 0000000..9fff80d --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleCreate.md @@ -0,0 +1,16 @@ +# AnalyticsRuleCreate + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | +**r#type** | **String** | | +**collection** | **String** | | +**event_type** | **String** | | +**rule_tag** | Option<**String**> | | [optional] +**params** | Option<[**models::AnalyticsRuleCreateParams**](AnalyticsRuleCreate_params.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleCreateParams.md b/typesense_codegen/docs/AnalyticsRuleCreateParams.md new file mode 100644 index 0000000..eba962c --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleCreateParams.md @@ -0,0 +1,17 @@ +# AnalyticsRuleCreateParams + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**destination_collection** | Option<**String**> | | [optional] +**limit** | Option<**i32**> | | [optional] +**capture_search_requests** | Option<**bool**> | | [optional] +**meta_fields** | Option<**Vec**> | | [optional] +**expand_query** | Option<**bool**> | | [optional] +**counter_field** | Option<**String**> | | [optional] +**weight** | Option<**i32**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleDeleteResponse.md b/typesense_codegen/docs/AnalyticsRuleDeleteResponse.md new file mode 100644 index 0000000..bd7512f --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleDeleteResponse.md @@ -0,0 +1,11 @@ +# AnalyticsRuleDeleteResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleParameters.md b/typesense_codegen/docs/AnalyticsRuleParameters.md index 31b4ac4..9be9eeb 100644 --- a/typesense_codegen/docs/AnalyticsRuleParameters.md +++ b/typesense_codegen/docs/AnalyticsRuleParameters.md @@ -4,9 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**source** | [**crate::models::AnalyticsRuleParametersSource**](AnalyticsRuleParameters_source.md) | | -**destination** | [**crate::models::AnalyticsRuleParametersDestination**](AnalyticsRuleParameters_destination.md) | | -**limit** | **i32** | | +**source** | [**models::AnalyticsRuleParametersSource**](AnalyticsRuleParametersSource.md) | | +**destination** | [**models::AnalyticsRuleParametersDestination**](AnalyticsRuleParametersDestination.md) | | +**limit** | Option<**i32**> | | [optional] +**expand_query** | Option<**bool**> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsRuleParametersDestination.md b/typesense_codegen/docs/AnalyticsRuleParametersDestination.md index 6bf99e5..e5efc9b 100644 --- a/typesense_codegen/docs/AnalyticsRuleParametersDestination.md +++ b/typesense_codegen/docs/AnalyticsRuleParametersDestination.md @@ -4,7 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**collection** | Option<**String**> | | [optional] +**collection** | **String** | | +**counter_field** | Option<**String**> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsRuleParametersSource.md b/typesense_codegen/docs/AnalyticsRuleParametersSource.md index b6a042b..05ab04d 100644 --- a/typesense_codegen/docs/AnalyticsRuleParametersSource.md +++ b/typesense_codegen/docs/AnalyticsRuleParametersSource.md @@ -4,7 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**collections** | Option<**Vec**> | | [optional] +**collections** | **Vec** | | +**events** | Option<[**Vec**](AnalyticsRuleParametersSource_events_inner.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsRuleParametersSourceEventsInner.md b/typesense_codegen/docs/AnalyticsRuleParametersSourceEventsInner.md new file mode 100644 index 0000000..31264d2 --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleParametersSourceEventsInner.md @@ -0,0 +1,13 @@ +# AnalyticsRuleParametersSourceEventsInner + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | **String** | | +**weight** | **f32** | | +**name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleSchema.md b/typesense_codegen/docs/AnalyticsRuleSchema.md index 359d489..4afdcd4 100644 --- a/typesense_codegen/docs/AnalyticsRuleSchema.md +++ b/typesense_codegen/docs/AnalyticsRuleSchema.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**name** | **String** | | **r#type** | **String** | | -**params** | [**crate::models::AnalyticsRuleParameters**](AnalyticsRuleParameters.md) | | +**params** | [**models::AnalyticsRuleParameters**](AnalyticsRuleParameters.md) | | +**name** | **String** | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsRuleUpdate.md b/typesense_codegen/docs/AnalyticsRuleUpdate.md new file mode 100644 index 0000000..7814cad --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleUpdate.md @@ -0,0 +1,13 @@ +# AnalyticsRuleUpdate + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | Option<**String**> | | [optional] +**rule_tag** | Option<**String**> | | [optional] +**params** | Option<[**models::AnalyticsRuleCreateParams**](AnalyticsRuleCreate_params.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRuleUpsertSchema.md b/typesense_codegen/docs/AnalyticsRuleUpsertSchema.md new file mode 100644 index 0000000..fa21e43 --- /dev/null +++ b/typesense_codegen/docs/AnalyticsRuleUpsertSchema.md @@ -0,0 +1,12 @@ +# AnalyticsRuleUpsertSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**r#type** | **String** | | +**params** | [**models::AnalyticsRuleParameters**](AnalyticsRuleParameters.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/AnalyticsRulesRetrieveSchema.md b/typesense_codegen/docs/AnalyticsRulesRetrieveSchema.md index f20cf77..c310473 100644 --- a/typesense_codegen/docs/AnalyticsRulesRetrieveSchema.md +++ b/typesense_codegen/docs/AnalyticsRulesRetrieveSchema.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**rules** | Option<[**Vec**](AnalyticsRuleSchema.md)> | | [optional] +**rules** | Option<[**Vec**](AnalyticsRuleSchema.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/AnalyticsStatus.md b/typesense_codegen/docs/AnalyticsStatus.md new file mode 100644 index 0000000..9bbc3c6 --- /dev/null +++ b/typesense_codegen/docs/AnalyticsStatus.md @@ -0,0 +1,17 @@ +# AnalyticsStatus + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**popular_prefix_queries** | Option<**i32**> | | [optional] +**nohits_prefix_queries** | Option<**i32**> | | [optional] +**log_prefix_queries** | Option<**i32**> | | [optional] +**query_log_events** | Option<**i32**> | | [optional] +**query_counter_events** | Option<**i32**> | | [optional] +**doc_log_events** | Option<**i32**> | | [optional] +**doc_counter_events** | Option<**i32**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ApiKeyDeleteResponse.md b/typesense_codegen/docs/ApiKeyDeleteResponse.md new file mode 100644 index 0000000..8c38f9e --- /dev/null +++ b/typesense_codegen/docs/ApiKeyDeleteResponse.md @@ -0,0 +1,11 @@ +# ApiKeyDeleteResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **i64** | The id of the API key that was deleted | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ApiKeysResponse.md b/typesense_codegen/docs/ApiKeysResponse.md index 1eac36f..c3e6c3d 100644 --- a/typesense_codegen/docs/ApiKeysResponse.md +++ b/typesense_codegen/docs/ApiKeysResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**keys** | [**Vec**](ApiKey.md) | | +**keys** | [**Vec**](ApiKey.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/ApiStatsResponse.md b/typesense_codegen/docs/ApiStatsResponse.md new file mode 100644 index 0000000..c2569e7 --- /dev/null +++ b/typesense_codegen/docs/ApiStatsResponse.md @@ -0,0 +1,23 @@ +# ApiStatsResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**delete_latency_ms** | Option<**f64**> | | [optional] +**delete_requests_per_second** | Option<**f64**> | | [optional] +**import_latency_ms** | Option<**f64**> | | [optional] +**import_requests_per_second** | Option<**f64**> | | [optional] +**latency_ms** | Option<[**serde_json::Value**](.md)> | | [optional] +**overloaded_requests_per_second** | Option<**f64**> | | [optional] +**pending_write_batches** | Option<**f64**> | | [optional] +**requests_per_second** | Option<[**serde_json::Value**](.md)> | | [optional] +**search_latency_ms** | Option<**f64**> | | [optional] +**search_requests_per_second** | Option<**f64**> | | [optional] +**total_requests_per_second** | Option<**f64**> | | [optional] +**write_latency_ms** | Option<**f64**> | | [optional] +**write_requests_per_second** | Option<**f64**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/CollectionAliasesResponse.md b/typesense_codegen/docs/CollectionAliasesResponse.md index b8a0399..285708c 100644 --- a/typesense_codegen/docs/CollectionAliasesResponse.md +++ b/typesense_codegen/docs/CollectionAliasesResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**aliases** | [**Vec**](CollectionAlias.md) | | +**aliases** | [**Vec**](CollectionAlias.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/CollectionResponse.md b/typesense_codegen/docs/CollectionResponse.md index aeb74a4..28b03da 100644 --- a/typesense_codegen/docs/CollectionResponse.md +++ b/typesense_codegen/docs/CollectionResponse.md @@ -5,11 +5,14 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **String** | Name of the collection | -**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | +**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | **default_sorting_field** | Option<**String**> | The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. | [optional][default to ] -**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] +**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] +**synonym_sets** | Option<**Vec**> | List of synonym set names to associate with this collection | [optional] **enable_nested_fields** | Option<**bool**> | Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. | [optional][default to false] **symbols_to_index** | Option<**Vec**> | List of symbols or special characters to be indexed. | [optional][default to []] +**voice_query_model** | Option<[**models::VoiceQueryModelCollectionConfig**](VoiceQueryModelCollectionConfig.md)> | | [optional] +**metadata** | Option<[**serde_json::Value**](.md)> | Optional details about the collection, e.g., when it was created, who created it etc. | [optional] **num_documents** | **i64** | Number of documents in the collection | [readonly] **created_at** | **i64** | Timestamp of when the collection was created (Unix epoch in seconds) | [readonly] diff --git a/typesense_codegen/docs/CollectionSchema.md b/typesense_codegen/docs/CollectionSchema.md index 1f78262..bca7415 100644 --- a/typesense_codegen/docs/CollectionSchema.md +++ b/typesense_codegen/docs/CollectionSchema.md @@ -5,11 +5,14 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **String** | Name of the collection | -**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | +**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | **default_sorting_field** | Option<**String**> | The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. | [optional][default to ] -**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] +**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] +**synonym_sets** | Option<**Vec**> | List of synonym set names to associate with this collection | [optional] **enable_nested_fields** | Option<**bool**> | Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. | [optional][default to false] **symbols_to_index** | Option<**Vec**> | List of symbols or special characters to be indexed. | [optional][default to []] +**voice_query_model** | Option<[**models::VoiceQueryModelCollectionConfig**](VoiceQueryModelCollectionConfig.md)> | | [optional] +**metadata** | Option<[**serde_json::Value**](.md)> | Optional details about the collection, e.g., when it was created, who created it etc. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/CollectionUpdateSchema.md b/typesense_codegen/docs/CollectionUpdateSchema.md index d40d070..6167d13 100644 --- a/typesense_codegen/docs/CollectionUpdateSchema.md +++ b/typesense_codegen/docs/CollectionUpdateSchema.md @@ -4,7 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | +**fields** | [**Vec**](Field.md) | A list of fields for querying, filtering and faceting | +**synonym_sets** | Option<**Vec**> | List of synonym set names to associate with this collection | [optional] +**metadata** | Option<[**serde_json::Value**](.md)> | Optional details about the collection, e.g., when it was created, who created it etc. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/CollectionsApi.md b/typesense_codegen/docs/CollectionsApi.md index 14cb336..4dc1cdf 100644 --- a/typesense_codegen/docs/CollectionsApi.md +++ b/typesense_codegen/docs/CollectionsApi.md @@ -1,6 +1,6 @@ # \CollectionsApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -18,7 +18,7 @@ Method | HTTP request | Description ## create_collection -> crate::models::CollectionResponse create_collection(collection_schema) +> models::CollectionResponse create_collection(collection_schema) Create a new collection When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. @@ -32,7 +32,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionResponse**](CollectionResponse.md) +[**models::CollectionResponse**](CollectionResponse.md) ### Authorization @@ -48,7 +48,7 @@ Name | Type | Description | Required | Notes ## delete_alias -> crate::models::CollectionAlias delete_alias(alias_name) +> models::CollectionAlias delete_alias(alias_name) Delete an alias ### Parameters @@ -60,7 +60,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionAlias**](CollectionAlias.md) +[**models::CollectionAlias**](CollectionAlias.md) ### Authorization @@ -76,7 +76,7 @@ Name | Type | Description | Required | Notes ## delete_collection -> crate::models::CollectionResponse delete_collection(collection_name) +> models::CollectionResponse delete_collection(collection_name) Delete a collection Permanently drops a collection. This action cannot be undone. For large collections, this might have an impact on read latencies. @@ -90,7 +90,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionResponse**](CollectionResponse.md) +[**models::CollectionResponse**](CollectionResponse.md) ### Authorization @@ -106,7 +106,7 @@ Name | Type | Description | Required | Notes ## get_alias -> crate::models::CollectionAlias get_alias(alias_name) +> models::CollectionAlias get_alias(alias_name) Retrieve an alias Find out which collection an alias points to by fetching it @@ -120,7 +120,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionAlias**](CollectionAlias.md) +[**models::CollectionAlias**](CollectionAlias.md) ### Authorization @@ -136,7 +136,7 @@ Name | Type | Description | Required | Notes ## get_aliases -> crate::models::CollectionAliasesResponse get_aliases() +> models::CollectionAliasesResponse get_aliases() List all aliases List all aliases and the corresponding collections that they map to. @@ -147,7 +147,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::CollectionAliasesResponse**](CollectionAliasesResponse.md) +[**models::CollectionAliasesResponse**](CollectionAliasesResponse.md) ### Authorization @@ -163,7 +163,7 @@ This endpoint does not need any parameter. ## get_collection -> crate::models::CollectionResponse get_collection(collection_name) +> models::CollectionResponse get_collection(collection_name) Retrieve a single collection Retrieve the details of a collection, given its name. @@ -177,7 +177,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionResponse**](CollectionResponse.md) +[**models::CollectionResponse**](CollectionResponse.md) ### Authorization @@ -193,18 +193,23 @@ Name | Type | Description | Required | Notes ## get_collections -> Vec get_collections() +> Vec get_collections(exclude_fields, limit, offset) List all collections Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first. ### Parameters -This endpoint does not need any parameter. + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**exclude_fields** | Option<**String**> | | | +**limit** | Option<**i32**> | | | +**offset** | Option<**i32**> | | | ### Return type -[**Vec**](CollectionResponse.md) +[**Vec**](CollectionResponse.md) ### Authorization @@ -220,7 +225,7 @@ This endpoint does not need any parameter. ## update_collection -> crate::models::CollectionUpdateSchema update_collection(collection_name, collection_update_schema) +> models::CollectionUpdateSchema update_collection(collection_name, collection_update_schema) Update a collection Update a collection's schema to modify the fields and their types. @@ -235,7 +240,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionUpdateSchema**](CollectionUpdateSchema.md) +[**models::CollectionUpdateSchema**](CollectionUpdateSchema.md) ### Authorization @@ -251,7 +256,7 @@ Name | Type | Description | Required | Notes ## upsert_alias -> crate::models::CollectionAlias upsert_alias(alias_name, collection_alias_schema) +> models::CollectionAlias upsert_alias(alias_name, collection_alias_schema) Create or update a collection alias Create or update a collection alias. An alias is a virtual collection name that points to a real collection. If you're familiar with symbolic links on Linux, it's very similar to that. Aliases are useful when you want to reindex your data in the background on a new collection and switch your application to it without any changes to your code. @@ -266,7 +271,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::CollectionAlias**](CollectionAlias.md) +[**models::CollectionAlias**](CollectionAlias.md) ### Authorization diff --git a/typesense_codegen/docs/ConversationModelCreateSchema.md b/typesense_codegen/docs/ConversationModelCreateSchema.md new file mode 100644 index 0000000..a8d70c5 --- /dev/null +++ b/typesense_codegen/docs/ConversationModelCreateSchema.md @@ -0,0 +1,19 @@ +# ConversationModelCreateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | Option<**String**> | An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. | [optional] +**model_name** | **String** | Name of the LLM model offered by OpenAI, Cloudflare or vLLM | +**api_key** | Option<**String**> | The LLM service's API Key | [optional] +**history_collection** | **String** | Typesense collection that stores the historical conversations | +**account_id** | Option<**String**> | LLM service's account ID (only applicable for Cloudflare) | [optional] +**system_prompt** | Option<**String**> | The system prompt that contains special instructions to the LLM | [optional] +**ttl** | Option<**i32**> | Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) | [optional] +**max_bytes** | **i32** | The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. | +**vllm_url** | Option<**String**> | URL of vLLM service | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ConversationModelSchema.md b/typesense_codegen/docs/ConversationModelSchema.md new file mode 100644 index 0000000..f9fe0d2 --- /dev/null +++ b/typesense_codegen/docs/ConversationModelSchema.md @@ -0,0 +1,19 @@ +# ConversationModelSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. | +**model_name** | **String** | Name of the LLM model offered by OpenAI, Cloudflare or vLLM | +**api_key** | Option<**String**> | The LLM service's API Key | [optional] +**history_collection** | **String** | Typesense collection that stores the historical conversations | +**account_id** | Option<**String**> | LLM service's account ID (only applicable for Cloudflare) | [optional] +**system_prompt** | Option<**String**> | The system prompt that contains special instructions to the LLM | [optional] +**ttl** | Option<**i32**> | Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) | [optional] +**max_bytes** | **i32** | The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. | +**vllm_url** | Option<**String**> | URL of vLLM service | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ConversationModelUpdateSchema.md b/typesense_codegen/docs/ConversationModelUpdateSchema.md new file mode 100644 index 0000000..a9471ce --- /dev/null +++ b/typesense_codegen/docs/ConversationModelUpdateSchema.md @@ -0,0 +1,19 @@ +# ConversationModelUpdateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | Option<**String**> | An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. | [optional] +**model_name** | Option<**String**> | Name of the LLM model offered by OpenAI, Cloudflare or vLLM | [optional] +**api_key** | Option<**String**> | The LLM service's API Key | [optional] +**history_collection** | Option<**String**> | Typesense collection that stores the historical conversations | [optional] +**account_id** | Option<**String**> | LLM service's account ID (only applicable for Cloudflare) | [optional] +**system_prompt** | Option<**String**> | The system prompt that contains special instructions to the LLM | [optional] +**ttl** | Option<**i32**> | Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) | [optional] +**max_bytes** | Option<**i32**> | The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. | [optional] +**vllm_url** | Option<**String**> | URL of vLLM service | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ConversationsApi.md b/typesense_codegen/docs/ConversationsApi.md new file mode 100644 index 0000000..4d4d581 --- /dev/null +++ b/typesense_codegen/docs/ConversationsApi.md @@ -0,0 +1,161 @@ +# \ConversationsApi + +All URIs are relative to *http://localhost:8108* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_conversation_model**](ConversationsApi.md#create_conversation_model) | **POST** /conversations/models | Create a conversation model +[**delete_conversation_model**](ConversationsApi.md#delete_conversation_model) | **DELETE** /conversations/models/{modelId} | Delete a conversation model +[**retrieve_all_conversation_models**](ConversationsApi.md#retrieve_all_conversation_models) | **GET** /conversations/models | List all conversation models +[**retrieve_conversation_model**](ConversationsApi.md#retrieve_conversation_model) | **GET** /conversations/models/{modelId} | Retrieve a conversation model +[**update_conversation_model**](ConversationsApi.md#update_conversation_model) | **PUT** /conversations/models/{modelId} | Update a conversation model + + + +## create_conversation_model + +> models::ConversationModelSchema create_conversation_model(conversation_model_create_schema) +Create a conversation model + +Create a Conversation Model + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**conversation_model_create_schema** | [**ConversationModelCreateSchema**](ConversationModelCreateSchema.md) | | [required] | + +### Return type + +[**models::ConversationModelSchema**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## delete_conversation_model + +> models::ConversationModelSchema delete_conversation_model(model_id) +Delete a conversation model + +Delete a conversation model + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The id of the conversation model to delete | [required] | + +### Return type + +[**models::ConversationModelSchema**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_all_conversation_models + +> Vec retrieve_all_conversation_models() +List all conversation models + +Retrieve all conversation models + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**Vec**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_conversation_model + +> models::ConversationModelSchema retrieve_conversation_model(model_id) +Retrieve a conversation model + +Retrieve a conversation model + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The id of the conversation model to retrieve | [required] | + +### Return type + +[**models::ConversationModelSchema**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## update_conversation_model + +> models::ConversationModelSchema update_conversation_model(model_id, conversation_model_update_schema) +Update a conversation model + +Update a conversation model + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The id of the conversation model to update | [required] | +**conversation_model_update_schema** | [**ConversationModelUpdateSchema**](ConversationModelUpdateSchema.md) | | [required] | + +### Return type + +[**models::ConversationModelSchema**](ConversationModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/CreateAnalyticsRule200Response.md b/typesense_codegen/docs/CreateAnalyticsRule200Response.md new file mode 100644 index 0000000..ed4affd --- /dev/null +++ b/typesense_codegen/docs/CreateAnalyticsRule200Response.md @@ -0,0 +1,12 @@ +# CreateAnalyticsRule200Response + +## Enum Variants + +| Name | Description | +|---- | -----| +| AnalyticsRule | | +| Vec | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInner.md b/typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInner.md new file mode 100644 index 0000000..d2f71ed --- /dev/null +++ b/typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInner.md @@ -0,0 +1,17 @@ +# CreateAnalyticsRule200ResponseOneOfInner + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | +**r#type** | **String** | | +**collection** | **String** | | +**event_type** | **String** | | +**rule_tag** | Option<**String**> | | [optional] +**params** | Option<[**models::AnalyticsRuleCreateParams**](AnalyticsRuleCreate_params.md)> | | [optional] +**error** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.md b/typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.md new file mode 100644 index 0000000..030113b --- /dev/null +++ b/typesense_codegen/docs/CreateAnalyticsRule200ResponseOneOfInnerAnyOf.md @@ -0,0 +1,11 @@ +# CreateAnalyticsRule200ResponseOneOfInnerAnyOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**error** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/CreateAnalyticsRuleRequest.md b/typesense_codegen/docs/CreateAnalyticsRuleRequest.md new file mode 100644 index 0000000..89c4bdc --- /dev/null +++ b/typesense_codegen/docs/CreateAnalyticsRuleRequest.md @@ -0,0 +1,12 @@ +# CreateAnalyticsRuleRequest + +## Enum Variants + +| Name | Description | +|---- | -----| +| AnalyticsRuleCreate | | +| Vec | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PromoteApi.md b/typesense_codegen/docs/CurationApi.md similarity index 70% rename from typesense_codegen/docs/PromoteApi.md rename to typesense_codegen/docs/CurationApi.md index 948b093..bb8afc5 100644 --- a/typesense_codegen/docs/PromoteApi.md +++ b/typesense_codegen/docs/CurationApi.md @@ -1,18 +1,18 @@ -# \PromoteApi +# \CurationApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- -[**delete_search_override**](PromoteApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection -[**get_search_overrides**](PromoteApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides -[**upsert_search_override**](PromoteApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others +[**delete_search_override**](CurationApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection +[**get_search_overrides**](CurationApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides +[**upsert_search_override**](CurationApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others ## delete_search_override -> crate::models::SearchOverride delete_search_override(collection_name, override_id) +> models::SearchOverrideDeleteResponse delete_search_override(collection_name, override_id) Delete an override associated with a collection ### Parameters @@ -25,7 +25,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) +[**models::SearchOverrideDeleteResponse**](SearchOverrideDeleteResponse.md) ### Authorization @@ -41,7 +41,7 @@ Name | Type | Description | Required | Notes ## get_search_overrides -> crate::models::SearchOverridesResponse get_search_overrides(collection_name) +> models::SearchOverridesResponse get_search_overrides(collection_name) List all collection overrides ### Parameters @@ -53,7 +53,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverridesResponse**](SearchOverridesResponse.md) +[**models::SearchOverridesResponse**](SearchOverridesResponse.md) ### Authorization @@ -69,7 +69,7 @@ Name | Type | Description | Required | Notes ## upsert_search_override -> crate::models::SearchOverride upsert_search_override(collection_name, override_id, search_override_schema) +> models::SearchOverride upsert_search_override(collection_name, override_id, search_override_schema) Create or update an override to promote certain documents over others Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. @@ -85,7 +85,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) +[**models::SearchOverride**](SearchOverride.md) ### Authorization diff --git a/typesense_codegen/docs/DebugApi.md b/typesense_codegen/docs/DebugApi.md index a1f8c0f..58e8833 100644 --- a/typesense_codegen/docs/DebugApi.md +++ b/typesense_codegen/docs/DebugApi.md @@ -1,6 +1,6 @@ # \DebugApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -10,7 +10,7 @@ Method | HTTP request | Description ## debug -> crate::models::Debug200Response debug() +> models::Debug200Response debug() Print debugging information Print debugging information @@ -21,7 +21,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::Debug200Response**](debug_200_response.md) +[**models::Debug200Response**](debug_200_response.md) ### Authorization diff --git a/typesense_codegen/docs/DeleteDocumentsDeleteDocumentsParametersParameter.md b/typesense_codegen/docs/DeleteDocumentsDeleteDocumentsParametersParameter.md index 433c2be..ca66c4a 100644 --- a/typesense_codegen/docs/DeleteDocumentsDeleteDocumentsParametersParameter.md +++ b/typesense_codegen/docs/DeleteDocumentsDeleteDocumentsParametersParameter.md @@ -4,8 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**filter_by** | Option<**String**> | | [optional] +**filter_by** | **String** | | **batch_size** | Option<**i32**> | Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. | [optional] +**ignore_not_found** | Option<**bool**> | | [optional] +**truncate** | Option<**bool**> | When true, removes all documents from the collection while preserving the collection and its schema. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/DeleteDocumentsParameters.md b/typesense_codegen/docs/DeleteDocumentsParameters.md new file mode 100644 index 0000000..f960189 --- /dev/null +++ b/typesense_codegen/docs/DeleteDocumentsParameters.md @@ -0,0 +1,14 @@ +# DeleteDocumentsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**filter_by** | **String** | | +**batch_size** | Option<**i32**> | Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. | [optional] +**ignore_not_found** | Option<**bool**> | | [optional] +**truncate** | Option<**bool**> | When true, removes all documents from the collection while preserving the collection and its schema. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/DeleteStopwordsSet200Response.md b/typesense_codegen/docs/DeleteStopwordsSet200Response.md new file mode 100644 index 0000000..919a663 --- /dev/null +++ b/typesense_codegen/docs/DeleteStopwordsSet200Response.md @@ -0,0 +1,11 @@ +# DeleteStopwordsSet200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/DirtyValues.md b/typesense_codegen/docs/DirtyValues.md new file mode 100644 index 0000000..50492e1 --- /dev/null +++ b/typesense_codegen/docs/DirtyValues.md @@ -0,0 +1,15 @@ +# DirtyValues + +## Enum Variants + +| Name | Value | +|---- | -----| +| CoerceOrReject | coerce_or_reject | +| CoerceOrDrop | coerce_or_drop | +| Drop | drop | +| Reject | reject | + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/DocumentIndexParameters.md b/typesense_codegen/docs/DocumentIndexParameters.md new file mode 100644 index 0000000..08f8e95 --- /dev/null +++ b/typesense_codegen/docs/DocumentIndexParameters.md @@ -0,0 +1,11 @@ +# DocumentIndexParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**dirty_values** | Option<[**models::DirtyValues**](DirtyValues.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/DocumentsApi.md b/typesense_codegen/docs/DocumentsApi.md index eebec19..9b5858f 100644 --- a/typesense_codegen/docs/DocumentsApi.md +++ b/typesense_codegen/docs/DocumentsApi.md @@ -1,19 +1,16 @@ # \DocumentsApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- [**delete_document**](DocumentsApi.md#delete_document) | **DELETE** /collections/{collectionName}/documents/{documentId} | Delete a document [**delete_documents**](DocumentsApi.md#delete_documents) | **DELETE** /collections/{collectionName}/documents | Delete a bunch of documents [**delete_search_override**](DocumentsApi.md#delete_search_override) | **DELETE** /collections/{collectionName}/overrides/{overrideId} | Delete an override associated with a collection -[**delete_search_synonym**](DocumentsApi.md#delete_search_synonym) | **DELETE** /collections/{collectionName}/synonyms/{synonymId} | Delete a synonym associated with a collection [**export_documents**](DocumentsApi.md#export_documents) | **GET** /collections/{collectionName}/documents/export | Export all documents in a collection -[**get_document**](DocumentsApi.md#get_document) | **GET** /collections/{collectionName}/documents/{documentId} | Retreive a document +[**get_document**](DocumentsApi.md#get_document) | **GET** /collections/{collectionName}/documents/{documentId} | Retrieve a document [**get_search_override**](DocumentsApi.md#get_search_override) | **GET** /collections/{collectionName}/overrides/{overrideId} | Retrieve a single search override [**get_search_overrides**](DocumentsApi.md#get_search_overrides) | **GET** /collections/{collectionName}/overrides | List all collection overrides -[**get_search_synonym**](DocumentsApi.md#get_search_synonym) | **GET** /collections/{collectionName}/synonyms/{synonymId} | Retrieve a single search synonym -[**get_search_synonyms**](DocumentsApi.md#get_search_synonyms) | **GET** /collections/{collectionName}/synonyms | List all collection synonyms [**import_documents**](DocumentsApi.md#import_documents) | **POST** /collections/{collectionName}/documents/import | Import documents into a collection [**index_document**](DocumentsApi.md#index_document) | **POST** /collections/{collectionName}/documents | Index a document [**multi_search**](DocumentsApi.md#multi_search) | **POST** /multi_search | send multiple search requests in a single HTTP request @@ -21,7 +18,6 @@ Method | HTTP request | Description [**update_document**](DocumentsApi.md#update_document) | **PATCH** /collections/{collectionName}/documents/{documentId} | Update a document [**update_documents**](DocumentsApi.md#update_documents) | **PATCH** /collections/{collectionName}/documents | Update documents with conditional query [**upsert_search_override**](DocumentsApi.md#upsert_search_override) | **PUT** /collections/{collectionName}/overrides/{overrideId} | Create or update an override to promote certain documents over others -[**upsert_search_synonym**](DocumentsApi.md#upsert_search_synonym) | **PUT** /collections/{collectionName}/synonyms/{synonymId} | Create or update a synonym @@ -58,7 +54,7 @@ Name | Type | Description | Required | Notes ## delete_documents -> crate::models::DeleteDocuments200Response delete_documents(collection_name, delete_documents_parameters) +> models::DeleteDocuments200Response delete_documents(collection_name, filter_by, batch_size, ignore_not_found, truncate) Delete a bunch of documents Delete a bunch of documents that match a specific filter condition. Use the `batch_size` parameter to control the number of documents that should deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. @@ -69,11 +65,14 @@ Delete a bunch of documents that match a specific filter condition. Use the `bat Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection to delete documents from | [required] | -**delete_documents_parameters** | Option<[**DeleteDocumentsDeleteDocumentsParametersParameter**](.md)> | | | +**filter_by** | Option<**String**> | | | +**batch_size** | Option<**i32**> | | | +**ignore_not_found** | Option<**bool**> | | | +**truncate** | Option<**bool**> | | | ### Return type -[**crate::models::DeleteDocuments200Response**](deleteDocuments_200_response.md) +[**models::DeleteDocuments200Response**](deleteDocuments_200_response.md) ### Authorization @@ -89,7 +88,7 @@ Name | Type | Description | Required | Notes ## delete_search_override -> crate::models::SearchOverride delete_search_override(collection_name, override_id) +> models::SearchOverrideDeleteResponse delete_search_override(collection_name, override_id) Delete an override associated with a collection ### Parameters @@ -102,36 +101,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) - -### Authorization - -[api_key_header](../README.md#api_key_header) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -## delete_search_synonym - -> crate::models::SearchSynonym delete_search_synonym(collection_name, synonym_id) -Delete a synonym associated with a collection - -### Parameters - - -Name | Type | Description | Required | Notes -------------- | ------------- | ------------- | ------------- | ------------- -**collection_name** | **String** | The name of the collection | [required] | -**synonym_id** | **String** | The ID of the search synonym to delete | [required] | - -### Return type - -[**crate::models::SearchSynonym**](SearchSynonym.md) +[**models::SearchOverrideDeleteResponse**](SearchOverrideDeleteResponse.md) ### Authorization @@ -147,7 +117,7 @@ Name | Type | Description | Required | Notes ## export_documents -> String export_documents(collection_name, export_documents_parameters) +> String export_documents(collection_name, filter_by, include_fields, exclude_fields) Export all documents in a collection Export all documents in a collection in JSON lines format. @@ -158,7 +128,9 @@ Export all documents in a collection in JSON lines format. Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection | [required] | -**export_documents_parameters** | Option<[**ExportDocumentsExportDocumentsParametersParameter**](.md)> | | | +**filter_by** | Option<**String**> | | | +**include_fields** | Option<**String**> | | | +**exclude_fields** | Option<**String**> | | | ### Return type @@ -179,7 +151,7 @@ Name | Type | Description | Required | Notes ## get_document > serde_json::Value get_document(collection_name, document_id) -Retreive a document +Retrieve a document Fetch an individual document from a collection by using its ID. @@ -209,7 +181,7 @@ Name | Type | Description | Required | Notes ## get_search_override -> crate::models::SearchOverride get_search_override(collection_name, override_id) +> models::SearchOverride get_search_override(collection_name, override_id) Retrieve a single search override Retrieve the details of a search override, given its id. @@ -224,7 +196,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) +[**models::SearchOverride**](SearchOverride.md) ### Authorization @@ -240,7 +212,7 @@ Name | Type | Description | Required | Notes ## get_search_overrides -> crate::models::SearchOverridesResponse get_search_overrides(collection_name) +> models::SearchOverridesResponse get_search_overrides(collection_name) List all collection overrides ### Parameters @@ -252,66 +224,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverridesResponse**](SearchOverridesResponse.md) - -### Authorization - -[api_key_header](../README.md#api_key_header) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -## get_search_synonym - -> crate::models::SearchSynonym get_search_synonym(collection_name, synonym_id) -Retrieve a single search synonym - -Retrieve the details of a search synonym, given its id. - -### Parameters - - -Name | Type | Description | Required | Notes -------------- | ------------- | ------------- | ------------- | ------------- -**collection_name** | **String** | The name of the collection | [required] | -**synonym_id** | **String** | The id of the search synonym | [required] | - -### Return type - -[**crate::models::SearchSynonym**](SearchSynonym.md) - -### Authorization - -[api_key_header](../README.md#api_key_header) - -### HTTP request headers - -- **Content-Type**: Not defined -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -## get_search_synonyms - -> crate::models::SearchSynonymsResponse get_search_synonyms(collection_name) -List all collection synonyms - -### Parameters - - -Name | Type | Description | Required | Notes -------------- | ------------- | ------------- | ------------- | ------------- -**collection_name** | **String** | The name of the collection | [required] | - -### Return type - -[**crate::models::SearchSynonymsResponse**](SearchSynonymsResponse.md) +[**models::SearchOverridesResponse**](SearchOverridesResponse.md) ### Authorization @@ -327,7 +240,7 @@ Name | Type | Description | Required | Notes ## import_documents -> String import_documents(collection_name, body, import_documents_parameters) +> String import_documents(collection_name, body, batch_size, return_id, remote_embedding_batch_size, return_doc, action, dirty_values) Import documents into a collection The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. @@ -339,7 +252,12 @@ Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection | [required] | **body** | **String** | The json array of documents or the JSONL file to import | [required] | -**import_documents_parameters** | Option<[**ImportDocumentsImportDocumentsParametersParameter**](.md)> | | | +**batch_size** | Option<**i32**> | | | +**return_id** | Option<**bool**> | | | +**remote_embedding_batch_size** | Option<**i32**> | | | +**return_doc** | Option<**bool**> | | | +**action** | Option<[**IndexAction**](.md)> | | | +**dirty_values** | Option<[**DirtyValues**](.md)> | | | ### Return type @@ -359,7 +277,7 @@ Name | Type | Description | Required | Notes ## index_document -> serde_json::Value index_document(collection_name, body, action) +> serde_json::Value index_document(collection_name, body, action, dirty_values) Index a document A document to be indexed in a given collection must conform to the schema of the collection. @@ -371,7 +289,8 @@ Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection to add the document to | [required] | **body** | **serde_json::Value** | The document object to be indexed | [required] | -**action** | Option<**String**> | Additional action to perform | | +**action** | Option<**IndexAction**> | Additional action to perform | | +**dirty_values** | Option<[**DirtyValues**](.md)> | Dealing with Dirty Data | | ### Return type @@ -391,7 +310,7 @@ Name | Type | Description | Required | Notes ## multi_search -> crate::models::MultiSearchResult multi_search(multi_search_parameters, multi_search_searches_parameter) +> models::MultiSearchResult multi_search(q, query_by, query_by_weights, text_match_type, prefix, infix, max_extra_prefix, max_extra_suffix, filter_by, sort_by, facet_by, max_facet_values, facet_query, num_typos, page, per_page, limit, offset, group_by, group_limit, group_missing_values, include_fields, exclude_fields, highlight_full_fields, highlight_affix_num_tokens, highlight_start_tag, highlight_end_tag, snippet_threshold, drop_tokens_threshold, drop_tokens_mode, typo_tokens_threshold, enable_typos_for_alpha_numerical_tokens, filter_curated_hits, enable_synonyms, enable_analytics, synonym_prefix, synonym_num_typos, pinned_hits, hidden_hits, override_tags, highlight_fields, pre_segmented_query, preset, enable_overrides, prioritize_exact_match, prioritize_token_position, prioritize_num_matching_fields, enable_typos_for_numerical_tokens, exhaustive_search, search_cutoff_ms, use_cache, cache_ttl, min_len_1typo, min_len_2typo, vector_query, remote_embedding_timeout_ms, remote_embedding_num_tries, facet_strategy, stopwords, facet_return_parent, voice_query, conversation, conversation_model_id, conversation_id, multi_search_searches_parameter) send multiple search requests in a single HTTP request This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. @@ -401,12 +320,75 @@ This is especially useful to avoid round-trip network latencies incurred otherwi Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- -**multi_search_parameters** | [**MultiSearchParameters**](.md) | | [required] | +**q** | Option<**String**> | | | +**query_by** | Option<**String**> | | | +**query_by_weights** | Option<**String**> | | | +**text_match_type** | Option<**String**> | | | +**prefix** | Option<**String**> | | | +**infix** | Option<**String**> | | | +**max_extra_prefix** | Option<**i32**> | | | +**max_extra_suffix** | Option<**i32**> | | | +**filter_by** | Option<**String**> | | | +**sort_by** | Option<**String**> | | | +**facet_by** | Option<**String**> | | | +**max_facet_values** | Option<**i32**> | | | +**facet_query** | Option<**String**> | | | +**num_typos** | Option<**String**> | | | +**page** | Option<**i32**> | | | +**per_page** | Option<**i32**> | | | +**limit** | Option<**i32**> | | | +**offset** | Option<**i32**> | | | +**group_by** | Option<**String**> | | | +**group_limit** | Option<**i32**> | | | +**group_missing_values** | Option<**bool**> | | | +**include_fields** | Option<**String**> | | | +**exclude_fields** | Option<**String**> | | | +**highlight_full_fields** | Option<**String**> | | | +**highlight_affix_num_tokens** | Option<**i32**> | | | +**highlight_start_tag** | Option<**String**> | | | +**highlight_end_tag** | Option<**String**> | | | +**snippet_threshold** | Option<**i32**> | | | +**drop_tokens_threshold** | Option<**i32**> | | | +**drop_tokens_mode** | Option<[**DropTokensMode**](.md)> | | | +**typo_tokens_threshold** | Option<**i32**> | | | +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | | | +**filter_curated_hits** | Option<**bool**> | | | +**enable_synonyms** | Option<**bool**> | | | +**enable_analytics** | Option<**bool**> | | |[default to true] +**synonym_prefix** | Option<**bool**> | | | +**synonym_num_typos** | Option<**i32**> | | | +**pinned_hits** | Option<**String**> | | | +**hidden_hits** | Option<**String**> | | | +**override_tags** | Option<**String**> | | | +**highlight_fields** | Option<**String**> | | | +**pre_segmented_query** | Option<**bool**> | | |[default to false] +**preset** | Option<**String**> | | | +**enable_overrides** | Option<**bool**> | | |[default to false] +**prioritize_exact_match** | Option<**bool**> | | |[default to true] +**prioritize_token_position** | Option<**bool**> | | |[default to false] +**prioritize_num_matching_fields** | Option<**bool**> | | |[default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | | |[default to true] +**exhaustive_search** | Option<**bool**> | | | +**search_cutoff_ms** | Option<**i32**> | | | +**use_cache** | Option<**bool**> | | | +**cache_ttl** | Option<**i32**> | | | +**min_len_1typo** | Option<**i32**> | | | +**min_len_2typo** | Option<**i32**> | | | +**vector_query** | Option<**String**> | | | +**remote_embedding_timeout_ms** | Option<**i32**> | | | +**remote_embedding_num_tries** | Option<**i32**> | | | +**facet_strategy** | Option<**String**> | | | +**stopwords** | Option<**String**> | | | +**facet_return_parent** | Option<**String**> | | | +**voice_query** | Option<**String**> | | | +**conversation** | Option<**bool**> | | | +**conversation_model_id** | Option<**String**> | | | +**conversation_id** | Option<**String**> | | | **multi_search_searches_parameter** | Option<[**MultiSearchSearchesParameter**](MultiSearchSearchesParameter.md)> | | | ### Return type -[**crate::models::MultiSearchResult**](MultiSearchResult.md) +[**models::MultiSearchResult**](MultiSearchResult.md) ### Authorization @@ -422,7 +404,7 @@ Name | Type | Description | Required | Notes ## search_collection -> crate::models::SearchResult search_collection(collection_name, search_parameters) +> models::SearchResult search_collection(collection_name, q, query_by, nl_query, nl_model_id, query_by_weights, text_match_type, prefix, infix, max_extra_prefix, max_extra_suffix, filter_by, max_filter_by_candidates, sort_by, facet_by, max_facet_values, facet_query, num_typos, page, per_page, limit, offset, group_by, group_limit, group_missing_values, include_fields, exclude_fields, highlight_full_fields, highlight_affix_num_tokens, highlight_start_tag, highlight_end_tag, enable_highlight_v1, enable_analytics, snippet_threshold, synonym_sets, drop_tokens_threshold, drop_tokens_mode, typo_tokens_threshold, enable_typos_for_alpha_numerical_tokens, filter_curated_hits, enable_synonyms, synonym_prefix, synonym_num_typos, pinned_hits, hidden_hits, override_tags, highlight_fields, split_join_tokens, pre_segmented_query, preset, enable_overrides, prioritize_exact_match, max_candidates, prioritize_token_position, prioritize_num_matching_fields, enable_typos_for_numerical_tokens, exhaustive_search, search_cutoff_ms, use_cache, cache_ttl, min_len_1typo, min_len_2typo, vector_query, remote_embedding_timeout_ms, remote_embedding_num_tries, facet_strategy, stopwords, facet_return_parent, voice_query, conversation, conversation_model_id, conversation_id) Search for documents in a collection Search for documents in a collection that match the search criteria. @@ -433,11 +415,81 @@ Search for documents in a collection that match the search criteria. Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection to search for the document under | [required] | -**search_parameters** | [**SearchParameters**](.md) | | [required] | +**q** | Option<**String**> | | | +**query_by** | Option<**String**> | | | +**nl_query** | Option<**bool**> | | | +**nl_model_id** | Option<**String**> | | | +**query_by_weights** | Option<**String**> | | | +**text_match_type** | Option<**String**> | | | +**prefix** | Option<**String**> | | | +**infix** | Option<**String**> | | | +**max_extra_prefix** | Option<**i32**> | | | +**max_extra_suffix** | Option<**i32**> | | | +**filter_by** | Option<**String**> | | | +**max_filter_by_candidates** | Option<**i32**> | | | +**sort_by** | Option<**String**> | | | +**facet_by** | Option<**String**> | | | +**max_facet_values** | Option<**i32**> | | | +**facet_query** | Option<**String**> | | | +**num_typos** | Option<**String**> | | | +**page** | Option<**i32**> | | | +**per_page** | Option<**i32**> | | | +**limit** | Option<**i32**> | | | +**offset** | Option<**i32**> | | | +**group_by** | Option<**String**> | | | +**group_limit** | Option<**i32**> | | | +**group_missing_values** | Option<**bool**> | | | +**include_fields** | Option<**String**> | | | +**exclude_fields** | Option<**String**> | | | +**highlight_full_fields** | Option<**String**> | | | +**highlight_affix_num_tokens** | Option<**i32**> | | | +**highlight_start_tag** | Option<**String**> | | | +**highlight_end_tag** | Option<**String**> | | | +**enable_highlight_v1** | Option<**bool**> | | |[default to true] +**enable_analytics** | Option<**bool**> | | |[default to true] +**snippet_threshold** | Option<**i32**> | | | +**synonym_sets** | Option<**String**> | | | +**drop_tokens_threshold** | Option<**i32**> | | | +**drop_tokens_mode** | Option<[**DropTokensMode**](.md)> | | | +**typo_tokens_threshold** | Option<**i32**> | | | +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | | | +**filter_curated_hits** | Option<**bool**> | | | +**enable_synonyms** | Option<**bool**> | | | +**synonym_prefix** | Option<**bool**> | | | +**synonym_num_typos** | Option<**i32**> | | | +**pinned_hits** | Option<**String**> | | | +**hidden_hits** | Option<**String**> | | | +**override_tags** | Option<**String**> | | | +**highlight_fields** | Option<**String**> | | | +**split_join_tokens** | Option<**String**> | | | +**pre_segmented_query** | Option<**bool**> | | | +**preset** | Option<**String**> | | | +**enable_overrides** | Option<**bool**> | | |[default to false] +**prioritize_exact_match** | Option<**bool**> | | |[default to true] +**max_candidates** | Option<**i32**> | | | +**prioritize_token_position** | Option<**bool**> | | |[default to false] +**prioritize_num_matching_fields** | Option<**bool**> | | |[default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | | |[default to true] +**exhaustive_search** | Option<**bool**> | | | +**search_cutoff_ms** | Option<**i32**> | | | +**use_cache** | Option<**bool**> | | | +**cache_ttl** | Option<**i32**> | | | +**min_len_1typo** | Option<**i32**> | | | +**min_len_2typo** | Option<**i32**> | | | +**vector_query** | Option<**String**> | | | +**remote_embedding_timeout_ms** | Option<**i32**> | | | +**remote_embedding_num_tries** | Option<**i32**> | | | +**facet_strategy** | Option<**String**> | | | +**stopwords** | Option<**String**> | | | +**facet_return_parent** | Option<**String**> | | | +**voice_query** | Option<**String**> | | | +**conversation** | Option<**bool**> | | | +**conversation_model_id** | Option<**String**> | | | +**conversation_id** | Option<**String**> | | | ### Return type -[**crate::models::SearchResult**](SearchResult.md) +[**models::SearchResult**](SearchResult.md) ### Authorization @@ -453,7 +505,7 @@ Name | Type | Description | Required | Notes ## update_document -> serde_json::Value update_document(collection_name, document_id, body) +> serde_json::Value update_document(collection_name, document_id, body, dirty_values) Update a document Update an individual document from a collection by using its ID. The update can be partial. @@ -466,6 +518,7 @@ Name | Type | Description | Required | Notes **collection_name** | **String** | The name of the collection to search for the document under | [required] | **document_id** | **String** | The Document ID | [required] | **body** | **serde_json::Value** | The document object with fields to be updated | [required] | +**dirty_values** | Option<[**DirtyValues**](.md)> | Dealing with Dirty Data | | ### Return type @@ -485,7 +538,7 @@ Name | Type | Description | Required | Notes ## update_documents -> crate::models::UpdateDocuments200Response update_documents(collection_name, body, update_documents_parameters) +> models::UpdateDocuments200Response update_documents(collection_name, body, filter_by) Update documents with conditional query The filter_by query parameter is used to filter to specify a condition against which the documents are matched. The request body contains the fields that should be updated for any documents that match the filter condition. This endpoint is only available if the Typesense server is version `0.25.0.rc12` or later. @@ -497,11 +550,11 @@ Name | Type | Description | Required | Notes ------------- | ------------- | ------------- | ------------- | ------------- **collection_name** | **String** | The name of the collection to update documents in | [required] | **body** | **serde_json::Value** | The document fields to be updated | [required] | -**update_documents_parameters** | Option<[**UpdateDocumentsUpdateDocumentsParametersParameter**](.md)> | | | +**filter_by** | Option<**String**> | | | ### Return type -[**crate::models::UpdateDocuments200Response**](updateDocuments_200_response.md) +[**models::UpdateDocuments200Response**](updateDocuments_200_response.md) ### Authorization @@ -517,7 +570,7 @@ Name | Type | Description | Required | Notes ## upsert_search_override -> crate::models::SearchOverride upsert_search_override(collection_name, override_id, search_override_schema) +> models::SearchOverride upsert_search_override(collection_name, override_id, search_override_schema) Create or update an override to promote certain documents over others Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. @@ -533,39 +586,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) - -### Authorization - -[api_key_header](../README.md#api_key_header) - -### HTTP request headers - -- **Content-Type**: application/json -- **Accept**: application/json - -[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) - - -## upsert_search_synonym - -> crate::models::SearchSynonym upsert_search_synonym(collection_name, synonym_id, search_synonym_schema) -Create or update a synonym - -Create or update a synonym to define search terms that should be considered equivalent. - -### Parameters - - -Name | Type | Description | Required | Notes -------------- | ------------- | ------------- | ------------- | ------------- -**collection_name** | **String** | The name of the collection | [required] | -**synonym_id** | **String** | The ID of the search synonym to create/update | [required] | -**search_synonym_schema** | [**SearchSynonymSchema**](SearchSynonymSchema.md) | The search synonym object to be created/updated | [required] | - -### Return type - -[**crate::models::SearchSynonym**](SearchSynonym.md) +[**models::SearchOverride**](SearchOverride.md) ### Authorization diff --git a/typesense_codegen/docs/DropTokensMode.md b/typesense_codegen/docs/DropTokensMode.md new file mode 100644 index 0000000..f6da263 --- /dev/null +++ b/typesense_codegen/docs/DropTokensMode.md @@ -0,0 +1,14 @@ +# DropTokensMode + +## Enum Variants + +| Name | Value | +|---- | -----| +| RightToLeft | right_to_left | +| LeftToRight | left_to_right | +| BothSidesColon3 | both_sides:3 | + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/ExportDocumentsExportDocumentsParametersParameter.md b/typesense_codegen/docs/ExportDocumentsExportDocumentsParametersParameter.md index 14b7aaa..553431f 100644 --- a/typesense_codegen/docs/ExportDocumentsExportDocumentsParametersParameter.md +++ b/typesense_codegen/docs/ExportDocumentsExportDocumentsParametersParameter.md @@ -5,8 +5,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **filter_by** | Option<**String**> | Filter conditions for refining your search results. Separate multiple conditions with &&. | [optional] -**include_fields** | **String** | List of fields from the document to include in the search result | -**exclude_fields** | **String** | List of fields from the document to exclude in the search result | +**include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] +**exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/ExportDocumentsParameters.md b/typesense_codegen/docs/ExportDocumentsParameters.md new file mode 100644 index 0000000..25c7dc7 --- /dev/null +++ b/typesense_codegen/docs/ExportDocumentsParameters.md @@ -0,0 +1,13 @@ +# ExportDocumentsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**filter_by** | Option<**String**> | Filter conditions for refining your search results. Separate multiple conditions with &&. | [optional] +**include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] +**exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/FacetCounts.md b/typesense_codegen/docs/FacetCounts.md index e850701..4b170c1 100644 --- a/typesense_codegen/docs/FacetCounts.md +++ b/typesense_codegen/docs/FacetCounts.md @@ -4,9 +4,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**counts** | Option<[**Vec**](FacetCounts_counts_inner.md)> | | [optional] +**counts** | Option<[**Vec**](FacetCounts_counts_inner.md)> | | [optional] **field_name** | Option<**String**> | | [optional] -**stats** | Option<[**crate::models::FacetCountsStats**](FacetCounts_stats.md)> | | [optional] +**stats** | Option<[**models::FacetCountsStats**](FacetCounts_stats.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/FacetCountsCountsInner.md b/typesense_codegen/docs/FacetCountsCountsInner.md index 23befac..3733448 100644 --- a/typesense_codegen/docs/FacetCountsCountsInner.md +++ b/typesense_codegen/docs/FacetCountsCountsInner.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **count** | Option<**i32**> | | [optional] **highlighted** | Option<**String**> | | [optional] **value** | Option<**String**> | | [optional] +**parent** | Option<[**serde_json::Value**](.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/Field.md b/typesense_codegen/docs/Field.md index dbf6a9e..17afabd 100644 --- a/typesense_codegen/docs/Field.md +++ b/typesense_codegen/docs/Field.md @@ -12,9 +12,17 @@ Name | Type | Description | Notes **locale** | Option<**String**> | | [optional] **sort** | Option<**bool**> | | [optional] **infix** | Option<**bool**> | | [optional][default to false] +**reference** | Option<**String**> | Name of a field in another collection that should be linked to this collection so that it can be joined during query. | [optional] **num_dim** | Option<**i32**> | | [optional] **drop** | Option<**bool**> | | [optional] -**embed** | Option<[**crate::models::FieldEmbed**](Field_embed.md)> | | [optional] +**store** | Option<**bool**> | When set to false, the field value will not be stored on disk. Default: true. | [optional] +**vec_dist** | Option<**String**> | The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. | [optional] +**range_index** | Option<**bool**> | Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. | [optional] +**stem** | Option<**bool**> | Values are stemmed before indexing in-memory. Default: false. | [optional] +**stem_dictionary** | Option<**String**> | Name of the stemming dictionary to use for this field | [optional] +**token_separators** | Option<**Vec**> | List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. | [optional][default to []] +**symbols_to_index** | Option<**Vec**> | List of symbols or special characters to be indexed. | [optional][default to []] +**embed** | Option<[**models::FieldEmbed**](Field_embed.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/FieldEmbed.md b/typesense_codegen/docs/FieldEmbed.md index b1dc03b..dca3983 100644 --- a/typesense_codegen/docs/FieldEmbed.md +++ b/typesense_codegen/docs/FieldEmbed.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **from** | **Vec** | | -**model_config** | [**crate::models::FieldEmbedModelConfig**](Field_embed_model_config.md) | | +**model_config** | [**models::FieldEmbedModelConfig**](Field_embed_model_config.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/FieldEmbedModelConfig.md b/typesense_codegen/docs/FieldEmbedModelConfig.md index 88c03af..8ee1235 100644 --- a/typesense_codegen/docs/FieldEmbedModelConfig.md +++ b/typesense_codegen/docs/FieldEmbedModelConfig.md @@ -6,10 +6,14 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **model_name** | **String** | | **api_key** | Option<**String**> | | [optional] +**url** | Option<**String**> | | [optional] **access_token** | Option<**String**> | | [optional] +**refresh_token** | Option<**String**> | | [optional] **client_id** | Option<**String**> | | [optional] **client_secret** | Option<**String**> | | [optional] **project_id** | Option<**String**> | | [optional] +**indexing_prefix** | Option<**String**> | | [optional] +**query_prefix** | Option<**String**> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/GetCollectionsGetCollectionsParametersParameter.md b/typesense_codegen/docs/GetCollectionsGetCollectionsParametersParameter.md new file mode 100644 index 0000000..f4fef66 --- /dev/null +++ b/typesense_codegen/docs/GetCollectionsGetCollectionsParametersParameter.md @@ -0,0 +1,13 @@ +# GetCollectionsGetCollectionsParametersParameter + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exclude_fields** | Option<**String**> | Comma-separated list of fields from the collection to exclude from the response | [optional] +**limit** | Option<**i32**> | Number of collections to fetch. Default: returns all collections. | [optional] +**offset** | Option<**i32**> | Identifies the starting point to return collections when paginating. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/GetCollectionsParameters.md b/typesense_codegen/docs/GetCollectionsParameters.md new file mode 100644 index 0000000..d1f2a68 --- /dev/null +++ b/typesense_codegen/docs/GetCollectionsParameters.md @@ -0,0 +1,13 @@ +# GetCollectionsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**exclude_fields** | Option<**String**> | Comma-separated list of fields from the collection to exclude from the response | [optional] +**limit** | Option<**i32**> | Number of collections to fetch. Default: returns all collections. | [optional] +**offset** | Option<**i32**> | Identifies the starting point to return collections when paginating. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/HealthApi.md b/typesense_codegen/docs/HealthApi.md index 8c4d523..cdc7c9f 100644 --- a/typesense_codegen/docs/HealthApi.md +++ b/typesense_codegen/docs/HealthApi.md @@ -1,6 +1,6 @@ # \HealthApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -10,7 +10,7 @@ Method | HTTP request | Description ## health -> crate::models::HealthStatus health() +> models::HealthStatus health() Checks if Typesense server is ready to accept requests. Checks if Typesense server is ready to accept requests. @@ -21,7 +21,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::HealthStatus**](HealthStatus.md) +[**models::HealthStatus**](HealthStatus.md) ### Authorization diff --git a/typesense_codegen/docs/ImportDocumentsImportDocumentsParametersParameter.md b/typesense_codegen/docs/ImportDocumentsImportDocumentsParametersParameter.md index aea6558..185baaa 100644 --- a/typesense_codegen/docs/ImportDocumentsImportDocumentsParametersParameter.md +++ b/typesense_codegen/docs/ImportDocumentsImportDocumentsParametersParameter.md @@ -4,10 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**action** | Option<**String**> | | [optional] **batch_size** | Option<**i32**> | | [optional] -**dirty_values** | Option<**String**> | | [optional] +**return_id** | Option<**bool**> | Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. | [optional] **remote_embedding_batch_size** | Option<**i32**> | | [optional] +**return_doc** | Option<**bool**> | | [optional] +**action** | Option<[**models::IndexAction**](IndexAction.md)> | | [optional] +**dirty_values** | Option<[**models::DirtyValues**](DirtyValues.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/ImportDocumentsParameters.md b/typesense_codegen/docs/ImportDocumentsParameters.md new file mode 100644 index 0000000..67099eb --- /dev/null +++ b/typesense_codegen/docs/ImportDocumentsParameters.md @@ -0,0 +1,16 @@ +# ImportDocumentsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**batch_size** | Option<**i32**> | | [optional] +**return_id** | Option<**bool**> | Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. | [optional] +**remote_embedding_batch_size** | Option<**i32**> | | [optional] +**return_doc** | Option<**bool**> | | [optional] +**action** | Option<[**models::IndexAction**](IndexAction.md)> | | [optional] +**dirty_values** | Option<[**models::DirtyValues**](DirtyValues.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/IndexAction.md b/typesense_codegen/docs/IndexAction.md new file mode 100644 index 0000000..7c450eb --- /dev/null +++ b/typesense_codegen/docs/IndexAction.md @@ -0,0 +1,15 @@ +# IndexAction + +## Enum Variants + +| Name | Value | +|---- | -----| +| Create | create | +| Update | update | +| Upsert | upsert | +| Emplace | emplace | + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/KeysApi.md b/typesense_codegen/docs/KeysApi.md index 422c127..dd5f01d 100644 --- a/typesense_codegen/docs/KeysApi.md +++ b/typesense_codegen/docs/KeysApi.md @@ -1,6 +1,6 @@ # \KeysApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -13,7 +13,7 @@ Method | HTTP request | Description ## create_key -> crate::models::ApiKey create_key(api_key_schema) +> models::ApiKey create_key(api_key_schema) Create an API Key Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. @@ -27,7 +27,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::ApiKey**](ApiKey.md) +[**models::ApiKey**](ApiKey.md) ### Authorization @@ -43,7 +43,7 @@ Name | Type | Description | Required | Notes ## delete_key -> crate::models::ApiKey delete_key(key_id) +> models::ApiKeyDeleteResponse delete_key(key_id) Delete an API key given its ID. ### Parameters @@ -55,7 +55,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::ApiKey**](ApiKey.md) +[**models::ApiKeyDeleteResponse**](ApiKeyDeleteResponse.md) ### Authorization @@ -71,7 +71,7 @@ Name | Type | Description | Required | Notes ## get_key -> crate::models::ApiKey get_key(key_id) +> models::ApiKey get_key(key_id) Retrieve (metadata about) a key Retrieve (metadata about) a key. Only the key prefix is returned when you retrieve a key. Due to security reasons, only the create endpoint returns the full API key. @@ -85,7 +85,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::ApiKey**](ApiKey.md) +[**models::ApiKey**](ApiKey.md) ### Authorization @@ -101,7 +101,7 @@ Name | Type | Description | Required | Notes ## get_keys -> crate::models::ApiKeysResponse get_keys() +> models::ApiKeysResponse get_keys() Retrieve (metadata about) all keys. ### Parameters @@ -110,7 +110,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::ApiKeysResponse**](ApiKeysResponse.md) +[**models::ApiKeysResponse**](ApiKeysResponse.md) ### Authorization diff --git a/typesense_codegen/docs/ListStemmingDictionaries200Response.md b/typesense_codegen/docs/ListStemmingDictionaries200Response.md new file mode 100644 index 0000000..d56a82d --- /dev/null +++ b/typesense_codegen/docs/ListStemmingDictionaries200Response.md @@ -0,0 +1,11 @@ +# ListStemmingDictionaries200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**dictionaries** | Option<**Vec**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/MultiSearchCollectionParameters.md b/typesense_codegen/docs/MultiSearchCollectionParameters.md index 07be3ee..b2bbf1f 100644 --- a/typesense_codegen/docs/MultiSearchCollectionParameters.md +++ b/typesense_codegen/docs/MultiSearchCollectionParameters.md @@ -20,10 +20,11 @@ Name | Type | Description | Notes **num_typos** | Option<**String**> | The number of typographical errors (1 or 2) that would be tolerated. Default: 2 | [optional] **page** | Option<**i32**> | Results from this specific page number would be fetched. | [optional] **per_page** | Option<**i32**> | Number of results to fetch per page. Default: 10 | [optional] -**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] +**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] **offset** | Option<**i32**> | Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. | [optional] **group_by** | Option<**String**> | You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. | [optional] **group_limit** | Option<**i32**> | Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 | [optional] +**group_missing_values** | Option<**bool**> | Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true | [optional] **include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] **exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] **highlight_full_fields** | Option<**String**> | List of fields which should be highlighted fully without snippeting | [optional] @@ -32,24 +33,44 @@ Name | Type | Description | Notes **highlight_end_tag** | Option<**String**> | The end tag used for the highlighted snippets. Default: `` | [optional] **snippet_threshold** | Option<**i32**> | Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 | [optional] **drop_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 | [optional] +**drop_tokens_mode** | Option<[**models::DropTokensMode**](DropTokensMode.md)> | | [optional] **typo_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 | [optional] -**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. | [optional] +**filter_curated_hits** | Option<**bool**> | Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false | [optional] +**enable_synonyms** | Option<**bool**> | If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true | [optional] +**enable_analytics** | Option<**bool**> | Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). | [optional][default to true] +**synonym_prefix** | Option<**bool**> | Allow synonym resolution on word prefixes in the query. Default: false | [optional] +**synonym_num_typos** | Option<**i32**> | Allow synonym resolution on typo-corrected words in the query. Default: 0 | [optional] +**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] **hidden_hits** | Option<**String**> | A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] -**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] -**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional] +**override_tags** | Option<**String**> | Comma separated list of tags to trigger the curations rules that match the tags. | [optional] +**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] +**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional][default to false] **preset** | Option<**String**> | Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. | [optional] -**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional] -**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional] -**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] -**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] +**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional][default to false] +**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional][default to true] +**prioritize_token_position** | Option<**bool**> | Make Typesense prioritize documents where the query words appear earlier in the text. | [optional][default to false] +**prioritize_num_matching_fields** | Option<**bool**> | Make Typesense prioritize documents where the query words appear in more number of fields. | [optional][default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | Make Typesense disable typos for numerical tokens. | [optional][default to true] +**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] +**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] **use_cache** | Option<**bool**> | Enable server side caching of search query results. By default, caching is disabled. | [optional] -**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] -**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] -**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] +**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] **vector_query** | Option<**String**> | Vector query expression for fetching documents \"closest\" to a given query/document vector. | [optional] **remote_embedding_timeout_ms** | Option<**i32**> | Timeout (in milliseconds) for fetching remote embeddings. | [optional] **remote_embedding_num_tries** | Option<**i32**> | Number of times to retry fetching remote embeddings. | [optional] -**collection** | **String** | The collection to search in. | +**facet_strategy** | Option<**String**> | Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). | [optional] +**stopwords** | Option<**String**> | Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. | [optional] +**facet_return_parent** | Option<**String**> | Comma separated string of nested facet fields whose parent object should be returned in facet response. | [optional] +**voice_query** | Option<**String**> | The base64 encoded audio file in 16 khz 16-bit WAV format. | [optional] +**conversation** | Option<**bool**> | Enable conversational search. | [optional] +**conversation_model_id** | Option<**String**> | The Id of Conversation Model to be used. | [optional] +**conversation_id** | Option<**String**> | The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. | [optional] +**collection** | Option<**String**> | The collection to search in. | [optional] +**x_typesense_api_key** | Option<**String**> | A separate search API key for each search within a multi_search request | [optional] +**rerank_hybrid_matches** | Option<**bool**> | When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. | [optional][default to false] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/MultiSearchParameters.md b/typesense_codegen/docs/MultiSearchParameters.md index 20a33a7..5041bca 100644 --- a/typesense_codegen/docs/MultiSearchParameters.md +++ b/typesense_codegen/docs/MultiSearchParameters.md @@ -20,10 +20,11 @@ Name | Type | Description | Notes **num_typos** | Option<**String**> | The number of typographical errors (1 or 2) that would be tolerated. Default: 2 | [optional] **page** | Option<**i32**> | Results from this specific page number would be fetched. | [optional] **per_page** | Option<**i32**> | Number of results to fetch per page. Default: 10 | [optional] -**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] +**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] **offset** | Option<**i32**> | Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. | [optional] **group_by** | Option<**String**> | You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. | [optional] **group_limit** | Option<**i32**> | Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 | [optional] +**group_missing_values** | Option<**bool**> | Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true | [optional] **include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] **exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] **highlight_full_fields** | Option<**String**> | List of fields which should be highlighted fully without snippeting | [optional] @@ -32,23 +33,41 @@ Name | Type | Description | Notes **highlight_end_tag** | Option<**String**> | The end tag used for the highlighted snippets. Default: `` | [optional] **snippet_threshold** | Option<**i32**> | Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 | [optional] **drop_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 | [optional] +**drop_tokens_mode** | Option<[**models::DropTokensMode**](DropTokensMode.md)> | | [optional] **typo_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 | [optional] -**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. | [optional] +**filter_curated_hits** | Option<**bool**> | Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false | [optional] +**enable_synonyms** | Option<**bool**> | If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true | [optional] +**enable_analytics** | Option<**bool**> | Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). | [optional][default to true] +**synonym_prefix** | Option<**bool**> | Allow synonym resolution on word prefixes in the query. Default: false | [optional] +**synonym_num_typos** | Option<**i32**> | Allow synonym resolution on typo-corrected words in the query. Default: 0 | [optional] +**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] **hidden_hits** | Option<**String**> | A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] -**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] -**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional] +**override_tags** | Option<**String**> | Comma separated list of tags to trigger the curations rules that match the tags. | [optional] +**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] +**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional][default to false] **preset** | Option<**String**> | Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. | [optional] -**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional] -**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional] -**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] -**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] +**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional][default to false] +**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional][default to true] +**prioritize_token_position** | Option<**bool**> | Make Typesense prioritize documents where the query words appear earlier in the text. | [optional][default to false] +**prioritize_num_matching_fields** | Option<**bool**> | Make Typesense prioritize documents where the query words appear in more number of fields. | [optional][default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | Make Typesense disable typos for numerical tokens. | [optional][default to true] +**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] +**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] **use_cache** | Option<**bool**> | Enable server side caching of search query results. By default, caching is disabled. | [optional] -**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] -**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] -**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] +**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] **vector_query** | Option<**String**> | Vector query expression for fetching documents \"closest\" to a given query/document vector. | [optional] **remote_embedding_timeout_ms** | Option<**i32**> | Timeout (in milliseconds) for fetching remote embeddings. | [optional] **remote_embedding_num_tries** | Option<**i32**> | Number of times to retry fetching remote embeddings. | [optional] +**facet_strategy** | Option<**String**> | Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). | [optional] +**stopwords** | Option<**String**> | Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. | [optional] +**facet_return_parent** | Option<**String**> | Comma separated string of nested facet fields whose parent object should be returned in facet response. | [optional] +**voice_query** | Option<**String**> | The base64 encoded audio file in 16 khz 16-bit WAV format. | [optional] +**conversation** | Option<**bool**> | Enable conversational search. | [optional] +**conversation_model_id** | Option<**String**> | The Id of Conversation Model to be used. | [optional] +**conversation_id** | Option<**String**> | The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/MultiSearchResult.md b/typesense_codegen/docs/MultiSearchResult.md index d9f399c..55bad9d 100644 --- a/typesense_codegen/docs/MultiSearchResult.md +++ b/typesense_codegen/docs/MultiSearchResult.md @@ -4,7 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**results** | [**Vec**](SearchResult.md) | | +**results** | [**Vec**](MultiSearchResultItem.md) | | +**conversation** | Option<[**models::SearchResultConversation**](SearchResultConversation.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/MultiSearchResultItem.md b/typesense_codegen/docs/MultiSearchResultItem.md new file mode 100644 index 0000000..0f306be --- /dev/null +++ b/typesense_codegen/docs/MultiSearchResultItem.md @@ -0,0 +1,24 @@ +# MultiSearchResultItem + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**facet_counts** | Option<[**Vec**](FacetCounts.md)> | | [optional] +**found** | Option<**i32**> | The number of documents found | [optional] +**found_docs** | Option<**i32**> | | [optional] +**search_time_ms** | Option<**i32**> | The number of milliseconds the search took | [optional] +**out_of** | Option<**i32**> | The total number of documents in the collection | [optional] +**search_cutoff** | Option<**bool**> | Whether the search was cut off | [optional] +**page** | Option<**i32**> | The search result page number | [optional] +**grouped_hits** | Option<[**Vec**](SearchGroupedHit.md)> | | [optional] +**hits** | Option<[**Vec**](SearchResultHit.md)> | The documents that matched the search query | [optional] +**request_params** | Option<[**models::SearchRequestParams**](SearchRequestParams.md)> | | [optional] +**conversation** | Option<[**models::SearchResultConversation**](SearchResultConversation.md)> | | [optional] +**union_request_params** | Option<[**Vec**](SearchRequestParams.md)> | Returned only for union query response. | [optional] +**code** | Option<**i64**> | HTTP error code | [optional] +**error** | Option<**String**> | Error description | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/MultiSearchSearchesParameter.md b/typesense_codegen/docs/MultiSearchSearchesParameter.md index aee8e7f..5bfd345 100644 --- a/typesense_codegen/docs/MultiSearchSearchesParameter.md +++ b/typesense_codegen/docs/MultiSearchSearchesParameter.md @@ -4,7 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**searches** | [**Vec**](MultiSearchCollectionParameters.md) | | +**union** | Option<**bool**> | When true, merges the search results from each search query into a single ordered set of hits. | [optional][default to false] +**searches** | [**Vec**](MultiSearchCollectionParameters.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/NlSearchModelBase.md b/typesense_codegen/docs/NlSearchModelBase.md new file mode 100644 index 0000000..b331895 --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelBase.md @@ -0,0 +1,28 @@ +# NlSearchModelBase + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**model_name** | Option<**String**> | Name of the NL model to use | [optional] +**api_key** | Option<**String**> | API key for the NL model service | [optional] +**api_url** | Option<**String**> | Custom API URL for the NL model service | [optional] +**max_bytes** | Option<**i32**> | Maximum number of bytes to process | [optional] +**temperature** | Option<**f64**> | Temperature parameter for the NL model | [optional] +**system_prompt** | Option<**String**> | System prompt for the NL model | [optional] +**top_p** | Option<**f64**> | Top-p parameter for the NL model (Google-specific) | [optional] +**top_k** | Option<**i32**> | Top-k parameter for the NL model (Google-specific) | [optional] +**stop_sequences** | Option<**Vec**> | Stop sequences for the NL model (Google-specific) | [optional] +**api_version** | Option<**String**> | API version for the NL model service | [optional] +**project_id** | Option<**String**> | Project ID for GCP Vertex AI | [optional] +**access_token** | Option<**String**> | Access token for GCP Vertex AI | [optional] +**refresh_token** | Option<**String**> | Refresh token for GCP Vertex AI | [optional] +**client_id** | Option<**String**> | Client ID for GCP Vertex AI | [optional] +**client_secret** | Option<**String**> | Client secret for GCP Vertex AI | [optional] +**region** | Option<**String**> | Region for GCP Vertex AI | [optional] +**max_output_tokens** | Option<**i32**> | Maximum output tokens for GCP Vertex AI | [optional] +**account_id** | Option<**String**> | Account ID for Cloudflare-specific models | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/NlSearchModelCreateSchema.md b/typesense_codegen/docs/NlSearchModelCreateSchema.md new file mode 100644 index 0000000..6690186 --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelCreateSchema.md @@ -0,0 +1,29 @@ +# NlSearchModelCreateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**model_name** | Option<**String**> | Name of the NL model to use | [optional] +**api_key** | Option<**String**> | API key for the NL model service | [optional] +**api_url** | Option<**String**> | Custom API URL for the NL model service | [optional] +**max_bytes** | Option<**i32**> | Maximum number of bytes to process | [optional] +**temperature** | Option<**f64**> | Temperature parameter for the NL model | [optional] +**system_prompt** | Option<**String**> | System prompt for the NL model | [optional] +**top_p** | Option<**f64**> | Top-p parameter for the NL model (Google-specific) | [optional] +**top_k** | Option<**i32**> | Top-k parameter for the NL model (Google-specific) | [optional] +**stop_sequences** | Option<**Vec**> | Stop sequences for the NL model (Google-specific) | [optional] +**api_version** | Option<**String**> | API version for the NL model service | [optional] +**project_id** | Option<**String**> | Project ID for GCP Vertex AI | [optional] +**access_token** | Option<**String**> | Access token for GCP Vertex AI | [optional] +**refresh_token** | Option<**String**> | Refresh token for GCP Vertex AI | [optional] +**client_id** | Option<**String**> | Client ID for GCP Vertex AI | [optional] +**client_secret** | Option<**String**> | Client secret for GCP Vertex AI | [optional] +**region** | Option<**String**> | Region for GCP Vertex AI | [optional] +**max_output_tokens** | Option<**i32**> | Maximum output tokens for GCP Vertex AI | [optional] +**account_id** | Option<**String**> | Account ID for Cloudflare-specific models | [optional] +**id** | Option<**String**> | Optional ID for the NL search model | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/NlSearchModelDeleteSchema.md b/typesense_codegen/docs/NlSearchModelDeleteSchema.md new file mode 100644 index 0000000..97be1ac --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelDeleteSchema.md @@ -0,0 +1,11 @@ +# NlSearchModelDeleteSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | ID of the deleted NL search model | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/NlSearchModelSchema.md b/typesense_codegen/docs/NlSearchModelSchema.md new file mode 100644 index 0000000..24f870f --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelSchema.md @@ -0,0 +1,29 @@ +# NlSearchModelSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**model_name** | Option<**String**> | Name of the NL model to use | [optional] +**api_key** | Option<**String**> | API key for the NL model service | [optional] +**api_url** | Option<**String**> | Custom API URL for the NL model service | [optional] +**max_bytes** | Option<**i32**> | Maximum number of bytes to process | [optional] +**temperature** | Option<**f64**> | Temperature parameter for the NL model | [optional] +**system_prompt** | Option<**String**> | System prompt for the NL model | [optional] +**top_p** | Option<**f64**> | Top-p parameter for the NL model (Google-specific) | [optional] +**top_k** | Option<**i32**> | Top-k parameter for the NL model (Google-specific) | [optional] +**stop_sequences** | Option<**Vec**> | Stop sequences for the NL model (Google-specific) | [optional] +**api_version** | Option<**String**> | API version for the NL model service | [optional] +**project_id** | Option<**String**> | Project ID for GCP Vertex AI | [optional] +**access_token** | Option<**String**> | Access token for GCP Vertex AI | [optional] +**refresh_token** | Option<**String**> | Refresh token for GCP Vertex AI | [optional] +**client_id** | Option<**String**> | Client ID for GCP Vertex AI | [optional] +**client_secret** | Option<**String**> | Client secret for GCP Vertex AI | [optional] +**region** | Option<**String**> | Region for GCP Vertex AI | [optional] +**max_output_tokens** | Option<**i32**> | Maximum output tokens for GCP Vertex AI | [optional] +**account_id** | Option<**String**> | Account ID for Cloudflare-specific models | [optional] +**id** | **String** | ID of the NL search model | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/NlSearchModelsApi.md b/typesense_codegen/docs/NlSearchModelsApi.md new file mode 100644 index 0000000..07d5448 --- /dev/null +++ b/typesense_codegen/docs/NlSearchModelsApi.md @@ -0,0 +1,161 @@ +# \NlSearchModelsApi + +All URIs are relative to *http://localhost:8108* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**create_nl_search_model**](NlSearchModelsApi.md#create_nl_search_model) | **POST** /nl_search_models | Create a NL search model +[**delete_nl_search_model**](NlSearchModelsApi.md#delete_nl_search_model) | **DELETE** /nl_search_models/{modelId} | Delete a NL search model +[**retrieve_all_nl_search_models**](NlSearchModelsApi.md#retrieve_all_nl_search_models) | **GET** /nl_search_models | List all NL search models +[**retrieve_nl_search_model**](NlSearchModelsApi.md#retrieve_nl_search_model) | **GET** /nl_search_models/{modelId} | Retrieve a NL search model +[**update_nl_search_model**](NlSearchModelsApi.md#update_nl_search_model) | **PUT** /nl_search_models/{modelId} | Update a NL search model + + + +## create_nl_search_model + +> models::NlSearchModelSchema create_nl_search_model(nl_search_model_create_schema) +Create a NL search model + +Create a new NL search model. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**nl_search_model_create_schema** | [**NlSearchModelCreateSchema**](NlSearchModelCreateSchema.md) | The NL search model to be created | [required] | + +### Return type + +[**models::NlSearchModelSchema**](NLSearchModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## delete_nl_search_model + +> models::NlSearchModelDeleteSchema delete_nl_search_model(model_id) +Delete a NL search model + +Delete a specific NL search model by its ID. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The ID of the NL search model to delete | [required] | + +### Return type + +[**models::NlSearchModelDeleteSchema**](NLSearchModelDeleteSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_all_nl_search_models + +> Vec retrieve_all_nl_search_models() +List all NL search models + +Retrieve all NL search models. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**Vec**](NLSearchModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_nl_search_model + +> models::NlSearchModelSchema retrieve_nl_search_model(model_id) +Retrieve a NL search model + +Retrieve a specific NL search model by its ID. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The ID of the NL search model to retrieve | [required] | + +### Return type + +[**models::NlSearchModelSchema**](NLSearchModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## update_nl_search_model + +> models::NlSearchModelSchema update_nl_search_model(model_id, body) +Update a NL search model + +Update an existing NL search model. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**model_id** | **String** | The ID of the NL search model to update | [required] | +**body** | **models::NlSearchModelCreateSchema** | The NL search model fields to update | [required] | + +### Return type + +[**models::NlSearchModelSchema**](NLSearchModelSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/OperationsApi.md b/typesense_codegen/docs/OperationsApi.md index 9a499de..86a6e6d 100644 --- a/typesense_codegen/docs/OperationsApi.md +++ b/typesense_codegen/docs/OperationsApi.md @@ -1,17 +1,158 @@ # \OperationsApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- +[**clear_cache**](OperationsApi.md#clear_cache) | **POST** /operations/cache/clear | Clear the cached responses of search requests in the LRU cache. +[**compact_db**](OperationsApi.md#compact_db) | **POST** /operations/db/compact | Compacting the on-disk database +[**get_schema_changes**](OperationsApi.md#get_schema_changes) | **GET** /operations/schema_changes | Get the status of in-progress schema change operations +[**retrieve_api_stats**](OperationsApi.md#retrieve_api_stats) | **GET** /stats.json | Get stats about API endpoints. +[**retrieve_metrics**](OperationsApi.md#retrieve_metrics) | **GET** /metrics.json | Get current RAM, CPU, Disk & Network usage metrics. [**take_snapshot**](OperationsApi.md#take_snapshot) | **POST** /operations/snapshot | Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. +[**toggle_slow_request_log**](OperationsApi.md#toggle_slow_request_log) | **POST** /config | Toggle Slow Request Log [**vote**](OperationsApi.md#vote) | **POST** /operations/vote | Triggers a follower node to initiate the raft voting process, which triggers leader re-election. +## clear_cache + +> models::SuccessStatus clear_cache() +Clear the cached responses of search requests in the LRU cache. + +Clear the cached responses of search requests that are sent with `use_cache` parameter in the LRU cache. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::SuccessStatus**](SuccessStatus.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## compact_db + +> models::SuccessStatus compact_db() +Compacting the on-disk database + +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. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::SuccessStatus**](SuccessStatus.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## get_schema_changes + +> Vec get_schema_changes() +Get the status of in-progress schema change operations + +Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**Vec**](SchemaChangeStatus.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_api_stats + +> models::ApiStatsResponse retrieve_api_stats() +Get stats about API endpoints. + +Retrieve the stats about API endpoints. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::ApiStatsResponse**](APIStatsResponse.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_metrics + +> serde_json::Value retrieve_metrics() +Get current RAM, CPU, Disk & Network usage metrics. + +Retrieve the metrics. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**serde_json::Value**](serde_json::Value.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + ## take_snapshot -> crate::models::SuccessStatus take_snapshot(snapshot_path) +> models::SuccessStatus take_snapshot(snapshot_path) Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. @@ -25,7 +166,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SuccessStatus**](SuccessStatus.md) +[**models::SuccessStatus**](SuccessStatus.md) ### Authorization @@ -39,9 +180,39 @@ Name | Type | Description | Required | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +## toggle_slow_request_log + +> models::SuccessStatus toggle_slow_request_log(toggle_slow_request_log_request) +Toggle Slow Request Log + +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. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**toggle_slow_request_log_request** | Option<[**ToggleSlowRequestLogRequest**](ToggleSlowRequestLogRequest.md)> | | | + +### Return type + +[**models::SuccessStatus**](SuccessStatus.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + ## vote -> crate::models::SuccessStatus vote() +> models::SuccessStatus vote() Triggers a follower node to initiate the raft voting process, which triggers leader re-election. Triggers a follower node to initiate the raft voting process, which triggers leader re-election. The follower node that you run this operation against will become the new leader, once this command succeeds. @@ -52,7 +223,7 @@ This endpoint does not need any parameter. ### Return type -[**crate::models::SuccessStatus**](SuccessStatus.md) +[**models::SuccessStatus**](SuccessStatus.md) ### Authorization diff --git a/typesense_codegen/docs/OverrideApi.md b/typesense_codegen/docs/OverrideApi.md index 02f1ca5..85e9cf3 100644 --- a/typesense_codegen/docs/OverrideApi.md +++ b/typesense_codegen/docs/OverrideApi.md @@ -1,6 +1,6 @@ # \OverrideApi -All URIs are relative to *http://localhost* +All URIs are relative to *http://localhost:8108* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -10,7 +10,7 @@ Method | HTTP request | Description ## get_search_override -> crate::models::SearchOverride get_search_override(collection_name, override_id) +> models::SearchOverride get_search_override(collection_name, override_id) Retrieve a single search override Retrieve the details of a search override, given its id. @@ -25,7 +25,7 @@ Name | Type | Description | Required | Notes ### Return type -[**crate::models::SearchOverride**](SearchOverride.md) +[**models::SearchOverride**](SearchOverride.md) ### Authorization diff --git a/typesense_codegen/docs/PresetDeleteSchema.md b/typesense_codegen/docs/PresetDeleteSchema.md new file mode 100644 index 0000000..36bbacf --- /dev/null +++ b/typesense_codegen/docs/PresetDeleteSchema.md @@ -0,0 +1,11 @@ +# PresetDeleteSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PresetSchema.md b/typesense_codegen/docs/PresetSchema.md new file mode 100644 index 0000000..e1457b9 --- /dev/null +++ b/typesense_codegen/docs/PresetSchema.md @@ -0,0 +1,12 @@ +# PresetSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**value** | [**models::PresetUpsertSchemaValue**](PresetUpsertSchema_value.md) | | +**name** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PresetUpsertSchema.md b/typesense_codegen/docs/PresetUpsertSchema.md new file mode 100644 index 0000000..ac9f9cd --- /dev/null +++ b/typesense_codegen/docs/PresetUpsertSchema.md @@ -0,0 +1,11 @@ +# PresetUpsertSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**value** | [**models::PresetUpsertSchemaValue**](PresetUpsertSchema_value.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PresetUpsertSchemaValue.md b/typesense_codegen/docs/PresetUpsertSchemaValue.md new file mode 100644 index 0000000..073a07c --- /dev/null +++ b/typesense_codegen/docs/PresetUpsertSchemaValue.md @@ -0,0 +1,12 @@ +# PresetUpsertSchemaValue + +## Enum Variants + +| Name | Description | +|---- | -----| +| MultiSearchSearchesParameter | | +| SearchParameters | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/PresetsApi.md b/typesense_codegen/docs/PresetsApi.md new file mode 100644 index 0000000..4a22b05 --- /dev/null +++ b/typesense_codegen/docs/PresetsApi.md @@ -0,0 +1,130 @@ +# \PresetsApi + +All URIs are relative to *http://localhost:8108* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_preset**](PresetsApi.md#delete_preset) | **DELETE** /presets/{presetId} | Delete a preset. +[**retrieve_all_presets**](PresetsApi.md#retrieve_all_presets) | **GET** /presets | Retrieves all presets. +[**retrieve_preset**](PresetsApi.md#retrieve_preset) | **GET** /presets/{presetId} | Retrieves a preset. +[**upsert_preset**](PresetsApi.md#upsert_preset) | **PUT** /presets/{presetId} | Upserts a preset. + + + +## delete_preset + +> models::PresetDeleteSchema delete_preset(preset_id) +Delete a preset. + +Permanently deletes a preset, given it's name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**preset_id** | **String** | The ID of the preset to delete. | [required] | + +### Return type + +[**models::PresetDeleteSchema**](PresetDeleteSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_all_presets + +> models::PresetsRetrieveSchema retrieve_all_presets() +Retrieves all presets. + +Retrieve the details of all presets + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::PresetsRetrieveSchema**](PresetsRetrieveSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_preset + +> models::PresetSchema retrieve_preset(preset_id) +Retrieves a preset. + +Retrieve the details of a preset, given it's name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**preset_id** | **String** | The ID of the preset to retrieve. | [required] | + +### Return type + +[**models::PresetSchema**](PresetSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## upsert_preset + +> models::PresetSchema upsert_preset(preset_id, preset_upsert_schema) +Upserts a preset. + +Create or update an existing preset. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**preset_id** | **String** | The name of the preset set to upsert. | [required] | +**preset_upsert_schema** | [**PresetUpsertSchema**](PresetUpsertSchema.md) | The stopwords set to upsert. | [required] | + +### Return type + +[**models::PresetSchema**](PresetSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/PresetsRetrieveSchema.md b/typesense_codegen/docs/PresetsRetrieveSchema.md new file mode 100644 index 0000000..6c2ace3 --- /dev/null +++ b/typesense_codegen/docs/PresetsRetrieveSchema.md @@ -0,0 +1,11 @@ +# PresetsRetrieveSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**presets** | [**Vec**](PresetSchema.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SchemaChangeStatus.md b/typesense_codegen/docs/SchemaChangeStatus.md new file mode 100644 index 0000000..5a87798 --- /dev/null +++ b/typesense_codegen/docs/SchemaChangeStatus.md @@ -0,0 +1,13 @@ +# SchemaChangeStatus + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**collection** | Option<**String**> | Name of the collection being modified | [optional] +**validated_docs** | Option<**i32**> | Number of documents that have been validated | [optional] +**altered_docs** | Option<**i32**> | Number of documents that have been altered | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchGroupedHit.md b/typesense_codegen/docs/SearchGroupedHit.md index 996a423..1972f65 100644 --- a/typesense_codegen/docs/SearchGroupedHit.md +++ b/typesense_codegen/docs/SearchGroupedHit.md @@ -6,7 +6,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **found** | Option<**i32**> | | [optional] **group_key** | [**Vec**](serde_json::Value.md) | | -**hits** | [**Vec**](SearchResultHit.md) | The documents that matched the search query | +**hits** | [**Vec**](SearchResultHit.md) | The documents that matched the search query | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchOverride.md b/typesense_codegen/docs/SearchOverride.md index 0c0cbfc..1204992 100644 --- a/typesense_codegen/docs/SearchOverride.md +++ b/typesense_codegen/docs/SearchOverride.md @@ -4,11 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**rule** | [**crate::models::SearchOverrideRule**](SearchOverrideRule.md) | | -**includes** | Option<[**Vec**](SearchOverrideInclude.md)> | List of document `id`s that should be included in the search results with their corresponding `position`s. | [optional] -**excludes** | Option<[**Vec**](SearchOverrideExclude.md)> | List of document `id`s that should be excluded from the search results. | [optional] +**rule** | [**models::SearchOverrideRule**](SearchOverrideRule.md) | | +**includes** | Option<[**Vec**](SearchOverrideInclude.md)> | List of document `id`s that should be included in the search results with their corresponding `position`s. | [optional] +**excludes** | Option<[**Vec**](SearchOverrideExclude.md)> | List of document `id`s that should be excluded from the search results. | [optional] **filter_by** | Option<**String**> | A filter by clause that is applied to any search query that matches the override rule. | [optional] **remove_matched_tokens** | Option<**bool**> | Indicates whether search query tokens that exist in the override's rule should be removed from the search query. | [optional] +**metadata** | Option<[**serde_json::Value**](.md)> | Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. | [optional] +**sort_by** | Option<**String**> | A sort by clause that is applied to any search query that matches the override rule. | [optional] +**replace_query** | Option<**String**> | Replaces the current search query with this value, when the search query matches the override rule. | [optional] +**filter_curated_hits** | Option<**bool**> | When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. | [optional] +**effective_from_ts** | Option<**i32**> | A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. | [optional] +**effective_to_ts** | Option<**i32**> | A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. | [optional] +**stop_processing** | Option<**bool**> | When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. | [optional] **id** | **String** | | [readonly] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchOverrideDeleteResponse.md b/typesense_codegen/docs/SearchOverrideDeleteResponse.md new file mode 100644 index 0000000..3392bd0 --- /dev/null +++ b/typesense_codegen/docs/SearchOverrideDeleteResponse.md @@ -0,0 +1,11 @@ +# SearchOverrideDeleteResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | The id of the override that was deleted | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchOverrideRule.md b/typesense_codegen/docs/SearchOverrideRule.md index f4ac180..2234944 100644 --- a/typesense_codegen/docs/SearchOverrideRule.md +++ b/typesense_codegen/docs/SearchOverrideRule.md @@ -4,8 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**query** | **String** | Indicates what search queries should be overridden | -**r#match** | **String** | Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. | +**tags** | Option<**Vec**> | List of tag values to associate with this override rule. | [optional] +**query** | Option<**String**> | Indicates what search queries should be overridden | [optional] +**r#match** | Option<**String**> | Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. | [optional] +**filter_by** | Option<**String**> | Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchOverrideSchema.md b/typesense_codegen/docs/SearchOverrideSchema.md index 6aaad22..4da9648 100644 --- a/typesense_codegen/docs/SearchOverrideSchema.md +++ b/typesense_codegen/docs/SearchOverrideSchema.md @@ -4,11 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**rule** | [**crate::models::SearchOverrideRule**](SearchOverrideRule.md) | | -**includes** | Option<[**Vec**](SearchOverrideInclude.md)> | List of document `id`s that should be included in the search results with their corresponding `position`s. | [optional] -**excludes** | Option<[**Vec**](SearchOverrideExclude.md)> | List of document `id`s that should be excluded from the search results. | [optional] +**rule** | [**models::SearchOverrideRule**](SearchOverrideRule.md) | | +**includes** | Option<[**Vec**](SearchOverrideInclude.md)> | List of document `id`s that should be included in the search results with their corresponding `position`s. | [optional] +**excludes** | Option<[**Vec**](SearchOverrideExclude.md)> | List of document `id`s that should be excluded from the search results. | [optional] **filter_by** | Option<**String**> | A filter by clause that is applied to any search query that matches the override rule. | [optional] **remove_matched_tokens** | Option<**bool**> | Indicates whether search query tokens that exist in the override's rule should be removed from the search query. | [optional] +**metadata** | Option<[**serde_json::Value**](.md)> | Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. | [optional] +**sort_by** | Option<**String**> | A sort by clause that is applied to any search query that matches the override rule. | [optional] +**replace_query** | Option<**String**> | Replaces the current search query with this value, when the search query matches the override rule. | [optional] +**filter_curated_hits** | Option<**bool**> | When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. | [optional] +**effective_from_ts** | Option<**i32**> | A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. | [optional] +**effective_to_ts** | Option<**i32**> | A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. | [optional] +**stop_processing** | Option<**bool**> | When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchOverridesResponse.md b/typesense_codegen/docs/SearchOverridesResponse.md index 422e1b3..4c3952b 100644 --- a/typesense_codegen/docs/SearchOverridesResponse.md +++ b/typesense_codegen/docs/SearchOverridesResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**overrides** | [**Vec**](SearchOverride.md) | | +**overrides** | [**Vec**](SearchOverride.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchParameters.md b/typesense_codegen/docs/SearchParameters.md index 740eb30..b6ccf51 100644 --- a/typesense_codegen/docs/SearchParameters.md +++ b/typesense_codegen/docs/SearchParameters.md @@ -4,15 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**q** | **String** | The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. | -**query_by** | **String** | A list of `string` fields that should be queried against. Multiple fields are separated with a comma. | +**q** | Option<**String**> | The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. | [optional] +**query_by** | Option<**String**> | A list of `string` fields that should be queried against. Multiple fields are separated with a comma. | [optional] +**nl_query** | Option<**bool**> | Whether to use natural language processing to parse the query. | [optional] +**nl_model_id** | Option<**String**> | The ID of the natural language model to use. | [optional] **query_by_weights** | Option<**String**> | The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. | [optional] **text_match_type** | Option<**String**> | In a multi-field matching context, this parameter determines how the representative text match score of a record is calculated. Possible values are max_score (default) or max_weight. | [optional] **prefix** | Option<**String**> | Boolean field to indicate that the last word in the query should be treated as a prefix, and not as a whole word. This is used for building autocomplete and instant search interfaces. Defaults to true. | [optional] **infix** | Option<**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 | [optional] **max_extra_prefix** | Option<**i32**> | There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query \"K2100\" has 2 extra symbols in \"6PK2100\". By default, any number of prefixes/suffixes can be present for a match. | [optional] **max_extra_suffix** | Option<**i32**> | There are also 2 parameters that allow you to control the extent of infix searching max_extra_prefix and max_extra_suffix which specify the maximum number of symbols before or after the query that can be present in the token. For example query \"K2100\" has 2 extra symbols in \"6PK2100\". By default, any number of prefixes/suffixes can be present for a match. | [optional] -**filter_by** | Option<**String**> | Filter conditions for refining youropen api validator search results. Separate multiple conditions with &&. | [optional] +**filter_by** | Option<**String**> | Filter conditions for refining your open api validator search results. Separate multiple conditions with &&. | [optional] +**max_filter_by_candidates** | Option<**i32**> | Controls the number of similar words that Typesense considers during fuzzy search on filter_by values. Useful for controlling prefix matches like company_name:Acm*. | [optional] **sort_by** | Option<**String**> | A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` | [optional] **facet_by** | Option<**String**> | A list of fields that will be used for faceting your results on. Separate multiple fields with a comma. | [optional] **max_facet_values** | Option<**i32**> | Maximum number of facet values to be returned. | [optional] @@ -20,10 +23,11 @@ Name | Type | Description | Notes **num_typos** | Option<**String**> | The number of typographical errors (1 or 2) that would be tolerated. Default: 2 | [optional] **page** | Option<**i32**> | Results from this specific page number would be fetched. | [optional] **per_page** | Option<**i32**> | Number of results to fetch per page. Default: 10 | [optional] -**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] +**limit** | Option<**i32**> | Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. | [optional] **offset** | Option<**i32**> | Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. | [optional] **group_by** | Option<**String**> | You can aggregate search results into groups or buckets by specify one or more `group_by` fields. Separate multiple fields with a comma. To group on a particular field, it must be a faceted field. | [optional] **group_limit** | Option<**i32**> | Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 | [optional] +**group_missing_values** | Option<**bool**> | Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true | [optional] **include_fields** | Option<**String**> | List of fields from the document to include in the search result | [optional] **exclude_fields** | Option<**String**> | List of fields from the document to exclude in the search result | [optional] **highlight_full_fields** | Option<**String**> | List of fields which should be highlighted fully without snippeting | [optional] @@ -31,28 +35,46 @@ Name | Type | Description | Notes **highlight_start_tag** | Option<**String**> | The start tag used for the highlighted snippets. Default: `` | [optional] **highlight_end_tag** | Option<**String**> | The end tag used for the highlighted snippets. Default: `` | [optional] **enable_highlight_v1** | Option<**bool**> | Flag for enabling/disabling the deprecated, old highlight structure in the response. Default: true | [optional][default to true] +**enable_analytics** | Option<**bool**> | Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). | [optional][default to true] **snippet_threshold** | Option<**i32**> | Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 | [optional] +**synonym_sets** | Option<**String**> | List of synonym set names to associate with this search query | [optional] **drop_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 | [optional] +**drop_tokens_mode** | Option<[**models::DropTokensMode**](DropTokensMode.md)> | | [optional] **typo_tokens_threshold** | Option<**i32**> | If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 | [optional] -**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] +**enable_typos_for_alpha_numerical_tokens** | Option<**bool**> | Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. | [optional] +**filter_curated_hits** | Option<**bool**> | Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false | [optional] +**enable_synonyms** | Option<**bool**> | If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true | [optional] +**synonym_prefix** | Option<**bool**> | Allow synonym resolution on word prefixes in the query. Default: false | [optional] +**synonym_num_typos** | Option<**i32**> | Allow synonym resolution on typo-corrected words in the query. Default: 0 | [optional] +**pinned_hits** | Option<**String**> | A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] **hidden_hits** | Option<**String**> | A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. | [optional] -**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] +**override_tags** | Option<**String**> | Comma separated list of tags to trigger the curations rules that match the tags. | [optional] +**highlight_fields** | Option<**String**> | A list of custom fields that must be highlighted even if you don't query for them | [optional] **split_join_tokens** | Option<**String**> | Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. | [optional] -**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional] +**pre_segmented_query** | Option<**bool**> | You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same | [optional] **preset** | Option<**String**> | Search using a bunch of search parameters by setting this parameter to the name of the existing Preset. | [optional] -**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional] -**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional] +**enable_overrides** | Option<**bool**> | If you have some overrides defined but want to disable all of them during query time, you can do that by setting this parameter to false | [optional][default to false] +**prioritize_exact_match** | Option<**bool**> | Set this parameter to true to ensure that an exact match is ranked above the others | [optional][default to true] **max_candidates** | Option<**i32**> | Control the number of words that Typesense considers for typo and prefix searching. | [optional] -**prioritize_token_position** | Option<**bool**> | Make Typesense prioritize documents where the query words appear earlier in the text. | [optional] -**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] -**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] +**prioritize_token_position** | Option<**bool**> | Make Typesense prioritize documents where the query words appear earlier in the text. | [optional][default to false] +**prioritize_num_matching_fields** | Option<**bool**> | Make Typesense prioritize documents where the query words appear in more number of fields. | [optional][default to true] +**enable_typos_for_numerical_tokens** | Option<**bool**> | Make Typesense disable typos for numerical tokens. | [optional][default to true] +**exhaustive_search** | Option<**bool**> | Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). | [optional] +**search_cutoff_ms** | Option<**i32**> | Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. | [optional] **use_cache** | Option<**bool**> | Enable server side caching of search query results. By default, caching is disabled. | [optional] -**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] -**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] -**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**cache_ttl** | Option<**i32**> | The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. | [optional] +**min_len_1typo** | Option<**i32**> | Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] +**min_len_2typo** | Option<**i32**> | Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. | [optional] **vector_query** | Option<**String**> | Vector query expression for fetching documents \"closest\" to a given query/document vector. | [optional] **remote_embedding_timeout_ms** | Option<**i32**> | Timeout (in milliseconds) for fetching remote embeddings. | [optional] **remote_embedding_num_tries** | Option<**i32**> | Number of times to retry fetching remote embeddings. | [optional] +**facet_strategy** | Option<**String**> | Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). | [optional] +**stopwords** | Option<**String**> | Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. | [optional] +**facet_return_parent** | Option<**String**> | Comma separated string of nested facet fields whose parent object should be returned in facet response. | [optional] +**voice_query** | Option<**String**> | The base64 encoded audio file in 16 khz 16-bit WAV format. | [optional] +**conversation** | Option<**bool**> | Enable conversational search. | [optional] +**conversation_model_id** | Option<**String**> | The Id of Conversation Model to be used. | [optional] +**conversation_id** | Option<**String**> | The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchRequestParams.md b/typesense_codegen/docs/SearchRequestParams.md new file mode 100644 index 0000000..57bed91 --- /dev/null +++ b/typesense_codegen/docs/SearchRequestParams.md @@ -0,0 +1,14 @@ +# SearchRequestParams + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**collection_name** | **String** | | +**q** | **String** | | +**per_page** | **i32** | | +**voice_query** | Option<[**models::SearchRequestParamsVoiceQuery**](SearchRequestParams_voice_query.md)> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchRequestParamsVoiceQuery.md b/typesense_codegen/docs/SearchRequestParamsVoiceQuery.md new file mode 100644 index 0000000..92e217b --- /dev/null +++ b/typesense_codegen/docs/SearchRequestParamsVoiceQuery.md @@ -0,0 +1,11 @@ +# SearchRequestParamsVoiceQuery + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**transcribed_query** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchResult.md b/typesense_codegen/docs/SearchResult.md index 857f5ea..0f3bb0f 100644 --- a/typesense_codegen/docs/SearchResult.md +++ b/typesense_codegen/docs/SearchResult.md @@ -4,15 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**facet_counts** | Option<[**Vec**](FacetCounts.md)> | | [optional] +**facet_counts** | Option<[**Vec**](FacetCounts.md)> | | [optional] **found** | Option<**i32**> | The number of documents found | [optional] +**found_docs** | Option<**i32**> | | [optional] **search_time_ms** | Option<**i32**> | The number of milliseconds the search took | [optional] **out_of** | Option<**i32**> | The total number of documents in the collection | [optional] **search_cutoff** | Option<**bool**> | Whether the search was cut off | [optional] **page** | Option<**i32**> | The search result page number | [optional] -**grouped_hits** | Option<[**Vec**](SearchGroupedHit.md)> | | [optional] -**hits** | Option<[**Vec**](SearchResultHit.md)> | The documents that matched the search query | [optional] -**request_params** | Option<[**crate::models::SearchResultRequestParams**](SearchResult_request_params.md)> | | [optional] +**grouped_hits** | Option<[**Vec**](SearchGroupedHit.md)> | | [optional] +**hits** | Option<[**Vec**](SearchResultHit.md)> | The documents that matched the search query | [optional] +**request_params** | Option<[**models::SearchRequestParams**](SearchRequestParams.md)> | | [optional] +**conversation** | Option<[**models::SearchResultConversation**](SearchResultConversation.md)> | | [optional] +**union_request_params** | Option<[**Vec**](SearchRequestParams.md)> | Returned only for union query response. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchResultConversation.md b/typesense_codegen/docs/SearchResultConversation.md new file mode 100644 index 0000000..2428ba7 --- /dev/null +++ b/typesense_codegen/docs/SearchResultConversation.md @@ -0,0 +1,14 @@ +# SearchResultConversation + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**answer** | **String** | | +**conversation_history** | [**Vec**](serde_json::Value.md) | | +**conversation_id** | **String** | | +**query** | **String** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchResultHit.md b/typesense_codegen/docs/SearchResultHit.md index 3b9d460..28d58a5 100644 --- a/typesense_codegen/docs/SearchResultHit.md +++ b/typesense_codegen/docs/SearchResultHit.md @@ -4,12 +4,15 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**highlights** | Option<[**Vec**](SearchHighlight.md)> | (Deprecated) Contains highlighted portions of the search fields | [optional] -**highlight** | Option<[**::std::collections::HashMap**](serde_json::Value.md)> | Highlighted version of the matching document | [optional] -**document** | Option<[**::std::collections::HashMap**](serde_json::Value.md)> | Can be any key-value pair | [optional] +**highlights** | Option<[**Vec**](SearchHighlight.md)> | (Deprecated) Contains highlighted portions of the search fields | [optional] +**highlight** | Option<[**std::collections::HashMap**](serde_json::Value.md)> | Highlighted version of the matching document | [optional] +**document** | Option<[**std::collections::HashMap**](serde_json::Value.md)> | Can be any key-value pair | [optional] **text_match** | Option<**i64**> | | [optional] -**geo_distance_meters** | Option<**::std::collections::HashMap**> | Can be any key-value pair | [optional] +**text_match_info** | Option<[**models::SearchResultHitTextMatchInfo**](SearchResultHit_text_match_info.md)> | | [optional] +**geo_distance_meters** | Option<**std::collections::HashMap**> | Can be any key-value pair | [optional] **vector_distance** | Option<**f32**> | Distance between the query vector and matching document's vector value | [optional] +**hybrid_search_info** | Option<[**models::SearchResultHitHybridSearchInfo**](SearchResultHit_hybrid_search_info.md)> | | [optional] +**search_index** | Option<**i32**> | Returned only for union query response. Indicates the index of the query which this document matched to. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchResultHitHybridSearchInfo.md b/typesense_codegen/docs/SearchResultHitHybridSearchInfo.md new file mode 100644 index 0000000..99126fa --- /dev/null +++ b/typesense_codegen/docs/SearchResultHitHybridSearchInfo.md @@ -0,0 +1,11 @@ +# SearchResultHitHybridSearchInfo + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**rank_fusion_score** | Option<**f32**> | Combined score from rank fusion of text and vector search | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchResultHitTextMatchInfo.md b/typesense_codegen/docs/SearchResultHitTextMatchInfo.md new file mode 100644 index 0000000..21faffa --- /dev/null +++ b/typesense_codegen/docs/SearchResultHitTextMatchInfo.md @@ -0,0 +1,17 @@ +# SearchResultHitTextMatchInfo + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**best_field_score** | Option<**String**> | | [optional] +**best_field_weight** | Option<**i32**> | | [optional] +**fields_matched** | Option<**i32**> | | [optional] +**num_tokens_dropped** | Option<**i64**> | | [optional] +**score** | Option<**String**> | | [optional] +**tokens_matched** | Option<**i32**> | | [optional] +**typo_prefix_score** | Option<**i32**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchResultRequestParams.md b/typesense_codegen/docs/SearchResultRequestParams.md index 2ba855f..9eeb27e 100644 --- a/typesense_codegen/docs/SearchResultRequestParams.md +++ b/typesense_codegen/docs/SearchResultRequestParams.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **collection_name** | **String** | | **q** | **String** | | **per_page** | **i32** | | +**voice_query** | Option<[**models::SearchResultRequestParamsVoiceQuery**](SearchResult_request_params_voice_query.md)> | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchResultRequestParamsVoiceQuery.md b/typesense_codegen/docs/SearchResultRequestParamsVoiceQuery.md new file mode 100644 index 0000000..e7293e7 --- /dev/null +++ b/typesense_codegen/docs/SearchResultRequestParamsVoiceQuery.md @@ -0,0 +1,11 @@ +# SearchResultRequestParamsVoiceQuery + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**transcribed_query** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchSynonym.md b/typesense_codegen/docs/SearchSynonym.md index 4061c2b..70c9964 100644 --- a/typesense_codegen/docs/SearchSynonym.md +++ b/typesense_codegen/docs/SearchSynonym.md @@ -6,6 +6,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **root** | Option<**String**> | For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. | [optional] **synonyms** | **Vec** | Array of words that should be considered as synonyms. | +**locale** | Option<**String**> | Locale for the synonym, leave blank to use the standard tokenizer. | [optional] +**symbols_to_index** | Option<**Vec**> | By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. | [optional] **id** | **String** | | [readonly] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchSynonymDeleteResponse.md b/typesense_codegen/docs/SearchSynonymDeleteResponse.md new file mode 100644 index 0000000..76ab57c --- /dev/null +++ b/typesense_codegen/docs/SearchSynonymDeleteResponse.md @@ -0,0 +1,11 @@ +# SearchSynonymDeleteResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | The id of the synonym that was deleted | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SearchSynonymSchema.md b/typesense_codegen/docs/SearchSynonymSchema.md index bcb5956..bac8165 100644 --- a/typesense_codegen/docs/SearchSynonymSchema.md +++ b/typesense_codegen/docs/SearchSynonymSchema.md @@ -6,6 +6,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **root** | Option<**String**> | For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. | [optional] **synonyms** | **Vec** | Array of words that should be considered as synonyms. | +**locale** | Option<**String**> | Locale for the synonym, leave blank to use the standard tokenizer. | [optional] +**symbols_to_index** | Option<**Vec**> | By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/SearchSynonymsResponse.md b/typesense_codegen/docs/SearchSynonymsResponse.md index f88f04c..6b946ee 100644 --- a/typesense_codegen/docs/SearchSynonymsResponse.md +++ b/typesense_codegen/docs/SearchSynonymsResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**synonyms** | [**Vec**](SearchSynonym.md) | | +**synonyms** | [**Vec**](SearchSynonym.md) | | [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/typesense_codegen/docs/StemmingApi.md b/typesense_codegen/docs/StemmingApi.md new file mode 100644 index 0000000..be81156 --- /dev/null +++ b/typesense_codegen/docs/StemmingApi.md @@ -0,0 +1,99 @@ +# \StemmingApi + +All URIs are relative to *http://localhost:8108* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**get_stemming_dictionary**](StemmingApi.md#get_stemming_dictionary) | **GET** /stemming/dictionaries/{dictionaryId} | Retrieve a stemming dictionary +[**import_stemming_dictionary**](StemmingApi.md#import_stemming_dictionary) | **POST** /stemming/dictionaries/import | Import a stemming dictionary +[**list_stemming_dictionaries**](StemmingApi.md#list_stemming_dictionaries) | **GET** /stemming/dictionaries | List all stemming dictionaries + + + +## get_stemming_dictionary + +> models::StemmingDictionary get_stemming_dictionary(dictionary_id) +Retrieve a stemming dictionary + +Fetch details of a specific stemming dictionary. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**dictionary_id** | **String** | The ID of the dictionary to retrieve | [required] | + +### Return type + +[**models::StemmingDictionary**](StemmingDictionary.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## import_stemming_dictionary + +> String import_stemming_dictionary(id, body) +Import a stemming dictionary + +Upload a JSONL file containing word mappings to create or update a stemming dictionary. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**id** | **String** | The ID to assign to the dictionary | [required] | +**body** | **String** | The JSONL file containing word mappings | [required] | + +### Return type + +**String** + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/octet-stream, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## list_stemming_dictionaries + +> models::ListStemmingDictionaries200Response list_stemming_dictionaries() +List all stemming dictionaries + +Retrieve a list of all available stemming dictionaries. + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::ListStemmingDictionaries200Response**](listStemmingDictionaries_200_response.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/StemmingDictionary.md b/typesense_codegen/docs/StemmingDictionary.md new file mode 100644 index 0000000..4aa3a3e --- /dev/null +++ b/typesense_codegen/docs/StemmingDictionary.md @@ -0,0 +1,12 @@ +# StemmingDictionary + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | Unique identifier for the dictionary | +**words** | [**Vec**](StemmingDictionary_words_inner.md) | List of word mappings in the dictionary | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StemmingDictionaryWordsInner.md b/typesense_codegen/docs/StemmingDictionaryWordsInner.md new file mode 100644 index 0000000..7d9a515 --- /dev/null +++ b/typesense_codegen/docs/StemmingDictionaryWordsInner.md @@ -0,0 +1,12 @@ +# StemmingDictionaryWordsInner + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**word** | **String** | The word form to be stemmed | +**root** | **String** | The root form of the word | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StopwordsApi.md b/typesense_codegen/docs/StopwordsApi.md new file mode 100644 index 0000000..8166db2 --- /dev/null +++ b/typesense_codegen/docs/StopwordsApi.md @@ -0,0 +1,130 @@ +# \StopwordsApi + +All URIs are relative to *http://localhost:8108* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_stopwords_set**](StopwordsApi.md#delete_stopwords_set) | **DELETE** /stopwords/{setId} | Delete a stopwords set. +[**retrieve_stopwords_set**](StopwordsApi.md#retrieve_stopwords_set) | **GET** /stopwords/{setId} | Retrieves a stopwords set. +[**retrieve_stopwords_sets**](StopwordsApi.md#retrieve_stopwords_sets) | **GET** /stopwords | Retrieves all stopwords sets. +[**upsert_stopwords_set**](StopwordsApi.md#upsert_stopwords_set) | **PUT** /stopwords/{setId} | Upserts a stopwords set. + + + +## delete_stopwords_set + +> models::DeleteStopwordsSet200Response delete_stopwords_set(set_id) +Delete a stopwords set. + +Permanently deletes a stopwords set, given it's name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**set_id** | **String** | The ID of the stopwords set to delete. | [required] | + +### Return type + +[**models::DeleteStopwordsSet200Response**](deleteStopwordsSet_200_response.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_stopwords_set + +> models::StopwordsSetRetrieveSchema retrieve_stopwords_set(set_id) +Retrieves a stopwords set. + +Retrieve the details of a stopwords set, given it's name. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**set_id** | **String** | The ID of the stopwords set to retrieve. | [required] | + +### Return type + +[**models::StopwordsSetRetrieveSchema**](StopwordsSetRetrieveSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_stopwords_sets + +> models::StopwordsSetsRetrieveAllSchema retrieve_stopwords_sets() +Retrieves all stopwords sets. + +Retrieve the details of all stopwords sets + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**models::StopwordsSetsRetrieveAllSchema**](StopwordsSetsRetrieveAllSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## upsert_stopwords_set + +> models::StopwordsSetSchema upsert_stopwords_set(set_id, stopwords_set_upsert_schema) +Upserts a stopwords set. + +When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**set_id** | **String** | The ID of the stopwords set to upsert. | [required] | +**stopwords_set_upsert_schema** | [**StopwordsSetUpsertSchema**](StopwordsSetUpsertSchema.md) | The stopwords set to upsert. | [required] | + +### Return type + +[**models::StopwordsSetSchema**](StopwordsSetSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/StopwordsSetRetrieveSchema.md b/typesense_codegen/docs/StopwordsSetRetrieveSchema.md new file mode 100644 index 0000000..284a9ed --- /dev/null +++ b/typesense_codegen/docs/StopwordsSetRetrieveSchema.md @@ -0,0 +1,11 @@ +# StopwordsSetRetrieveSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stopwords** | [**models::StopwordsSetSchema**](StopwordsSetSchema.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StopwordsSetSchema.md b/typesense_codegen/docs/StopwordsSetSchema.md new file mode 100644 index 0000000..97d49dc --- /dev/null +++ b/typesense_codegen/docs/StopwordsSetSchema.md @@ -0,0 +1,13 @@ +# StopwordsSetSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | | +**stopwords** | **Vec** | | +**locale** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StopwordsSetUpsertSchema.md b/typesense_codegen/docs/StopwordsSetUpsertSchema.md new file mode 100644 index 0000000..29082d9 --- /dev/null +++ b/typesense_codegen/docs/StopwordsSetUpsertSchema.md @@ -0,0 +1,12 @@ +# StopwordsSetUpsertSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stopwords** | **Vec** | | +**locale** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/StopwordsSetsRetrieveAllSchema.md b/typesense_codegen/docs/StopwordsSetsRetrieveAllSchema.md new file mode 100644 index 0000000..074531b --- /dev/null +++ b/typesense_codegen/docs/StopwordsSetsRetrieveAllSchema.md @@ -0,0 +1,11 @@ +# StopwordsSetsRetrieveAllSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stopwords** | [**Vec**](StopwordsSetSchema.md) | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SynonymItemSchema.md b/typesense_codegen/docs/SynonymItemSchema.md new file mode 100644 index 0000000..1e842d2 --- /dev/null +++ b/typesense_codegen/docs/SynonymItemSchema.md @@ -0,0 +1,15 @@ +# SynonymItemSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | Unique identifier for the synonym item | +**synonyms** | **Vec** | Array of words that should be considered as synonyms | +**root** | Option<**String**> | For 1-way synonyms, indicates the root word that words in the synonyms parameter map to | [optional] +**locale** | Option<**String**> | Locale for the synonym, leave blank to use the standard tokenizer | [optional] +**symbols_to_index** | Option<**Vec**> | By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SynonymSetCreateSchema.md b/typesense_codegen/docs/SynonymSetCreateSchema.md new file mode 100644 index 0000000..d139f56 --- /dev/null +++ b/typesense_codegen/docs/SynonymSetCreateSchema.md @@ -0,0 +1,11 @@ +# SynonymSetCreateSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**items** | [**Vec**](SynonymItemSchema.md) | Array of synonym items | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SynonymSetDeleteSchema.md b/typesense_codegen/docs/SynonymSetDeleteSchema.md new file mode 100644 index 0000000..dfb8d24 --- /dev/null +++ b/typesense_codegen/docs/SynonymSetDeleteSchema.md @@ -0,0 +1,11 @@ +# SynonymSetDeleteSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | Name of the deleted synonym set | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SynonymSetSchema.md b/typesense_codegen/docs/SynonymSetSchema.md new file mode 100644 index 0000000..d859838 --- /dev/null +++ b/typesense_codegen/docs/SynonymSetSchema.md @@ -0,0 +1,12 @@ +# SynonymSetSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**items** | [**Vec**](SynonymItemSchema.md) | Array of synonym items | +**name** | **String** | Name of the synonym set | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SynonymSetsRetrieveSchema.md b/typesense_codegen/docs/SynonymSetsRetrieveSchema.md new file mode 100644 index 0000000..f18b08a --- /dev/null +++ b/typesense_codegen/docs/SynonymSetsRetrieveSchema.md @@ -0,0 +1,11 @@ +# SynonymSetsRetrieveSchema + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**synonym_sets** | [**Vec**](SynonymSetSchema.md) | Array of synonym sets | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/SynonymsApi.md b/typesense_codegen/docs/SynonymsApi.md new file mode 100644 index 0000000..d00c016 --- /dev/null +++ b/typesense_codegen/docs/SynonymsApi.md @@ -0,0 +1,130 @@ +# \SynonymsApi + +All URIs are relative to *http://localhost:8108* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**delete_synonym_set**](SynonymsApi.md#delete_synonym_set) | **DELETE** /synonym_sets/{synonymSetName} | Delete a synonym set +[**retrieve_synonym_set**](SynonymsApi.md#retrieve_synonym_set) | **GET** /synonym_sets/{synonymSetName} | Retrieve a synonym set +[**retrieve_synonym_sets**](SynonymsApi.md#retrieve_synonym_sets) | **GET** /synonym_sets | List all synonym sets +[**upsert_synonym_set**](SynonymsApi.md#upsert_synonym_set) | **PUT** /synonym_sets/{synonymSetName} | Create or update a synonym set + + + +## delete_synonym_set + +> models::SynonymSetDeleteSchema delete_synonym_set(synonym_set_name) +Delete a synonym set + +Delete a specific synonym set by its name + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**synonym_set_name** | **String** | The name of the synonym set to delete | [required] | + +### Return type + +[**models::SynonymSetDeleteSchema**](SynonymSetDeleteSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_synonym_set + +> models::SynonymSetCreateSchema retrieve_synonym_set(synonym_set_name) +Retrieve a synonym set + +Retrieve a specific synonym set by its name + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**synonym_set_name** | **String** | The name of the synonym set to retrieve | [required] | + +### Return type + +[**models::SynonymSetCreateSchema**](SynonymSetCreateSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## retrieve_synonym_sets + +> Vec retrieve_synonym_sets() +List all synonym sets + +Retrieve all synonym sets + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**Vec**](SynonymSetSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## upsert_synonym_set + +> models::SynonymSetSchema upsert_synonym_set(synonym_set_name, synonym_set_create_schema) +Create or update a synonym set + +Create or update a synonym set with the given name + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**synonym_set_name** | **String** | The name of the synonym set to create/update | [required] | +**synonym_set_create_schema** | [**SynonymSetCreateSchema**](SynonymSetCreateSchema.md) | The synonym set to be created/updated | [required] | + +### Return type + +[**models::SynonymSetSchema**](SynonymSetSchema.md) + +### Authorization + +[api_key_header](../README.md#api_key_header) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/typesense_codegen/docs/ToggleSlowRequestLogRequest.md b/typesense_codegen/docs/ToggleSlowRequestLogRequest.md new file mode 100644 index 0000000..5e238c6 --- /dev/null +++ b/typesense_codegen/docs/ToggleSlowRequestLogRequest.md @@ -0,0 +1,11 @@ +# ToggleSlowRequestLogRequest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**log_slow_requests_time_ms** | **i32** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/UpdateDocumentsParameters.md b/typesense_codegen/docs/UpdateDocumentsParameters.md new file mode 100644 index 0000000..31eef40 --- /dev/null +++ b/typesense_codegen/docs/UpdateDocumentsParameters.md @@ -0,0 +1,11 @@ +# UpdateDocumentsParameters + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**filter_by** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/docs/VoiceQueryModelCollectionConfig.md b/typesense_codegen/docs/VoiceQueryModelCollectionConfig.md new file mode 100644 index 0000000..24b0aa9 --- /dev/null +++ b/typesense_codegen/docs/VoiceQueryModelCollectionConfig.md @@ -0,0 +1,11 @@ +# VoiceQueryModelCollectionConfig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**model_name** | Option<**String**> | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/typesense_codegen/git_push.sh b/typesense_codegen/git_push.sh deleted file mode 100644 index f53a75d..0000000 --- a/typesense_codegen/git_push.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/bin/sh -# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ -# -# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="github.com" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -if [ "$git_user_id" = "" ]; then - git_user_id="GIT_USER_ID" - echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" -fi - -if [ "$git_repo_id" = "" ]; then - git_repo_id="GIT_REPO_ID" - echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" -fi - -if [ "$release_note" = "" ]; then - release_note="Minor update" - echo "[INFO] No command line input provided. Set \$release_note to $release_note" -fi - -# Initialize the local directory as a Git repository -git init - -# Adds the files in the local repository and stages them for commit. -git add . - -# Commits the tracked changes and prepares them to be pushed to a remote repository. -git commit -m "$release_note" - -# Sets the new remote -git_remote=$(git remote) -if [ "$git_remote" = "" ]; then # git remote not defined - - if [ "$GIT_TOKEN" = "" ]; then - echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." - git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git - fi - -fi - -git pull origin master - -# Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' diff --git a/typesense_codegen/src/apis/analytics_api.rs b/typesense_codegen/src/apis/analytics_api.rs index 04d5c87..ef17e52 100644 --- a/typesense_codegen/src/apis/analytics_api.rs +++ b/typesense_codegen/src/apis/analytics_api.rs @@ -3,19 +3,83 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; + +/// struct for passing parameters to the method [`create_analytics_event`] +#[derive(Clone, Debug)] +pub struct CreateAnalyticsEventParams { + /// The analytics event to be created + pub analytics_event: models::AnalyticsEvent, +} + +/// struct for passing parameters to the method [`create_analytics_rule`] +#[derive(Clone, Debug)] +pub struct CreateAnalyticsRuleParams { + /// The analytics rule(s) to be created + pub create_analytics_rule_request: models::CreateAnalyticsRuleRequest, +} + +/// struct for passing parameters to the method [`delete_analytics_rule`] +#[derive(Clone, Debug)] +pub struct DeleteAnalyticsRuleParams { + /// The name of the analytics rule to delete + pub rule_name: String, +} + +/// struct for passing parameters to the method [`get_analytics_events`] +#[derive(Clone, Debug)] +pub struct GetAnalyticsEventsParams { + pub user_id: String, + /// Analytics rule name + pub name: String, + /// Number of events to return (max 1000) + pub n: i32, +} + +/// struct for passing parameters to the method [`retrieve_analytics_rule`] +#[derive(Clone, Debug)] +pub struct RetrieveAnalyticsRuleParams { + /// The name of the analytics rule to retrieve + pub rule_name: String, +} + +/// struct for passing parameters to the method [`retrieve_analytics_rules`] +#[derive(Clone, Debug)] +pub struct RetrieveAnalyticsRulesParams { + /// Filter rules by rule_tag + pub rule_tag: Option, +} + +/// struct for passing parameters to the method [`upsert_analytics_rule`] +#[derive(Clone, Debug)] +pub struct UpsertAnalyticsRuleParams { + /// The name of the analytics rule to upsert + pub rule_name: String, + /// The Analytics rule to be upserted + pub analytics_rule_update: models::AnalyticsRuleUpdate, +} + +/// struct for typed errors of method [`create_analytics_event`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateAnalyticsEventError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} /// struct for typed errors of method [`create_analytics_rule`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum CreateAnalyticsRuleError { - Status400(crate::models::ApiResponse), + Status400(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -23,7 +87,29 @@ pub enum CreateAnalyticsRuleError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteAnalyticsRuleError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`flush_analytics`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum FlushAnalyticsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_analytics_events`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetAnalyticsEventsError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_analytics_status`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetAnalyticsStatusError { UnknownValue(serde_json::Value), } @@ -31,7 +117,7 @@ pub enum DeleteAnalyticsRuleError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum RetrieveAnalyticsRuleError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -42,198 +128,550 @@ pub enum RetrieveAnalyticsRulesError { UnknownValue(serde_json::Value), } -/// When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. -pub async fn create_analytics_rule( - configuration: &configuration::Configuration, - analytics_rule_schema: crate::models::AnalyticsRuleSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/analytics/rules", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); +/// struct for typed errors of method [`upsert_analytics_rule`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertAnalyticsRuleError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); +/// Submit a single analytics event. The event must correspond to an existing analytics rule by name. +pub async fn create_analytics_event( + configuration: &configuration::Configuration, + params: &CreateAnalyticsEventParams, +) -> Result> { + let uri_str = format!("{}/analytics/events", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&analytics_rule_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.analytics_event); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Create one or more analytics rules. You can send a single rule object or an array of rule objects. +pub async fn create_analytics_rule( + configuration: &configuration::Configuration, + params: &CreateAnalyticsRuleParams, +) -> Result> { + let uri_str = format!("{}/analytics/rules", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.create_analytics_rule_request); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CreateAnalyticsRule200Response`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Permanently deletes an analytics rule, given it's name pub async fn delete_analytics_rule( configuration: &configuration::Configuration, - rule_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &DeleteAnalyticsRuleParams, +) -> Result> { + let uri_str = format!( "{}/analytics/rules/{ruleName}", - local_var_configuration.base_path, - ruleName = crate::apis::urlencode(rule_name) + configuration.base_path, + ruleName = crate::apis::urlencode(¶ms.rule_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; +/// Triggers a flush of analytics data to persistent storage. +pub async fn flush_analytics( + configuration: &configuration::Configuration, +) -> Result> { + let uri_str = format!("{}/analytics/flush", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventCreateResponse`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve the most recent events for a user and rule. +pub async fn get_analytics_events( + configuration: &configuration::Configuration, + params: &GetAnalyticsEventsParams, +) -> Result> { + let uri_str = format!("{}/analytics/events", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + req_builder = req_builder.query(&[("user_id", ¶ms.user_id.to_string())]); + req_builder = req_builder.query(&[("name", ¶ms.name.to_string())]); + req_builder = req_builder.query(&[("n", ¶ms.n.to_string())]); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsEventsResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsEventsResponse`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -/// Retrieve the details of an analytics rule, given it's name -pub async fn retrieve_analytics_rule( +/// Returns sizes of internal analytics buffers and queues. +pub async fn get_analytics_status( configuration: &configuration::Configuration, - rule_name: &str, -) -> Result> { - let local_var_configuration = configuration; +) -> Result> { + let uri_str = format!("{}/analytics/status", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_client = &local_var_configuration.client; + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; - let local_var_uri_str = format!( + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsStatus`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve the details of an analytics rule, given it's name +pub async fn retrieve_analytics_rule( + configuration: &configuration::Configuration, + params: &RetrieveAnalyticsRuleParams, +) -> Result> { + let uri_str = format!( "{}/analytics/rules/{ruleName}", - local_var_configuration.base_path, - ruleName = crate::apis::urlencode(rule_name) + configuration.base_path, + ruleName = crate::apis::urlencode(¶ms.rule_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } -/// Retrieve the details of all analytics rules +/// Retrieve all analytics rules. Use the optional rule_tag filter to narrow down results. pub async fn retrieve_analytics_rules( configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; + params: &RetrieveAnalyticsRulesParams, +) -> Result, Error> { + let uri_str = format!("{}/analytics/rules", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_uri_str = format!("{}/analytics/rules", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref param_value) = params.rule_tag { + req_builder = req_builder.query(&[("rule_tag", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; +/// Upserts an analytics rule with the given name. +pub async fn upsert_analytics_rule( + configuration: &configuration::Configuration, + params: &UpsertAnalyticsRuleParams, +) -> Result> { + let uri_str = format!( + "{}/analytics/rules/{ruleName}", + configuration.base_path, + ruleName = crate::apis::urlencode(¶ms.rule_name) + ); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.analytics_rule_update); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::AnalyticsRule`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::AnalyticsRule`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } diff --git a/typesense_codegen/src/apis/collections_api.rs b/typesense_codegen/src/apis/collections_api.rs index 000dc71..b965f8c 100644 --- a/typesense_codegen/src/apis/collections_api.rs +++ b/typesense_codegen/src/apis/collections_api.rs @@ -3,20 +3,83 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; + +/// struct for passing parameters to the method [`create_collection`] +#[derive(Clone, Debug)] +pub struct CreateCollectionParams { + /// The collection object to be created + pub collection_schema: models::CollectionSchema, +} + +/// struct for passing parameters to the method [`delete_alias`] +#[derive(Clone, Debug)] +pub struct DeleteAliasParams { + /// The name of the alias to delete + pub alias_name: String, +} + +/// struct for passing parameters to the method [`delete_collection`] +#[derive(Clone, Debug)] +pub struct DeleteCollectionParams { + /// The name of the collection to delete + pub collection_name: String, +} + +/// struct for passing parameters to the method [`get_alias`] +#[derive(Clone, Debug)] +pub struct GetAliasParams { + /// The name of the alias to retrieve + pub alias_name: String, +} + +/// struct for passing parameters to the method [`get_collection`] +#[derive(Clone, Debug)] +pub struct GetCollectionParams { + /// The name of the collection to retrieve + pub collection_name: String, +} + +/// struct for passing parameters to the method [`get_collections`] +#[derive(Clone, Debug)] +pub struct GetCollectionsParams { + pub exclude_fields: Option, + pub limit: Option, + pub offset: Option, +} + +/// struct for passing parameters to the method [`update_collection`] +#[derive(Clone, Debug)] +pub struct UpdateCollectionParams { + /// The name of the collection to update + pub collection_name: String, + /// The document object with fields to be updated + pub collection_update_schema: models::CollectionUpdateSchema, +} + +/// struct for passing parameters to the method [`upsert_alias`] +#[derive(Clone, Debug)] +pub struct UpsertAliasParams { + /// The name of the alias to create/update + pub alias_name: String, + /// Collection alias to be created/updated + pub collection_alias_schema: Option, +} /// struct for typed errors of method [`create_collection`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum CreateCollectionError { - Status400(crate::models::ApiResponse), - Status409(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status409(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -24,7 +87,7 @@ pub enum CreateCollectionError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteAliasError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -32,7 +95,7 @@ pub enum DeleteAliasError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteCollectionError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -40,7 +103,7 @@ pub enum DeleteCollectionError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetAliasError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -55,7 +118,7 @@ pub enum GetAliasesError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetCollectionError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -70,8 +133,8 @@ pub enum GetCollectionsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpdateCollectionError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -79,455 +142,562 @@ pub enum UpdateCollectionError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpsertAliasError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } /// When a collection is created, we give it a name and describe the fields that will be indexed from the documents added to the collection. pub async fn create_collection( configuration: &configuration::Configuration, - collection_schema: crate::models::CollectionSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/collections", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + params: &CreateCollectionParams, +) -> Result> { + let uri_str = format!("{}/collections", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&collection_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.collection_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } pub async fn delete_alias( configuration: &configuration::Configuration, - alias_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &DeleteAliasParams, +) -> Result> { + let uri_str = format!( "{}/aliases/{aliasName}", - local_var_configuration.base_path, - aliasName = crate::apis::urlencode(alias_name) + configuration.base_path, + aliasName = crate::apis::urlencode(¶ms.alias_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Permanently drops a collection. This action cannot be undone. For large collections, this might have an impact on read latencies. pub async fn delete_collection( configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &DeleteCollectionParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Find out which collection an alias points to by fetching it pub async fn get_alias( configuration: &configuration::Configuration, - alias_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &GetAliasParams, +) -> Result> { + let uri_str = format!( "{}/aliases/{aliasName}", - local_var_configuration.base_path, - aliasName = crate::apis::urlencode(alias_name) + configuration.base_path, + aliasName = crate::apis::urlencode(¶ms.alias_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`" + )))); + } + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// List all aliases and the corresponding collections that they map to. pub async fn get_aliases( configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; +) -> Result> { + let uri_str = format!("{}/aliases", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_uri_str = format!("{}/aliases", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionAliasesResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAliasesResponse`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of a collection, given its name. pub async fn get_collection( configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &GetCollectionParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionResponse`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Returns a summary of all your collections. The collections are returned sorted by creation date, with the most recent collections appearing first. pub async fn get_collections( configuration: &configuration::Configuration, -) -> Result, Error> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; + params: &GetCollectionsParams, +) -> Result, Error> { + let uri_str = format!("{}/collections", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_uri_str = format!("{}/collections", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref param_value) = params.exclude_fields { + req_builder = req_builder.query(&[("exclude_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.limit { + req_builder = req_builder.query(&[("limit", ¶m_value.to_string())]); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref param_value) = params.offset { + req_builder = req_builder.query(&[("offset", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Update a collection's schema to modify the fields and their types. pub async fn update_collection( configuration: &configuration::Configuration, - collection_name: &str, - collection_update_schema: crate::models::CollectionUpdateSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &UpdateCollectionParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PATCH, local_var_uri_str.as_str()); + let mut req_builder = configuration + .client + .request(reqwest::Method::PATCH, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&collection_update_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.collection_update_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionUpdateSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionUpdateSchema`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create or update a collection alias. An alias is a virtual collection name that points to a real collection. If you're familiar with symbolic links on Linux, it's very similar to that. Aliases are useful when you want to reindex your data in the background on a new collection and switch your application to it without any changes to your code. pub async fn upsert_alias( configuration: &configuration::Configuration, - alias_name: &str, - collection_alias_schema: Option, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &UpsertAliasParams, +) -> Result> { + let uri_str = format!( "{}/aliases/{aliasName}", - local_var_configuration.base_path, - aliasName = crate::apis::urlencode(alias_name) + configuration.base_path, + aliasName = crate::apis::urlencode(¶ms.alias_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&collection_alias_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.collection_alias_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::CollectionAlias`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::CollectionAlias`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } diff --git a/typesense_codegen/src/apis/configuration.rs b/typesense_codegen/src/apis/configuration.rs index f5e29b4..32cfc2e 100644 --- a/typesense_codegen/src/apis/configuration.rs +++ b/typesense_codegen/src/apis/configuration.rs @@ -3,21 +3,27 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 28.0 * * Generated by: https://openapi-generator.tech */ +// This file was added to .openapi-generator-ignore so we can freely modify it. + +#[cfg(target_arch = "wasm32")] +pub type HttpClient = reqwest::Client; + +#[cfg(not(target_arch = "wasm32"))] +pub type HttpClient = reqwest_middleware::ClientWithMiddleware; #[derive(Debug, Clone)] pub struct Configuration { pub base_path: String, pub user_agent: Option, - pub client: reqwest::Client, + pub client: HttpClient, pub basic_auth: Option, pub oauth_access_token: Option, pub bearer_access_token: Option, pub api_key: Option, - // TODO: take an oauth2 token source, similar to the go one } pub type BasicAuth = (String, Option); @@ -29,17 +35,24 @@ pub struct ApiKey { } impl Configuration { + #[inline] pub fn new() -> Configuration { Configuration::default() } } impl Default for Configuration { + #[inline] fn default() -> Self { + #[cfg(target_arch = "wasm32")] + let client = reqwest::Client::new(); + + #[cfg(not(target_arch = "wasm32"))] + let client = reqwest_middleware::ClientBuilder::new(reqwest::Client::new()).build(); Configuration { base_path: "http://localhost".to_owned(), - user_agent: Some("OpenAPI-Generator/0.25.0/rust".to_owned()), - client: reqwest::Client::new(), + user_agent: Some("OpenAPI-Generator/30.0/rust".to_owned()), + client, basic_auth: None, oauth_access_token: None, bearer_access_token: None, diff --git a/typesense_codegen/src/apis/conversations_api.rs b/typesense_codegen/src/apis/conversations_api.rs new file mode 100644 index 0000000..c495f6b --- /dev/null +++ b/typesense_codegen/src/apis/conversations_api.rs @@ -0,0 +1,381 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; + +/// struct for passing parameters to the method [`create_conversation_model`] +#[derive(Clone, Debug)] +pub struct CreateConversationModelParams { + pub conversation_model_create_schema: models::ConversationModelCreateSchema, +} + +/// struct for passing parameters to the method [`delete_conversation_model`] +#[derive(Clone, Debug)] +pub struct DeleteConversationModelParams { + /// The id of the conversation model to delete + pub model_id: String, +} + +/// struct for passing parameters to the method [`retrieve_conversation_model`] +#[derive(Clone, Debug)] +pub struct RetrieveConversationModelParams { + /// The id of the conversation model to retrieve + pub model_id: String, +} + +/// struct for passing parameters to the method [`update_conversation_model`] +#[derive(Clone, Debug)] +pub struct UpdateConversationModelParams { + /// The id of the conversation model to update + pub model_id: String, + pub conversation_model_update_schema: models::ConversationModelUpdateSchema, +} + +/// struct for typed errors of method [`create_conversation_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateConversationModelError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`delete_conversation_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteConversationModelError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_all_conversation_models`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveAllConversationModelsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_conversation_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveConversationModelError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`update_conversation_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpdateConversationModelError { + UnknownValue(serde_json::Value), +} + +/// Create a Conversation Model +pub async fn create_conversation_model( + configuration: &configuration::Configuration, + params: &CreateConversationModelParams, +) -> Result> { + let uri_str = format!("{}/conversations/models", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.conversation_model_create_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Delete a conversation model +pub async fn delete_conversation_model( + configuration: &configuration::Configuration, + params: &DeleteConversationModelParams, +) -> Result> { + let uri_str = format!( + "{}/conversations/models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(¶ms.model_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve all conversation models +pub async fn retrieve_all_conversation_models( + configuration: &configuration::Configuration, +) -> Result, Error> { + let uri_str = format!("{}/conversations/models", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = + serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve a conversation model +pub async fn retrieve_conversation_model( + configuration: &configuration::Configuration, + params: &RetrieveConversationModelParams, +) -> Result> { + let uri_str = format!( + "{}/conversations/models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(¶ms.model_id) + ); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Update a conversation model +pub async fn update_conversation_model( + configuration: &configuration::Configuration, + params: &UpdateConversationModelParams, +) -> Result> { + let uri_str = format!( + "{}/conversations/models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(¶ms.model_id) + ); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.conversation_model_update_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ConversationModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ConversationModelSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} diff --git a/typesense_codegen/src/apis/curation_api.rs b/typesense_codegen/src/apis/curation_api.rs new file mode 100644 index 0000000..4d3c9c6 --- /dev/null +++ b/typesense_codegen/src/apis/curation_api.rs @@ -0,0 +1,250 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; + +/// struct for passing parameters to the method [`delete_search_override`] +#[derive(Clone, Debug)] +pub struct DeleteSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search override to delete + pub override_id: String, +} + +/// struct for passing parameters to the method [`get_search_overrides`] +#[derive(Clone, Debug)] +pub struct GetSearchOverridesParams { + /// The name of the collection + pub collection_name: String, +} + +/// struct for passing parameters to the method [`upsert_search_override`] +#[derive(Clone, Debug)] +pub struct UpsertSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search override to create/update + pub override_id: String, + /// The search override object to be created/updated + pub search_override_schema: models::SearchOverrideSchema, +} + +/// struct for typed errors of method [`delete_search_override`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteSearchOverrideError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_search_overrides`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetSearchOverridesError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`upsert_search_override`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertSearchOverrideError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +pub async fn delete_search_override( + configuration: &configuration::Configuration, + params: &DeleteSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name), + overrideId = crate::apis::urlencode(¶ms.override_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +pub async fn get_search_overrides( + configuration: &configuration::Configuration, + params: &GetSearchOverridesParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides", + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name) + ); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. +pub async fn upsert_search_override( + configuration: &configuration::Configuration, + params: &UpsertSearchOverrideParams, +) -> Result> { + let uri_str = format!( + "{}/collections/{collectionName}/overrides/{overrideId}", + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name), + overrideId = crate::apis::urlencode(¶ms.override_id) + ); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.search_override_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} diff --git a/typesense_codegen/src/apis/debug_api.rs b/typesense_codegen/src/apis/debug_api.rs index 5f4dd0f..73a5dba 100644 --- a/typesense_codegen/src/apis/debug_api.rs +++ b/typesense_codegen/src/apis/debug_api.rs @@ -3,13 +3,15 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; /// struct for typed errors of method [`debug`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -21,44 +23,55 @@ pub enum DebugError { /// Print debugging information pub async fn debug( configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; +) -> Result> { + let uri_str = format!("{}/debug", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/debug", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::Debug200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::Debug200Response`" + )))); + } + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } diff --git a/typesense_codegen/src/apis/documents_api.rs b/typesense_codegen/src/apis/documents_api.rs index f19502b..92a3e8e 100644 --- a/typesense_codegen/src/apis/documents_api.rs +++ b/typesense_codegen/src/apis/documents_api.rs @@ -3,19 +3,295 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; + +/// struct for passing parameters to the method [`delete_document`] +#[derive(Clone, Debug)] +pub struct DeleteDocumentParams { + /// The name of the collection to search for the document under + pub collection_name: String, + /// The Document ID + pub document_id: String, +} + +/// struct for passing parameters to the method [`delete_documents`] +#[derive(Clone, Debug)] +pub struct DeleteDocumentsParams { + /// The name of the collection to delete documents from + pub collection_name: String, + pub filter_by: Option, + pub batch_size: Option, + pub ignore_not_found: Option, + pub truncate: Option, +} + +/// struct for passing parameters to the method [`delete_search_override`] +#[derive(Clone, Debug)] +pub struct DeleteSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search override to delete + pub override_id: String, +} + +/// struct for passing parameters to the method [`export_documents`] +#[derive(Clone, Debug)] +pub struct ExportDocumentsParams { + /// The name of the collection + pub collection_name: String, + pub filter_by: Option, + pub include_fields: Option, + pub exclude_fields: Option, +} + +/// struct for passing parameters to the method [`get_document`] +#[derive(Clone, Debug)] +pub struct GetDocumentParams { + /// The name of the collection to search for the document under + pub collection_name: String, + /// The Document ID + pub document_id: String, +} + +/// struct for passing parameters to the method [`get_search_override`] +#[derive(Clone, Debug)] +pub struct GetSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The id of the search override + pub override_id: String, +} + +/// struct for passing parameters to the method [`get_search_overrides`] +#[derive(Clone, Debug)] +pub struct GetSearchOverridesParams { + /// The name of the collection + pub collection_name: String, +} + +/// struct for passing parameters to the method [`import_documents`] +#[derive(Clone, Debug)] +pub struct ImportDocumentsParams { + /// The name of the collection + pub collection_name: String, + /// The json array of documents or the JSONL file to import + pub body: String, + pub batch_size: Option, + pub return_id: Option, + pub remote_embedding_batch_size: Option, + pub return_doc: Option, + pub action: Option, + pub dirty_values: Option, +} + +/// struct for passing parameters to the method [`index_document`] +#[derive(Clone, Debug)] +pub struct IndexDocumentParams { + /// The name of the collection to add the document to + pub collection_name: String, + /// The document object to be indexed + pub body: serde_json::Value, + /// Additional action to perform + pub action: Option, + /// Dealing with Dirty Data + pub dirty_values: Option, +} + +/// struct for passing parameters to the method [`multi_search`] +#[derive(Clone, Debug)] +pub struct MultiSearchParams { + pub q: Option, + pub query_by: Option, + pub query_by_weights: Option, + pub text_match_type: Option, + pub prefix: Option, + pub infix: Option, + pub max_extra_prefix: Option, + pub max_extra_suffix: Option, + pub filter_by: Option, + pub sort_by: Option, + pub facet_by: Option, + pub max_facet_values: Option, + pub facet_query: Option, + pub num_typos: Option, + pub page: Option, + pub per_page: Option, + pub limit: Option, + pub offset: Option, + pub group_by: Option, + pub group_limit: Option, + pub group_missing_values: Option, + pub include_fields: Option, + pub exclude_fields: Option, + pub highlight_full_fields: Option, + pub highlight_affix_num_tokens: Option, + pub highlight_start_tag: Option, + pub highlight_end_tag: Option, + pub snippet_threshold: Option, + pub drop_tokens_threshold: Option, + pub drop_tokens_mode: Option, + pub typo_tokens_threshold: Option, + pub enable_typos_for_alpha_numerical_tokens: Option, + pub filter_curated_hits: Option, + pub enable_synonyms: Option, + pub enable_analytics: Option, + pub synonym_prefix: Option, + pub synonym_num_typos: Option, + pub pinned_hits: Option, + pub hidden_hits: Option, + pub override_tags: Option, + pub highlight_fields: Option, + pub pre_segmented_query: Option, + pub preset: Option, + pub enable_overrides: Option, + pub prioritize_exact_match: Option, + pub prioritize_token_position: Option, + pub prioritize_num_matching_fields: Option, + pub enable_typos_for_numerical_tokens: Option, + pub exhaustive_search: Option, + pub search_cutoff_ms: Option, + pub use_cache: Option, + pub cache_ttl: Option, + pub min_len_1typo: Option, + pub min_len_2typo: Option, + pub vector_query: Option, + pub remote_embedding_timeout_ms: Option, + pub remote_embedding_num_tries: Option, + pub facet_strategy: Option, + pub stopwords: Option, + pub facet_return_parent: Option, + pub voice_query: Option, + pub conversation: Option, + pub conversation_model_id: Option, + pub conversation_id: Option, + pub multi_search_searches_parameter: Option, +} + +/// struct for passing parameters to the method [`search_collection`] +#[derive(Clone, Debug)] +pub struct SearchCollectionParams { + /// The name of the collection to search for the document under + pub collection_name: String, + pub q: Option, + pub query_by: Option, + pub nl_query: Option, + pub nl_model_id: Option, + pub query_by_weights: Option, + pub text_match_type: Option, + pub prefix: Option, + pub infix: Option, + pub max_extra_prefix: Option, + pub max_extra_suffix: Option, + pub filter_by: Option, + pub max_filter_by_candidates: Option, + pub sort_by: Option, + pub facet_by: Option, + pub max_facet_values: Option, + pub facet_query: Option, + pub num_typos: Option, + pub page: Option, + pub per_page: Option, + pub limit: Option, + pub offset: Option, + pub group_by: Option, + pub group_limit: Option, + pub group_missing_values: Option, + pub include_fields: Option, + pub exclude_fields: Option, + pub highlight_full_fields: Option, + pub highlight_affix_num_tokens: Option, + pub highlight_start_tag: Option, + pub highlight_end_tag: Option, + pub enable_highlight_v1: Option, + pub enable_analytics: Option, + pub snippet_threshold: Option, + pub synonym_sets: Option, + pub drop_tokens_threshold: Option, + pub drop_tokens_mode: Option, + pub typo_tokens_threshold: Option, + pub enable_typos_for_alpha_numerical_tokens: Option, + pub filter_curated_hits: Option, + pub enable_synonyms: Option, + pub synonym_prefix: Option, + pub synonym_num_typos: Option, + pub pinned_hits: Option, + pub hidden_hits: Option, + pub override_tags: Option, + pub highlight_fields: Option, + pub split_join_tokens: Option, + pub pre_segmented_query: Option, + pub preset: Option, + pub enable_overrides: Option, + pub prioritize_exact_match: Option, + pub max_candidates: Option, + pub prioritize_token_position: Option, + pub prioritize_num_matching_fields: Option, + pub enable_typos_for_numerical_tokens: Option, + pub exhaustive_search: Option, + pub search_cutoff_ms: Option, + pub use_cache: Option, + pub cache_ttl: Option, + pub min_len_1typo: Option, + pub min_len_2typo: Option, + pub vector_query: Option, + pub remote_embedding_timeout_ms: Option, + pub remote_embedding_num_tries: Option, + pub facet_strategy: Option, + pub stopwords: Option, + pub facet_return_parent: Option, + pub voice_query: Option, + pub conversation: Option, + pub conversation_model_id: Option, + pub conversation_id: Option, +} + +/// struct for passing parameters to the method [`update_document`] +#[derive(Clone, Debug)] +pub struct UpdateDocumentParams { + /// The name of the collection to search for the document under + pub collection_name: String, + /// The Document ID + pub document_id: String, + /// The document object with fields to be updated + pub body: serde_json::Value, + /// Dealing with Dirty Data + pub dirty_values: Option, +} + +/// struct for passing parameters to the method [`update_documents`] +#[derive(Clone, Debug)] +pub struct UpdateDocumentsParams { + /// The name of the collection to update documents in + pub collection_name: String, + /// The document fields to be updated + pub body: serde_json::Value, + pub filter_by: Option, +} + +/// struct for passing parameters to the method [`upsert_search_override`] +#[derive(Clone, Debug)] +pub struct UpsertSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The ID of the search override to create/update + pub override_id: String, + /// The search override object to be created/updated + pub search_override_schema: models::SearchOverrideSchema, +} /// struct for typed errors of method [`delete_document`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteDocumentError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -23,7 +299,7 @@ pub enum DeleteDocumentError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteDocumentsError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -31,15 +307,7 @@ pub enum DeleteDocumentsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteSearchOverrideError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`delete_search_synonym`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum DeleteSearchSynonymError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -47,7 +315,7 @@ pub enum DeleteSearchSynonymError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum ExportDocumentsError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -55,7 +323,7 @@ pub enum ExportDocumentsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetDocumentError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -73,28 +341,12 @@ pub enum GetSearchOverridesError { UnknownValue(serde_json::Value), } -/// struct for typed errors of method [`get_search_synonym`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum GetSearchSynonymError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`get_search_synonyms`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum GetSearchSynonymsError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - /// struct for typed errors of method [`import_documents`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum ImportDocumentsError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -102,7 +354,7 @@ pub enum ImportDocumentsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum IndexDocumentError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -110,7 +362,7 @@ pub enum IndexDocumentError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum MultiSearchError { - Status400(crate::models::ApiResponse), + Status400(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -118,8 +370,8 @@ pub enum MultiSearchError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum SearchCollectionError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -127,7 +379,7 @@ pub enum SearchCollectionError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpdateDocumentError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -135,8 +387,8 @@ pub enum UpdateDocumentError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpdateDocumentsError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -144,990 +396,1351 @@ pub enum UpdateDocumentsError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpsertSearchOverrideError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`upsert_search_synonym`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum UpsertSearchSynonymError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } /// Delete an individual document from a collection by using its ID. pub async fn delete_document( configuration: &configuration::Configuration, - collection_name: &str, - document_id: &str, + params: &DeleteDocumentParams, ) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + let uri_str = format!( "{}/collections/{collectionName}/documents/{documentId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - documentId = crate::apis::urlencode(document_id) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name), + documentId = crate::apis::urlencode(¶ms.document_id) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Delete a bunch of documents that match a specific filter condition. Use the `batch_size` parameter to control the number of documents that should deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. pub async fn delete_documents( configuration: &configuration::Configuration, - collection_name: &str, - delete_documents_parameters: Option< - crate::models::DeleteDocumentsDeleteDocumentsParametersParameter, - >, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &DeleteDocumentsParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/documents", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); - if let Some(ref delete_documents_parameters_ref) = delete_documents_parameters { - local_var_req_builder = local_var_req_builder.query(&delete_documents_parameters_ref); + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.batch_size { + req_builder = req_builder.query(&[("batch_size", ¶m_value.to_string())]); } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref param_value) = params.ignore_not_found { + req_builder = req_builder.query(&[("ignore_not_found", ¶m_value.to_string())]); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref param_value) = params.truncate { + req_builder = req_builder.query(&[("truncate", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::DeleteDocuments200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::DeleteDocuments200Response`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } pub async fn delete_search_override( configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &DeleteSearchOverrideParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name), + overrideId = crate::apis::urlencode(¶ms.override_id) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } -} - -pub async fn delete_search_synonym( - configuration: &configuration::Configuration, - collection_name: &str, - synonym_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/synonyms/{synonymId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - synonymId = crate::apis::urlencode(synonym_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverrideDeleteResponse`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Export all documents in a collection in JSON lines format. pub async fn export_documents( configuration: &configuration::Configuration, - collection_name: &str, - export_documents_parameters: Option< - crate::models::ExportDocumentsExportDocumentsParametersParameter, - >, + params: &ExportDocumentsParams, ) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + let uri_str = format!( "{}/collections/{collectionName}/documents/export", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref export_documents_parameters_ref) = export_documents_parameters { - local_var_req_builder = local_var_req_builder.query(&export_documents_parameters_ref); + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.include_fields { + req_builder = req_builder.query(&[("include_fields", ¶m_value.to_string())]); } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref param_value) = params.exclude_fields { + req_builder = req_builder.query(&[("exclude_fields", ¶m_value.to_string())]); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json | ContentType::Text => return Ok(content), + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `String`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Fetch an individual document from a collection by using its ID. pub async fn get_document( configuration: &configuration::Configuration, - collection_name: &str, - document_id: &str, + params: &GetDocumentParams, ) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + let uri_str = format!( "{}/collections/{collectionName}/documents/{documentId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - documentId = crate::apis::urlencode(document_id) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name), + documentId = crate::apis::urlencode(¶ms.document_id) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve the details of a search override, given its id. pub async fn get_search_override( configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &GetSearchOverrideParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name), + overrideId = crate::apis::urlencode(¶ms.override_id) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } pub async fn get_search_overrides( configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &GetSearchOverridesParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/overrides", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } -} - -/// Retrieve the details of a search synonym, given its id. -pub async fn get_search_synonym( - configuration: &configuration::Configuration, - collection_name: &str, - synonym_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/synonyms/{synonymId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - synonymId = crate::apis::urlencode(synonym_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverridesResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverridesResponse`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) - } -} - -pub async fn get_search_synonyms( - configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/synonyms", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// The documents to be imported must be formatted in a newline delimited JSON structure. You can feed the output file from a Typesense export operation directly as import. pub async fn import_documents( configuration: &configuration::Configuration, - collection_name: &str, - body: String, - import_documents_parameters: Option< - crate::models::ImportDocumentsImportDocumentsParametersParameter, - >, + params: &ImportDocumentsParams, ) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + let uri_str = format!( "{}/collections/{collectionName}/documents/import", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); - if let Some(ref import_documents_parameters_ref) = import_documents_parameters { - local_var_req_builder = local_var_req_builder.query(&import_documents_parameters_ref); + if let Some(ref param_value) = params.batch_size { + req_builder = req_builder.query(&[("batch_size", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.return_id { + req_builder = req_builder.query(&[("return_id", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_batch_size { + req_builder = + req_builder.query(&[("remote_embedding_batch_size", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.return_doc { + req_builder = req_builder.query(&[("return_doc", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.action { + req_builder = req_builder.query(&[("action", ¶m_value.to_string())]); } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref param_value) = params.dirty_values { + req_builder = req_builder.query(&[("dirty_values", ¶m_value.to_string())]); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - // was changed by hand - local_var_req_builder = local_var_req_builder.body(body); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - // was changed by hand - Ok(local_var_content) + req_builder = req_builder + .header(reqwest::header::CONTENT_TYPE, "text/plain") + .body(params.body.to_owned()); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json | ContentType::Text => return Ok(content), + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `String`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// A document to be indexed in a given collection must conform to the schema of the collection. pub async fn index_document( configuration: &configuration::Configuration, - collection_name: &str, - body: serde_json::Value, - action: Option<&str>, + params: &IndexDocumentParams, ) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + let uri_str = format!( "{}/collections/{collectionName}/documents", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - if let Some(ref local_var_str) = action { - local_var_req_builder = - local_var_req_builder.query(&[("action", &local_var_str.to_string())]); - } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref param_value) = params.action { + req_builder = req_builder.query(&[("action", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.dirty_values { + req_builder = req_builder.query(&[("dirty_values", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&body); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// This is especially useful to avoid round-trip network latencies incurred otherwise if each of these requests are sent in separate HTTP requests. You can also use this feature to do a federated search across multiple collections in a single HTTP request. -pub async fn multi_search serde::Deserialize<'d>>( +pub async fn multi_search( configuration: &configuration::Configuration, - multi_search_parameters: crate::models::MultiSearchParameters, - multi_search_searches_parameter: Option, -) -> Result, Error> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/multi_search", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - local_var_req_builder = local_var_req_builder.query(&multi_search_parameters); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + params: &MultiSearchParams, +) -> Result> { + let uri_str = format!("{}/multi_search", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref param_value) = params.q { + req_builder = req_builder.query(&[("q", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.query_by { + req_builder = req_builder.query(&[("query_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.query_by_weights { + req_builder = req_builder.query(&[("query_by_weights", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.text_match_type { + req_builder = req_builder.query(&[("text_match_type", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prefix { + req_builder = req_builder.query(&[("prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.infix { + req_builder = req_builder.query(&[("infix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_extra_prefix { + req_builder = req_builder.query(&[("max_extra_prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_extra_suffix { + req_builder = req_builder.query(&[("max_extra_suffix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.sort_by { + req_builder = req_builder.query(&[("sort_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_by { + req_builder = req_builder.query(&[("facet_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_facet_values { + req_builder = req_builder.query(&[("max_facet_values", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_query { + req_builder = req_builder.query(&[("facet_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.num_typos { + req_builder = req_builder.query(&[("num_typos", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.page { + req_builder = req_builder.query(&[("page", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.per_page { + req_builder = req_builder.query(&[("per_page", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.limit { + req_builder = req_builder.query(&[("limit", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.offset { + req_builder = req_builder.query(&[("offset", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_by { + req_builder = req_builder.query(&[("group_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_limit { + req_builder = req_builder.query(&[("group_limit", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_missing_values { + req_builder = req_builder.query(&[("group_missing_values", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.include_fields { + req_builder = req_builder.query(&[("include_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.exclude_fields { + req_builder = req_builder.query(&[("exclude_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_full_fields { + req_builder = req_builder.query(&[("highlight_full_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_affix_num_tokens { + req_builder = + req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_start_tag { + req_builder = req_builder.query(&[("highlight_start_tag", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_end_tag { + req_builder = req_builder.query(&[("highlight_end_tag", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.snippet_threshold { + req_builder = req_builder.query(&[("snippet_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.drop_tokens_threshold { + req_builder = req_builder.query(&[("drop_tokens_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.drop_tokens_mode { + req_builder = req_builder.query(&[("drop_tokens_mode", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.typo_tokens_threshold { + req_builder = req_builder.query(&[("typo_tokens_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_typos_for_alpha_numerical_tokens { + req_builder = req_builder.query(&[( + "enable_typos_for_alpha_numerical_tokens", + ¶m_value.to_string(), + )]); + } + if let Some(ref param_value) = params.filter_curated_hits { + req_builder = req_builder.query(&[("filter_curated_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_synonyms { + req_builder = req_builder.query(&[("enable_synonyms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_analytics { + req_builder = req_builder.query(&[("enable_analytics", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_prefix { + req_builder = req_builder.query(&[("synonym_prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_num_typos { + req_builder = req_builder.query(&[("synonym_num_typos", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.pinned_hits { + req_builder = req_builder.query(&[("pinned_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.hidden_hits { + req_builder = req_builder.query(&[("hidden_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.override_tags { + req_builder = req_builder.query(&[("override_tags", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_fields { + req_builder = req_builder.query(&[("highlight_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.pre_segmented_query { + req_builder = req_builder.query(&[("pre_segmented_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.preset { + req_builder = req_builder.query(&[("preset", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_overrides { + req_builder = req_builder.query(&[("enable_overrides", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_exact_match { + req_builder = req_builder.query(&[("prioritize_exact_match", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_token_position { + req_builder = req_builder.query(&[("prioritize_token_position", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_num_matching_fields { + req_builder = + req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_typos_for_numerical_tokens { + req_builder = req_builder.query(&[( + "enable_typos_for_numerical_tokens", + ¶m_value.to_string(), + )]); + } + if let Some(ref param_value) = params.exhaustive_search { + req_builder = req_builder.query(&[("exhaustive_search", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.search_cutoff_ms { + req_builder = req_builder.query(&[("search_cutoff_ms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.use_cache { + req_builder = req_builder.query(&[("use_cache", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.cache_ttl { + req_builder = req_builder.query(&[("cache_ttl", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.min_len_1typo { + req_builder = req_builder.query(&[("min_len_1typo", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.min_len_2typo { + req_builder = req_builder.query(&[("min_len_2typo", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.vector_query { + req_builder = req_builder.query(&[("vector_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_timeout_ms { + req_builder = + req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_num_tries { + req_builder = + req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_strategy { + req_builder = req_builder.query(&[("facet_strategy", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.stopwords { + req_builder = req_builder.query(&[("stopwords", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_return_parent { + req_builder = req_builder.query(&[("facet_return_parent", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.voice_query { + req_builder = req_builder.query(&[("voice_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation { + req_builder = req_builder.query(&[("conversation", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation_model_id { + req_builder = req_builder.query(&[("conversation_model_id", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation_id { + req_builder = req_builder.query(&[("conversation_id", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&multi_search_searches_parameter); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.multi_search_searches_parameter); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Search for documents in a collection that match the search criteria. -pub async fn search_collection serde::Deserialize<'d>>( +pub async fn search_collection serde::Deserialize<'de> + Serialize>( configuration: &configuration::Configuration, - collection_name: &str, - search_parameters: crate::models::SearchParameters, -) -> Result, Error> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &SearchCollectionParams, +) -> Result, Error> { + let uri_str = format!( "{}/collections/{collectionName}/documents/search", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - local_var_req_builder = local_var_req_builder.query(&search_parameters); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref param_value) = params.q { + req_builder = req_builder.query(&[("q", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.query_by { + req_builder = req_builder.query(&[("query_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.nl_query { + req_builder = req_builder.query(&[("nl_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.nl_model_id { + req_builder = req_builder.query(&[("nl_model_id", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.query_by_weights { + req_builder = req_builder.query(&[("query_by_weights", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.text_match_type { + req_builder = req_builder.query(&[("text_match_type", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prefix { + req_builder = req_builder.query(&[("prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.infix { + req_builder = req_builder.query(&[("infix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_extra_prefix { + req_builder = req_builder.query(&[("max_extra_prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_extra_suffix { + req_builder = req_builder.query(&[("max_extra_suffix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_filter_by_candidates { + req_builder = req_builder.query(&[("max_filter_by_candidates", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.sort_by { + req_builder = req_builder.query(&[("sort_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_by { + req_builder = req_builder.query(&[("facet_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_facet_values { + req_builder = req_builder.query(&[("max_facet_values", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_query { + req_builder = req_builder.query(&[("facet_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.num_typos { + req_builder = req_builder.query(&[("num_typos", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.page { + req_builder = req_builder.query(&[("page", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.per_page { + req_builder = req_builder.query(&[("per_page", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.limit { + req_builder = req_builder.query(&[("limit", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.offset { + req_builder = req_builder.query(&[("offset", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_by { + req_builder = req_builder.query(&[("group_by", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_limit { + req_builder = req_builder.query(&[("group_limit", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.group_missing_values { + req_builder = req_builder.query(&[("group_missing_values", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.include_fields { + req_builder = req_builder.query(&[("include_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.exclude_fields { + req_builder = req_builder.query(&[("exclude_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_full_fields { + req_builder = req_builder.query(&[("highlight_full_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_affix_num_tokens { + req_builder = + req_builder.query(&[("highlight_affix_num_tokens", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_start_tag { + req_builder = req_builder.query(&[("highlight_start_tag", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_end_tag { + req_builder = req_builder.query(&[("highlight_end_tag", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_highlight_v1 { + req_builder = req_builder.query(&[("enable_highlight_v1", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_analytics { + req_builder = req_builder.query(&[("enable_analytics", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.snippet_threshold { + req_builder = req_builder.query(&[("snippet_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_sets { + req_builder = req_builder.query(&[("synonym_sets", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.drop_tokens_threshold { + req_builder = req_builder.query(&[("drop_tokens_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.drop_tokens_mode { + req_builder = req_builder.query(&[("drop_tokens_mode", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.typo_tokens_threshold { + req_builder = req_builder.query(&[("typo_tokens_threshold", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_typos_for_alpha_numerical_tokens { + req_builder = req_builder.query(&[( + "enable_typos_for_alpha_numerical_tokens", + ¶m_value.to_string(), + )]); + } + if let Some(ref param_value) = params.filter_curated_hits { + req_builder = req_builder.query(&[("filter_curated_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_synonyms { + req_builder = req_builder.query(&[("enable_synonyms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_prefix { + req_builder = req_builder.query(&[("synonym_prefix", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.synonym_num_typos { + req_builder = req_builder.query(&[("synonym_num_typos", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.pinned_hits { + req_builder = req_builder.query(&[("pinned_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.hidden_hits { + req_builder = req_builder.query(&[("hidden_hits", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.override_tags { + req_builder = req_builder.query(&[("override_tags", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.highlight_fields { + req_builder = req_builder.query(&[("highlight_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.split_join_tokens { + req_builder = req_builder.query(&[("split_join_tokens", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.pre_segmented_query { + req_builder = req_builder.query(&[("pre_segmented_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.preset { + req_builder = req_builder.query(&[("preset", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_overrides { + req_builder = req_builder.query(&[("enable_overrides", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_exact_match { + req_builder = req_builder.query(&[("prioritize_exact_match", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.max_candidates { + req_builder = req_builder.query(&[("max_candidates", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_token_position { + req_builder = req_builder.query(&[("prioritize_token_position", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.prioritize_num_matching_fields { + req_builder = + req_builder.query(&[("prioritize_num_matching_fields", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.enable_typos_for_numerical_tokens { + req_builder = req_builder.query(&[( + "enable_typos_for_numerical_tokens", + ¶m_value.to_string(), + )]); + } + if let Some(ref param_value) = params.exhaustive_search { + req_builder = req_builder.query(&[("exhaustive_search", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.search_cutoff_ms { + req_builder = req_builder.query(&[("search_cutoff_ms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.use_cache { + req_builder = req_builder.query(&[("use_cache", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.cache_ttl { + req_builder = req_builder.query(&[("cache_ttl", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.min_len_1typo { + req_builder = req_builder.query(&[("min_len_1typo", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.min_len_2typo { + req_builder = req_builder.query(&[("min_len_2typo", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.vector_query { + req_builder = req_builder.query(&[("vector_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_timeout_ms { + req_builder = + req_builder.query(&[("remote_embedding_timeout_ms", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.remote_embedding_num_tries { + req_builder = + req_builder.query(&[("remote_embedding_num_tries", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_strategy { + req_builder = req_builder.query(&[("facet_strategy", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.stopwords { + req_builder = req_builder.query(&[("stopwords", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.facet_return_parent { + req_builder = req_builder.query(&[("facet_return_parent", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.voice_query { + req_builder = req_builder.query(&[("voice_query", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation { + req_builder = req_builder.query(&[("conversation", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation_model_id { + req_builder = req_builder.query(&[("conversation_model_id", ¶m_value.to_string())]); + } + if let Some(ref param_value) = params.conversation_id { + req_builder = req_builder.query(&[("conversation_id", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchResult`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchResult`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Update an individual document from a collection by using its ID. The update can be partial. pub async fn update_document( configuration: &configuration::Configuration, - collection_name: &str, - document_id: &str, - body: serde_json::Value, + params: &UpdateDocumentParams, ) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + let uri_str = format!( "{}/collections/{collectionName}/documents/{documentId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - documentId = crate::apis::urlencode(document_id) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name), + documentId = crate::apis::urlencode(¶ms.document_id) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PATCH, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + let mut req_builder = configuration + .client + .request(reqwest::Method::PATCH, &uri_str); + + if let Some(ref param_value) = params.dirty_values { + req_builder = req_builder.query(&[("dirty_values", ¶m_value.to_string())]); + } + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&body); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// The filter_by query parameter is used to filter to specify a condition against which the documents are matched. The request body contains the fields that should be updated for any documents that match the filter condition. This endpoint is only available if the Typesense server is version `0.25.0.rc12` or later. pub async fn update_documents( configuration: &configuration::Configuration, - collection_name: &str, - body: serde_json::Value, - update_documents_parameters: Option< - crate::models::UpdateDocumentsUpdateDocumentsParametersParameter, - >, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &UpdateDocumentsParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/documents", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PATCH, local_var_uri_str.as_str()); + let mut req_builder = configuration + .client + .request(reqwest::Method::PATCH, &uri_str); - if let Some(ref update_documents_parameters_ref) = update_documents_parameters { - local_var_req_builder = local_var_req_builder.query(&update_documents_parameters_ref); + if let Some(ref param_value) = params.filter_by { + req_builder = req_builder.query(&[("filter_by", ¶m_value.to_string())]); } - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&body); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::UpdateDocuments200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::UpdateDocuments200Response`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. pub async fn upsert_search_override( configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, - search_override_schema: crate::models::SearchOverrideSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &UpsertSearchOverrideParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name), + overrideId = crate::apis::urlencode(¶ms.override_id) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - local_var_req_builder = local_var_req_builder.json(&search_override_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } -} - -/// Create or update a synonym to define search terms that should be considered equivalent. -pub async fn upsert_search_synonym( - configuration: &configuration::Configuration, - collection_name: &str, - synonym_id: &str, - search_synonym_schema: crate::models::SearchSynonymSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/synonyms/{synonymId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - synonymId = crate::apis::urlencode(synonym_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&search_synonym_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.search_override_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } diff --git a/typesense_codegen/src/apis/health_api.rs b/typesense_codegen/src/apis/health_api.rs index 3930680..8cc1524 100644 --- a/typesense_codegen/src/apis/health_api.rs +++ b/typesense_codegen/src/apis/health_api.rs @@ -3,13 +3,15 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; /// struct for typed errors of method [`health`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -21,44 +23,55 @@ pub enum HealthError { /// Checks if Typesense server is ready to accept requests. pub async fn health( configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; +) -> Result> { + let uri_str = format!("{}/health", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/health", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::HealthStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::HealthStatus`" + )))); + } + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } diff --git a/typesense_codegen/src/apis/keys_api.rs b/typesense_codegen/src/apis/keys_api.rs index 084ed6c..c702492 100644 --- a/typesense_codegen/src/apis/keys_api.rs +++ b/typesense_codegen/src/apis/keys_api.rs @@ -3,20 +3,43 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; + +/// struct for passing parameters to the method [`create_key`] +#[derive(Clone, Debug)] +pub struct CreateKeyParams { + /// The object that describes API key scope + pub api_key_schema: Option, +} + +/// struct for passing parameters to the method [`delete_key`] +#[derive(Clone, Debug)] +pub struct DeleteKeyParams { + /// The ID of the key to delete + pub key_id: i64, +} + +/// struct for passing parameters to the method [`get_key`] +#[derive(Clone, Debug)] +pub struct GetKeyParams { + /// The ID of the key to retrieve + pub key_id: i64, +} /// struct for typed errors of method [`create_key`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum CreateKeyError { - Status400(crate::models::ApiResponse), - Status409(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status409(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -24,8 +47,8 @@ pub enum CreateKeyError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteKeyError { - Status400(crate::models::ApiResponse), - Status404(crate::models::ApiResponse), + Status400(models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -33,7 +56,7 @@ pub enum DeleteKeyError { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetKeyError { - Status404(crate::models::ApiResponse), + Status404(models::ApiResponse), UnknownValue(serde_json::Value), } @@ -47,191 +70,237 @@ pub enum GetKeysError { /// Create an API Key with fine-grain access control. You can restrict access on both a per-collection and per-action level. The generated key is returned only during creation. You want to store this key carefully in a secure place. pub async fn create_key( configuration: &configuration::Configuration, - api_key_schema: Option, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/keys", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + params: &CreateKeyParams, +) -> Result> { + let uri_str = format!("{}/keys", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - local_var_req_builder = local_var_req_builder.json(&api_key_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + req_builder = req_builder.json(¶ms.api_key_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiKey`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } pub async fn delete_key( configuration: &configuration::Configuration, - key_id: i64, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &DeleteKeyParams, +) -> Result> { + let uri_str = format!( "{}/keys/{keyId}", - local_var_configuration.base_path, - keyId = key_id + configuration.base_path, + keyId = params.key_id ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiKeyDeleteResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeyDeleteResponse`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Retrieve (metadata about) a key. Only the key prefix is returned when you retrieve a key. Due to security reasons, only the create endpoint returns the full API key. pub async fn get_key( configuration: &configuration::Configuration, - key_id: i64, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &GetKeyParams, +) -> Result> { + let uri_str = format!( "{}/keys/{keyId}", - local_var_configuration.base_path, - keyId = key_id + configuration.base_path, + keyId = params.key_id ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiKey`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKey`" + )))); + } + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } pub async fn get_keys( configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/keys", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); +) -> Result> { + let uri_str = format!("{}/keys", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiKeysResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiKeysResponse`" + )))); + } + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } diff --git a/typesense_codegen/src/apis/mod.rs b/typesense_codegen/src/apis/mod.rs index dd940c9..12bf0c1 100644 --- a/typesense_codegen/src/apis/mod.rs +++ b/typesense_codegen/src/apis/mod.rs @@ -1,5 +1,4 @@ -use std::error; -use std::fmt; +use std::{error, fmt}; #[derive(Debug, Clone)] pub struct ResponseContent { @@ -11,6 +10,8 @@ pub struct ResponseContent { #[derive(Debug)] pub enum Error { Reqwest(reqwest::Error), + #[cfg(not(target_family = "wasm"))] + ReqwestMiddleware(reqwest_middleware::Error), Serde(serde_json::Error), Io(std::io::Error), ResponseError(ResponseContent), @@ -20,6 +21,8 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let (module, e) = match self { Error::Reqwest(e) => ("reqwest", e.to_string()), + #[cfg(not(target_family = "wasm"))] + Error::ReqwestMiddleware(e) => ("reqwest-middleware", e.to_string()), Error::Serde(e) => ("serde", e.to_string()), Error::Io(e) => ("IO", e.to_string()), Error::ResponseError(e) => ("response", format!("status code {}", e.status)), @@ -32,6 +35,8 @@ impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { Some(match self { Error::Reqwest(e) => e, + #[cfg(not(target_family = "wasm"))] + Error::ReqwestMiddleware(e) => e, Error::Serde(e) => e, Error::Io(e) => e, Error::ResponseError(_) => return None, @@ -45,6 +50,13 @@ impl From for Error { } } +#[cfg(not(target_family = "wasm"))] +impl From for Error { + fn from(e: reqwest_middleware::Error) -> Self { + Error::ReqwestMiddleware(e) + } +} + impl From for Error { fn from(e: serde_json::Error) -> Self { Error::Serde(e) @@ -91,14 +103,41 @@ pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String unimplemented!("Only objects are supported with style=deepObject") } +/// Internal use only +/// A content type supported by this client. +#[allow(dead_code)] +enum ContentType { + Json, + Text, + Unsupported(String), +} + +impl From<&str> for ContentType { + fn from(content_type: &str) -> Self { + if content_type.starts_with("application") && content_type.contains("json") { + return Self::Json; + } else if content_type.starts_with("text/plain") { + return Self::Text; + } else { + return Self::Unsupported(content_type.to_string()); + } + } +} + pub mod analytics_api; pub mod collections_api; +pub mod conversations_api; +pub mod curation_api; pub mod debug_api; pub mod documents_api; pub mod health_api; pub mod keys_api; +pub mod nl_search_models_api; pub mod operations_api; pub mod override_api; -pub mod promote_api; +pub mod presets_api; +pub mod stemming_api; +pub mod stopwords_api; +pub mod synonyms_api; pub mod configuration; diff --git a/typesense_codegen/src/apis/nl_search_models_api.rs b/typesense_codegen/src/apis/nl_search_models_api.rs new file mode 100644 index 0000000..5458cbb --- /dev/null +++ b/typesense_codegen/src/apis/nl_search_models_api.rs @@ -0,0 +1,386 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; + +/// struct for passing parameters to the method [`create_nl_search_model`] +#[derive(Clone, Debug)] +pub struct CreateNlSearchModelParams { + /// The NL search model to be created + pub nl_search_model_create_schema: models::NlSearchModelCreateSchema, +} + +/// struct for passing parameters to the method [`delete_nl_search_model`] +#[derive(Clone, Debug)] +pub struct DeleteNlSearchModelParams { + /// The ID of the NL search model to delete + pub model_id: String, +} + +/// struct for passing parameters to the method [`retrieve_nl_search_model`] +#[derive(Clone, Debug)] +pub struct RetrieveNlSearchModelParams { + /// The ID of the NL search model to retrieve + pub model_id: String, +} + +/// struct for passing parameters to the method [`update_nl_search_model`] +#[derive(Clone, Debug)] +pub struct UpdateNlSearchModelParams { + /// The ID of the NL search model to update + pub model_id: String, + /// The NL search model fields to update + pub body: models::NlSearchModelCreateSchema, +} + +/// struct for typed errors of method [`create_nl_search_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateNlSearchModelError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`delete_nl_search_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteNlSearchModelError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_all_nl_search_models`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveAllNlSearchModelsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_nl_search_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveNlSearchModelError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`update_nl_search_model`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpdateNlSearchModelError { + Status400(models::ApiResponse), + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// Create a new NL search model. +pub async fn create_nl_search_model( + configuration: &configuration::Configuration, + params: &CreateNlSearchModelParams, +) -> Result> { + let uri_str = format!("{}/nl_search_models", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.nl_search_model_create_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Delete a specific NL search model by its ID. +pub async fn delete_nl_search_model( + configuration: &configuration::Configuration, + params: &DeleteNlSearchModelParams, +) -> Result> { + let uri_str = format!( + "{}/nl_search_models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(¶ms.model_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelDeleteSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve all NL search models. +pub async fn retrieve_all_nl_search_models( + configuration: &configuration::Configuration, +) -> Result, Error> { + let uri_str = format!("{}/nl_search_models", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve a specific NL search model by its ID. +pub async fn retrieve_nl_search_model( + configuration: &configuration::Configuration, + params: &RetrieveNlSearchModelParams, +) -> Result> { + let uri_str = format!( + "{}/nl_search_models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(¶ms.model_id) + ); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Update an existing NL search model. +pub async fn update_nl_search_model( + configuration: &configuration::Configuration, + params: &UpdateNlSearchModelParams, +) -> Result> { + let uri_str = format!( + "{}/nl_search_models/{modelId}", + configuration.base_path, + modelId = crate::apis::urlencode(¶ms.model_id) + ); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::NlSearchModelSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::NlSearchModelSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} diff --git a/typesense_codegen/src/apis/operations_api.rs b/typesense_codegen/src/apis/operations_api.rs index 0c2adc3..8a1b91d 100644 --- a/typesense_codegen/src/apis/operations_api.rs +++ b/typesense_codegen/src/apis/operations_api.rs @@ -3,13 +3,63 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; + +/// struct for passing parameters to the method [`take_snapshot`] +#[derive(Clone, Debug)] +pub struct TakeSnapshotParams { + /// The directory on the server where the snapshot should be saved. + pub snapshot_path: String, +} + +/// struct for passing parameters to the method [`toggle_slow_request_log`] +#[derive(Clone, Debug)] +pub struct ToggleSlowRequestLogParams { + pub toggle_slow_request_log_request: Option, +} + +/// struct for typed errors of method [`clear_cache`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ClearCacheError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`compact_db`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CompactDbError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_schema_changes`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetSchemaChangesError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_api_stats`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveApiStatsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_metrics`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveMetricsError { + UnknownValue(serde_json::Value), +} /// struct for typed errors of method [`take_snapshot`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -18,6 +68,13 @@ pub enum TakeSnapshotError { UnknownValue(serde_json::Value), } +/// struct for typed errors of method [`toggle_slow_request_log`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ToggleSlowRequestLogError { + UnknownValue(serde_json::Value), +} + /// struct for typed errors of method [`vote`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -25,96 +82,464 @@ pub enum VoteError { UnknownValue(serde_json::Value), } +/// Clear the cached responses of search requests that are sent with `use_cache` parameter in the LRU cache. +pub async fn clear_cache( + configuration: &configuration::Configuration, +) -> Result> { + let uri_str = format!("{}/operations/cache/clear", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// 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. +pub async fn compact_db( + configuration: &configuration::Configuration, +) -> Result> { + let uri_str = format!("{}/operations/db/compact", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Returns the status of any ongoing schema change operations. If no schema changes are in progress, returns an empty response. +pub async fn get_schema_changes( + configuration: &configuration::Configuration, +) -> Result, Error> { + let uri_str = format!("{}/operations/schema_changes", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve the stats about API endpoints. +pub async fn retrieve_api_stats( + configuration: &configuration::Configuration, +) -> Result> { + let uri_str = format!("{}/stats.json", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ApiStatsResponse`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ApiStatsResponse`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve the metrics. +pub async fn retrieve_metrics( + configuration: &configuration::Configuration, +) -> Result> { + let uri_str = format!("{}/metrics.json", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `serde_json::Value`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + /// Creates a point-in-time snapshot of a Typesense node's state and data in the specified directory. You can then backup the snapshot directory that gets created and later restore it as a data directory, as needed. pub async fn take_snapshot( configuration: &configuration::Configuration, - snapshot_path: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/operations/snapshot", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - local_var_req_builder = - local_var_req_builder.query(&[("snapshot_path", &snapshot_path.to_string())]); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + params: &TakeSnapshotParams, +) -> Result> { + let uri_str = format!("{}/operations/snapshot", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + req_builder = req_builder.query(&[("snapshot_path", ¶ms.snapshot_path.to_string())]); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// 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. +pub async fn toggle_slow_request_log( + configuration: &configuration::Configuration, + params: &ToggleSlowRequestLogParams, +) -> Result> { + let uri_str = format!("{}/config", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - Err(Error::ResponseError(local_var_error)) + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.toggle_slow_request_log_request); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } /// Triggers a follower node to initiate the raft voting process, which triggers leader re-election. The follower node that you run this operation against will become the new leader, once this command succeeds. pub async fn vote( configuration: &configuration::Configuration, -) -> Result> { - let local_var_configuration = configuration; +) -> Result> { + let uri_str = format!("{}/operations/vote", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!("{}/operations/vote", local_var_configuration.base_path); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SuccessStatus`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SuccessStatus`" + )))); + } + } } else { - let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } diff --git a/typesense_codegen/src/apis/override_api.rs b/typesense_codegen/src/apis/override_api.rs index 1cad7a8..9eadf5a 100644 --- a/typesense_codegen/src/apis/override_api.rs +++ b/typesense_codegen/src/apis/override_api.rs @@ -3,13 +3,24 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ -use super::{Error, configuration}; -use crate::apis::ResponseContent; +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; + +/// struct for passing parameters to the method [`get_search_override`] +#[derive(Clone, Debug)] +pub struct GetSearchOverrideParams { + /// The name of the collection + pub collection_name: String, + /// The id of the search override + pub override_id: String, +} /// struct for typed errors of method [`get_search_override`] #[derive(Debug, Clone, Serialize, Deserialize)] @@ -21,52 +32,61 @@ pub enum GetSearchOverrideError { /// Retrieve the details of a search override, given its id. pub async fn get_search_override( configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( + params: &GetSearchOverrideParams, +) -> Result> { + let uri_str = format!( "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) + configuration.base_path, + collectionName = crate::apis::urlencode(¶ms.collection_name), + overrideId = crate::apis::urlencode(¶ms.override_id) ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); }; - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SearchOverride`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SearchOverride`" + )))); + } + } } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) } } diff --git a/typesense_codegen/src/apis/presets_api.rs b/typesense_codegen/src/apis/presets_api.rs new file mode 100644 index 0000000..8b296b2 --- /dev/null +++ b/typesense_codegen/src/apis/presets_api.rs @@ -0,0 +1,310 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; + +/// struct for passing parameters to the method [`delete_preset`] +#[derive(Clone, Debug)] +pub struct DeletePresetParams { + /// The ID of the preset to delete. + pub preset_id: String, +} + +/// struct for passing parameters to the method [`retrieve_preset`] +#[derive(Clone, Debug)] +pub struct RetrievePresetParams { + /// The ID of the preset to retrieve. + pub preset_id: String, +} + +/// struct for passing parameters to the method [`upsert_preset`] +#[derive(Clone, Debug)] +pub struct UpsertPresetParams { + /// The name of the preset set to upsert. + pub preset_id: String, + /// The stopwords set to upsert. + pub preset_upsert_schema: models::PresetUpsertSchema, +} + +/// struct for typed errors of method [`delete_preset`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeletePresetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_all_presets`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveAllPresetsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_preset`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrievePresetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`upsert_preset`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertPresetError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// Permanently deletes a preset, given it's name. +pub async fn delete_preset( + configuration: &configuration::Configuration, + params: &DeletePresetParams, +) -> Result> { + let uri_str = format!( + "{}/presets/{presetId}", + configuration.base_path, + presetId = crate::apis::urlencode(¶ms.preset_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::PresetDeleteSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::PresetDeleteSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve the details of all presets +pub async fn retrieve_all_presets( + configuration: &configuration::Configuration, +) -> Result> { + let uri_str = format!("{}/presets", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::PresetsRetrieveSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::PresetsRetrieveSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve the details of a preset, given it's name. +pub async fn retrieve_preset( + configuration: &configuration::Configuration, + params: &RetrievePresetParams, +) -> Result> { + let uri_str = format!( + "{}/presets/{presetId}", + configuration.base_path, + presetId = crate::apis::urlencode(¶ms.preset_id) + ); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::PresetSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Create or update an existing preset. +pub async fn upsert_preset( + configuration: &configuration::Configuration, + params: &UpsertPresetParams, +) -> Result> { + let uri_str = format!( + "{}/presets/{presetId}", + configuration.base_path, + presetId = crate::apis::urlencode(¶ms.preset_id) + ); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.preset_upsert_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::PresetSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::PresetSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} diff --git a/typesense_codegen/src/apis/promote_api.rs b/typesense_codegen/src/apis/promote_api.rs deleted file mode 100644 index 55a2c7e..0000000 --- a/typesense_codegen/src/apis/promote_api.rs +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -use super::{Error, configuration}; -use crate::apis::ResponseContent; - -/// struct for typed errors of method [`delete_search_override`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum DeleteSearchOverrideError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`get_search_overrides`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum GetSearchOverridesError { - UnknownValue(serde_json::Value), -} - -/// struct for typed errors of method [`upsert_search_override`] -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum UpsertSearchOverrideError { - Status404(crate::models::ApiResponse), - UnknownValue(serde_json::Value), -} - -pub async fn delete_search_override( - configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) - } -} - -pub async fn get_search_overrides( - configuration: &configuration::Configuration, - collection_name: &str, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) - } -} - -/// Create or update an override to promote certain documents over others. Using overrides, you can include or exclude specific documents for a given query. -pub async fn upsert_search_override( - configuration: &configuration::Configuration, - collection_name: &str, - override_id: &str, - search_override_schema: crate::models::SearchOverrideSchema, -) -> Result> { - let local_var_configuration = configuration; - - let local_var_client = &local_var_configuration.client; - - let local_var_uri_str = format!( - "{}/collections/{collectionName}/overrides/{overrideId}", - local_var_configuration.base_path, - collectionName = crate::apis::urlencode(collection_name), - overrideId = crate::apis::urlencode(override_id) - ); - let mut local_var_req_builder = - local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); - - if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { - local_var_req_builder = - local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent); - } - if let Some(ref local_var_apikey) = local_var_configuration.api_key { - let local_var_key = &local_var_apikey.key; - let local_var_value = match local_var_apikey.prefix { - Some(ref local_var_prefix) => format!("{local_var_prefix} {local_var_key}"), - None => local_var_key.clone(), - }; - local_var_req_builder = - local_var_req_builder.header("X-TYPESENSE-API-KEY", local_var_value); - }; - local_var_req_builder = local_var_req_builder.json(&search_override_schema); - - let local_var_req = local_var_req_builder.build()?; - let local_var_resp = local_var_client.execute(local_var_req).await?; - - let local_var_status = local_var_resp.status(); - let local_var_content = local_var_resp.text().await?; - - if !local_var_status.is_client_error() && !local_var_status.is_server_error() { - serde_json::from_str(&local_var_content).map_err(Error::from) - } else { - let local_var_entity: Option = - serde_json::from_str(&local_var_content).ok(); - let local_var_error = ResponseContent { - status: local_var_status, - content: local_var_content, - entity: local_var_entity, - }; - Err(Error::ResponseError(local_var_error)) - } -} diff --git a/typesense_codegen/src/apis/stemming_api.rs b/typesense_codegen/src/apis/stemming_api.rs new file mode 100644 index 0000000..cd5e9cb --- /dev/null +++ b/typesense_codegen/src/apis/stemming_api.rs @@ -0,0 +1,231 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; + +/// struct for passing parameters to the method [`get_stemming_dictionary`] +#[derive(Clone, Debug)] +pub struct GetStemmingDictionaryParams { + /// The ID of the dictionary to retrieve + pub dictionary_id: String, +} + +/// struct for passing parameters to the method [`import_stemming_dictionary`] +#[derive(Clone, Debug)] +pub struct ImportStemmingDictionaryParams { + /// The ID to assign to the dictionary + pub id: String, + /// The JSONL file containing word mappings + pub body: String, +} + +/// struct for typed errors of method [`get_stemming_dictionary`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetStemmingDictionaryError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`import_stemming_dictionary`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ImportStemmingDictionaryError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`list_stemming_dictionaries`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ListStemmingDictionariesError { + UnknownValue(serde_json::Value), +} + +/// Fetch details of a specific stemming dictionary. +pub async fn get_stemming_dictionary( + configuration: &configuration::Configuration, + params: &GetStemmingDictionaryParams, +) -> Result> { + let uri_str = format!( + "{}/stemming/dictionaries/{dictionaryId}", + configuration.base_path, + dictionaryId = crate::apis::urlencode(¶ms.dictionary_id) + ); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::StemmingDictionary`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::StemmingDictionary`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Upload a JSONL file containing word mappings to create or update a stemming dictionary. +pub async fn import_stemming_dictionary( + configuration: &configuration::Configuration, + params: &ImportStemmingDictionaryParams, +) -> Result> { + let uri_str = format!("{}/stemming/dictionaries/import", configuration.base_path); + let mut req_builder = configuration + .client + .request(reqwest::Method::POST, &uri_str); + + req_builder = req_builder.query(&[("id", ¶ms.id.to_string())]); + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.body); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `String`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `String`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve a list of all available stemming dictionaries. +pub async fn list_stemming_dictionaries( + configuration: &configuration::Configuration, +) -> Result> { + let uri_str = format!("{}/stemming/dictionaries", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::ListStemmingDictionaries200Response`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} diff --git a/typesense_codegen/src/apis/stopwords_api.rs b/typesense_codegen/src/apis/stopwords_api.rs new file mode 100644 index 0000000..76c120b --- /dev/null +++ b/typesense_codegen/src/apis/stopwords_api.rs @@ -0,0 +1,310 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; + +/// struct for passing parameters to the method [`delete_stopwords_set`] +#[derive(Clone, Debug)] +pub struct DeleteStopwordsSetParams { + /// The ID of the stopwords set to delete. + pub set_id: String, +} + +/// struct for passing parameters to the method [`retrieve_stopwords_set`] +#[derive(Clone, Debug)] +pub struct RetrieveStopwordsSetParams { + /// The ID of the stopwords set to retrieve. + pub set_id: String, +} + +/// struct for passing parameters to the method [`upsert_stopwords_set`] +#[derive(Clone, Debug)] +pub struct UpsertStopwordsSetParams { + /// The ID of the stopwords set to upsert. + pub set_id: String, + /// The stopwords set to upsert. + pub stopwords_set_upsert_schema: models::StopwordsSetUpsertSchema, +} + +/// struct for typed errors of method [`delete_stopwords_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteStopwordsSetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_stopwords_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveStopwordsSetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_stopwords_sets`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveStopwordsSetsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`upsert_stopwords_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertStopwordsSetError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// Permanently deletes a stopwords set, given it's name. +pub async fn delete_stopwords_set( + configuration: &configuration::Configuration, + params: &DeleteStopwordsSetParams, +) -> Result> { + let uri_str = format!( + "{}/stopwords/{setId}", + configuration.base_path, + setId = crate::apis::urlencode(¶ms.set_id) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::DeleteStopwordsSet200Response`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve the details of a stopwords set, given it's name. +pub async fn retrieve_stopwords_set( + configuration: &configuration::Configuration, + params: &RetrieveStopwordsSetParams, +) -> Result> { + let uri_str = format!( + "{}/stopwords/{setId}", + configuration.base_path, + setId = crate::apis::urlencode(¶ms.set_id) + ); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetRetrieveSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve the details of all stopwords sets +pub async fn retrieve_stopwords_sets( + configuration: &configuration::Configuration, +) -> Result> { + let uri_str = format!("{}/stopwords", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetsRetrieveAllSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// When an analytics rule is created, we give it a name and describe the type, the source collections and the destination collection. +pub async fn upsert_stopwords_set( + configuration: &configuration::Configuration, + params: &UpsertStopwordsSetParams, +) -> Result> { + let uri_str = format!( + "{}/stopwords/{setId}", + configuration.base_path, + setId = crate::apis::urlencode(¶ms.set_id) + ); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.stopwords_set_upsert_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::StopwordsSetSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::StopwordsSetSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} diff --git a/typesense_codegen/src/apis/synonyms_api.rs b/typesense_codegen/src/apis/synonyms_api.rs new file mode 100644 index 0000000..90777fa --- /dev/null +++ b/typesense_codegen/src/apis/synonyms_api.rs @@ -0,0 +1,310 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use super::{ContentType, Error, configuration}; +use crate::{apis::ResponseContent, models}; +use reqwest; +use serde::{Deserialize, Serialize, de::Error as _}; + +/// struct for passing parameters to the method [`delete_synonym_set`] +#[derive(Clone, Debug)] +pub struct DeleteSynonymSetParams { + /// The name of the synonym set to delete + pub synonym_set_name: String, +} + +/// struct for passing parameters to the method [`retrieve_synonym_set`] +#[derive(Clone, Debug)] +pub struct RetrieveSynonymSetParams { + /// The name of the synonym set to retrieve + pub synonym_set_name: String, +} + +/// struct for passing parameters to the method [`upsert_synonym_set`] +#[derive(Clone, Debug)] +pub struct UpsertSynonymSetParams { + /// The name of the synonym set to create/update + pub synonym_set_name: String, + /// The synonym set to be created/updated + pub synonym_set_create_schema: models::SynonymSetCreateSchema, +} + +/// struct for typed errors of method [`delete_synonym_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteSynonymSetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_synonym_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveSynonymSetError { + Status404(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`retrieve_synonym_sets`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RetrieveSynonymSetsError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`upsert_synonym_set`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UpsertSynonymSetError { + Status400(models::ApiResponse), + UnknownValue(serde_json::Value), +} + +/// Delete a specific synonym set by its name +pub async fn delete_synonym_set( + configuration: &configuration::Configuration, + params: &DeleteSynonymSetParams, +) -> Result> { + let uri_str = format!( + "{}/synonym_sets/{synonymSetName}", + configuration.base_path, + synonymSetName = crate::apis::urlencode(¶ms.synonym_set_name) + ); + let mut req_builder = configuration + .client + .request(reqwest::Method::DELETE, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SynonymSetDeleteSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetDeleteSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve a specific synonym set by its name +pub async fn retrieve_synonym_set( + configuration: &configuration::Configuration, + params: &RetrieveSynonymSetParams, +) -> Result> { + let uri_str = format!( + "{}/synonym_sets/{synonymSetName}", + configuration.base_path, + synonymSetName = crate::apis::urlencode(¶ms.synonym_set_name) + ); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SynonymSetCreateSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetCreateSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Retrieve all synonym sets +pub async fn retrieve_synonym_sets( + configuration: &configuration::Configuration, +) -> Result, Error> { + let uri_str = format!("{}/synonym_sets", configuration.base_path); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `Vec`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `Vec`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} + +/// Create or update a synonym set with the given name +pub async fn upsert_synonym_set( + configuration: &configuration::Configuration, + params: &UpsertSynonymSetParams, +) -> Result> { + let uri_str = format!( + "{}/synonym_sets/{synonymSetName}", + configuration.base_path, + synonymSetName = crate::apis::urlencode(¶ms.synonym_set_name) + ); + let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + if let Some(ref apikey) = configuration.api_key { + let key = &apikey.key; + let value = match apikey.prefix { + Some(ref prefix) => &format!("{prefix} {key}"), + None => key, + }; + req_builder = req_builder.header("X-TYPESENSE-API-KEY", value); + }; + req_builder = req_builder.json(¶ms.synonym_set_create_schema); + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => { + return Err(Error::from(serde_json::Error::custom( + "Received `text/plain` content type response that cannot be converted to `models::SynonymSetSchema`", + ))); + } + ContentType::Unsupported(unknown_type) => { + return Err(Error::from(serde_json::Error::custom(format!( + "Received `{unknown_type}` content type response that cannot be converted to `models::SynonymSetSchema`" + )))); + } + } + } else { + let content = resp.text().await?; + let entity: Option = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { + status, + content, + entity, + })) + } +} diff --git a/typesense_codegen/src/lib.rs b/typesense_codegen/src/lib.rs index 4c8b05d..d9c227b 100644 --- a/typesense_codegen/src/lib.rs +++ b/typesense_codegen/src/lib.rs @@ -1,5 +1,7 @@ -#[macro_use] -extern crate serde_derive; +#![allow(unused_imports)] +#![allow(clippy::empty_docs)] +#![allow(clippy::needless_return)] +#![allow(elided_lifetimes_in_paths)] pub mod apis; pub mod models; diff --git a/typesense_codegen/src/models/analytics_event.rs b/typesense_codegen/src/models/analytics_event.rs new file mode 100644 index 0000000..7ab05e0 --- /dev/null +++ b/typesense_codegen/src/models/analytics_event.rs @@ -0,0 +1,38 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsEvent { + /// Name of the analytics rule this event corresponds to + #[serde(rename = "name")] + pub name: String, + /// Type of event (e.g., click, conversion, query, visit) + #[serde(rename = "event_type")] + pub event_type: String, + #[serde(rename = "data")] + pub data: Box, +} + +impl AnalyticsEvent { + pub fn new( + name: String, + event_type: String, + data: models::AnalyticsEventData, + ) -> AnalyticsEvent { + AnalyticsEvent { + name, + event_type, + data: Box::new(data), + } + } +} diff --git a/typesense_codegen/src/models/analytics_event_create_response.rs b/typesense_codegen/src/models/analytics_event_create_response.rs new file mode 100644 index 0000000..2018290 --- /dev/null +++ b/typesense_codegen/src/models/analytics_event_create_response.rs @@ -0,0 +1,24 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsEventCreateResponse { + #[serde(rename = "ok")] + pub ok: bool, +} + +impl AnalyticsEventCreateResponse { + pub fn new(ok: bool) -> AnalyticsEventCreateResponse { + AnalyticsEventCreateResponse { ok } + } +} diff --git a/typesense_codegen/src/models/analytics_event_data.rs b/typesense_codegen/src/models/analytics_event_data.rs new file mode 100644 index 0000000..7c28241 --- /dev/null +++ b/typesense_codegen/src/models/analytics_event_data.rs @@ -0,0 +1,40 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// AnalyticsEventData : Event payload +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsEventData { + #[serde(rename = "user_id", skip_serializing_if = "Option::is_none")] + pub user_id: Option, + #[serde(rename = "doc_id", skip_serializing_if = "Option::is_none")] + pub doc_id: Option, + #[serde(rename = "doc_ids", skip_serializing_if = "Option::is_none")] + pub doc_ids: Option>, + #[serde(rename = "q", skip_serializing_if = "Option::is_none")] + pub q: Option, + #[serde(rename = "analytics_tag", skip_serializing_if = "Option::is_none")] + pub analytics_tag: Option, +} + +impl AnalyticsEventData { + /// Event payload + pub fn new() -> AnalyticsEventData { + AnalyticsEventData { + user_id: None, + doc_id: None, + doc_ids: None, + q: None, + analytics_tag: None, + } + } +} diff --git a/typesense_codegen/src/models/analytics_events_response.rs b/typesense_codegen/src/models/analytics_events_response.rs new file mode 100644 index 0000000..a0de4e0 --- /dev/null +++ b/typesense_codegen/src/models/analytics_events_response.rs @@ -0,0 +1,24 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsEventsResponse { + #[serde(rename = "events")] + pub events: Vec, +} + +impl AnalyticsEventsResponse { + pub fn new(events: Vec) -> AnalyticsEventsResponse { + AnalyticsEventsResponse { events } + } +} diff --git a/typesense_codegen/src/models/analytics_events_response_events_inner.rs b/typesense_codegen/src/models/analytics_events_response_events_inner.rs new file mode 100644 index 0000000..9744a20 --- /dev/null +++ b/typesense_codegen/src/models/analytics_events_response_events_inner.rs @@ -0,0 +1,47 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsEventsResponseEventsInner { + #[serde(rename = "name", skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(rename = "event_type", skip_serializing_if = "Option::is_none")] + pub event_type: Option, + #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] + pub collection: Option, + #[serde(rename = "timestamp", skip_serializing_if = "Option::is_none")] + pub timestamp: Option, + #[serde(rename = "user_id", skip_serializing_if = "Option::is_none")] + pub user_id: Option, + #[serde(rename = "doc_id", skip_serializing_if = "Option::is_none")] + pub doc_id: Option, + #[serde(rename = "doc_ids", skip_serializing_if = "Option::is_none")] + pub doc_ids: Option>, + #[serde(rename = "query", skip_serializing_if = "Option::is_none")] + pub query: Option, +} + +impl AnalyticsEventsResponseEventsInner { + pub fn new() -> AnalyticsEventsResponseEventsInner { + AnalyticsEventsResponseEventsInner { + name: None, + event_type: None, + collection: None, + timestamp: None, + user_id: None, + doc_id: None, + doc_ids: None, + query: None, + } + } +} diff --git a/typesense_codegen/src/models/analytics_rule.rs b/typesense_codegen/src/models/analytics_rule.rs new file mode 100644 index 0000000..4c01197 --- /dev/null +++ b/typesense_codegen/src/models/analytics_rule.rs @@ -0,0 +1,64 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsRule { + #[serde(rename = "name")] + pub name: String, + #[serde(rename = "type")] + pub r#type: Type, + #[serde(rename = "collection")] + pub collection: String, + #[serde(rename = "event_type")] + pub event_type: String, + #[serde(rename = "rule_tag", skip_serializing_if = "Option::is_none")] + pub rule_tag: Option, + #[serde(rename = "params", skip_serializing_if = "Option::is_none")] + pub params: Option>, +} + +impl AnalyticsRule { + pub fn new( + name: String, + r#type: Type, + collection: String, + event_type: String, + ) -> AnalyticsRule { + AnalyticsRule { + name, + r#type, + collection, + event_type, + rule_tag: None, + params: None, + } + } +} +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Type { + #[serde(rename = "popular_queries")] + PopularQueries, + #[serde(rename = "nohits_queries")] + NohitsQueries, + #[serde(rename = "counter")] + Counter, + #[serde(rename = "log")] + Log, +} + +impl Default for Type { + fn default() -> Type { + Self::PopularQueries + } +} diff --git a/typesense_codegen/src/models/analytics_rule_create.rs b/typesense_codegen/src/models/analytics_rule_create.rs new file mode 100644 index 0000000..b9f8993 --- /dev/null +++ b/typesense_codegen/src/models/analytics_rule_create.rs @@ -0,0 +1,64 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsRuleCreate { + #[serde(rename = "name")] + pub name: String, + #[serde(rename = "type")] + pub r#type: Type, + #[serde(rename = "collection")] + pub collection: String, + #[serde(rename = "event_type")] + pub event_type: String, + #[serde(rename = "rule_tag", skip_serializing_if = "Option::is_none")] + pub rule_tag: Option, + #[serde(rename = "params", skip_serializing_if = "Option::is_none")] + pub params: Option>, +} + +impl AnalyticsRuleCreate { + pub fn new( + name: String, + r#type: Type, + collection: String, + event_type: String, + ) -> AnalyticsRuleCreate { + AnalyticsRuleCreate { + name, + r#type, + collection, + event_type, + rule_tag: None, + params: None, + } + } +} +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Type { + #[serde(rename = "popular_queries")] + PopularQueries, + #[serde(rename = "nohits_queries")] + NohitsQueries, + #[serde(rename = "counter")] + Counter, + #[serde(rename = "log")] + Log, +} + +impl Default for Type { + fn default() -> Type { + Self::PopularQueries + } +} diff --git a/typesense_codegen/src/models/analytics_rule_create_params.rs b/typesense_codegen/src/models/analytics_rule_create_params.rs new file mode 100644 index 0000000..6127dd3 --- /dev/null +++ b/typesense_codegen/src/models/analytics_rule_create_params.rs @@ -0,0 +1,50 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsRuleCreateParams { + #[serde( + rename = "destination_collection", + skip_serializing_if = "Option::is_none" + )] + pub destination_collection: Option, + #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] + pub limit: Option, + #[serde( + rename = "capture_search_requests", + skip_serializing_if = "Option::is_none" + )] + pub capture_search_requests: Option, + #[serde(rename = "meta_fields", skip_serializing_if = "Option::is_none")] + pub meta_fields: Option>, + #[serde(rename = "expand_query", skip_serializing_if = "Option::is_none")] + pub expand_query: Option, + #[serde(rename = "counter_field", skip_serializing_if = "Option::is_none")] + pub counter_field: Option, + #[serde(rename = "weight", skip_serializing_if = "Option::is_none")] + pub weight: Option, +} + +impl AnalyticsRuleCreateParams { + pub fn new() -> AnalyticsRuleCreateParams { + AnalyticsRuleCreateParams { + destination_collection: None, + limit: None, + capture_search_requests: None, + meta_fields: None, + expand_query: None, + counter_field: None, + weight: None, + } + } +} diff --git a/typesense_codegen/src/models/analytics_rule_parameters.rs b/typesense_codegen/src/models/analytics_rule_parameters.rs deleted file mode 100644 index 32b4de4..0000000 --- a/typesense_codegen/src/models/analytics_rule_parameters.rs +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct AnalyticsRuleParameters { - #[serde(rename = "source")] - pub source: Box, - #[serde(rename = "destination")] - pub destination: Box, - #[serde(rename = "limit")] - pub limit: i32, -} - -impl AnalyticsRuleParameters { - pub fn new( - source: crate::models::AnalyticsRuleParametersSource, - destination: crate::models::AnalyticsRuleParametersDestination, - limit: i32, - ) -> AnalyticsRuleParameters { - AnalyticsRuleParameters { - source: Box::new(source), - destination: Box::new(destination), - limit, - } - } -} diff --git a/typesense_codegen/src/models/analytics_rule_parameters_destination.rs b/typesense_codegen/src/models/analytics_rule_parameters_destination.rs deleted file mode 100644 index b713af8..0000000 --- a/typesense_codegen/src/models/analytics_rule_parameters_destination.rs +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct AnalyticsRuleParametersDestination { - #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] - pub collection: Option, -} - -impl AnalyticsRuleParametersDestination { - pub fn new() -> AnalyticsRuleParametersDestination { - AnalyticsRuleParametersDestination { collection: None } - } -} diff --git a/typesense_codegen/src/models/analytics_rule_parameters_source.rs b/typesense_codegen/src/models/analytics_rule_parameters_source.rs deleted file mode 100644 index ae055fa..0000000 --- a/typesense_codegen/src/models/analytics_rule_parameters_source.rs +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct AnalyticsRuleParametersSource { - #[serde(rename = "collections", skip_serializing_if = "Option::is_none")] - pub collections: Option>, -} - -impl AnalyticsRuleParametersSource { - pub fn new() -> AnalyticsRuleParametersSource { - AnalyticsRuleParametersSource { collections: None } - } -} diff --git a/typesense_codegen/src/models/analytics_rule_schema.rs b/typesense_codegen/src/models/analytics_rule_schema.rs deleted file mode 100644 index 4d9c266..0000000 --- a/typesense_codegen/src/models/analytics_rule_schema.rs +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct AnalyticsRuleSchema { - #[serde(rename = "name")] - pub name: String, - #[serde(rename = "type")] - pub r#type: String, - #[serde(rename = "params")] - pub params: Box, -} - -impl AnalyticsRuleSchema { - pub fn new( - name: String, - r#type: String, - params: crate::models::AnalyticsRuleParameters, - ) -> AnalyticsRuleSchema { - AnalyticsRuleSchema { - name, - r#type, - params: Box::new(params), - } - } -} diff --git a/typesense_codegen/src/models/analytics_rule_update.rs b/typesense_codegen/src/models/analytics_rule_update.rs new file mode 100644 index 0000000..3a42cc4 --- /dev/null +++ b/typesense_codegen/src/models/analytics_rule_update.rs @@ -0,0 +1,34 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// AnalyticsRuleUpdate : Fields allowed to update on an analytics rule +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsRuleUpdate { + #[serde(rename = "name", skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(rename = "rule_tag", skip_serializing_if = "Option::is_none")] + pub rule_tag: Option, + #[serde(rename = "params", skip_serializing_if = "Option::is_none")] + pub params: Option>, +} + +impl AnalyticsRuleUpdate { + /// Fields allowed to update on an analytics rule + pub fn new() -> AnalyticsRuleUpdate { + AnalyticsRuleUpdate { + name: None, + rule_tag: None, + params: None, + } + } +} diff --git a/typesense_codegen/src/models/analytics_rules_retrieve_schema.rs b/typesense_codegen/src/models/analytics_rules_retrieve_schema.rs deleted file mode 100644 index ed32555..0000000 --- a/typesense_codegen/src/models/analytics_rules_retrieve_schema.rs +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct AnalyticsRulesRetrieveSchema { - #[serde(rename = "rules", skip_serializing_if = "Option::is_none")] - pub rules: Option>, -} - -impl AnalyticsRulesRetrieveSchema { - pub fn new() -> AnalyticsRulesRetrieveSchema { - AnalyticsRulesRetrieveSchema { rules: None } - } -} diff --git a/typesense_codegen/src/models/analytics_status.rs b/typesense_codegen/src/models/analytics_status.rs new file mode 100644 index 0000000..ee3f151 --- /dev/null +++ b/typesense_codegen/src/models/analytics_status.rs @@ -0,0 +1,53 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct AnalyticsStatus { + #[serde( + rename = "popular_prefix_queries", + skip_serializing_if = "Option::is_none" + )] + pub popular_prefix_queries: Option, + #[serde( + rename = "nohits_prefix_queries", + skip_serializing_if = "Option::is_none" + )] + pub nohits_prefix_queries: Option, + #[serde(rename = "log_prefix_queries", skip_serializing_if = "Option::is_none")] + pub log_prefix_queries: Option, + #[serde(rename = "query_log_events", skip_serializing_if = "Option::is_none")] + pub query_log_events: Option, + #[serde( + rename = "query_counter_events", + skip_serializing_if = "Option::is_none" + )] + pub query_counter_events: Option, + #[serde(rename = "doc_log_events", skip_serializing_if = "Option::is_none")] + pub doc_log_events: Option, + #[serde(rename = "doc_counter_events", skip_serializing_if = "Option::is_none")] + pub doc_counter_events: Option, +} + +impl AnalyticsStatus { + pub fn new() -> AnalyticsStatus { + AnalyticsStatus { + popular_prefix_queries: None, + nohits_prefix_queries: None, + log_prefix_queries: None, + query_log_events: None, + query_counter_events: None, + doc_log_events: None, + doc_counter_events: None, + } + } +} diff --git a/typesense_codegen/src/models/api_key.rs b/typesense_codegen/src/models/api_key.rs index 7de6d81..511f8b9 100644 --- a/typesense_codegen/src/models/api_key.rs +++ b/typesense_codegen/src/models/api_key.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKey { #[serde(rename = "value", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/api_key_delete_response.rs b/typesense_codegen/src/models/api_key_delete_response.rs new file mode 100644 index 0000000..b9b453e --- /dev/null +++ b/typesense_codegen/src/models/api_key_delete_response.rs @@ -0,0 +1,25 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ApiKeyDeleteResponse { + /// The id of the API key that was deleted + #[serde(rename = "id")] + pub id: i64, +} + +impl ApiKeyDeleteResponse { + pub fn new(id: i64) -> ApiKeyDeleteResponse { + ApiKeyDeleteResponse { id } + } +} diff --git a/typesense_codegen/src/models/api_key_schema.rs b/typesense_codegen/src/models/api_key_schema.rs index 2f6cb2b..095e5ec 100644 --- a/typesense_codegen/src/models/api_key_schema.rs +++ b/typesense_codegen/src/models/api_key_schema.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKeySchema { #[serde(rename = "value", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/api_keys_response.rs b/typesense_codegen/src/models/api_keys_response.rs index f523a98..784a6bf 100644 --- a/typesense_codegen/src/models/api_keys_response.rs +++ b/typesense_codegen/src/models/api_keys_response.rs @@ -3,19 +3,22 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKeysResponse { #[serde(rename = "keys")] - pub keys: Vec, + pub keys: Vec, } impl ApiKeysResponse { - pub fn new(keys: Vec) -> ApiKeysResponse { + pub fn new(keys: Vec) -> ApiKeysResponse { ApiKeysResponse { keys } } } diff --git a/typesense_codegen/src/models/api_response.rs b/typesense_codegen/src/models/api_response.rs index 691ea49..0a27c4f 100644 --- a/typesense_codegen/src/models/api_response.rs +++ b/typesense_codegen/src/models/api_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiResponse { #[serde(rename = "message")] diff --git a/typesense_codegen/src/models/api_stats_response.rs b/typesense_codegen/src/models/api_stats_response.rs new file mode 100644 index 0000000..c35c77a --- /dev/null +++ b/typesense_codegen/src/models/api_stats_response.rs @@ -0,0 +1,86 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ApiStatsResponse { + #[serde(rename = "delete_latency_ms", skip_serializing_if = "Option::is_none")] + pub delete_latency_ms: Option, + #[serde( + rename = "delete_requests_per_second", + skip_serializing_if = "Option::is_none" + )] + pub delete_requests_per_second: Option, + #[serde(rename = "import_latency_ms", skip_serializing_if = "Option::is_none")] + pub import_latency_ms: Option, + #[serde( + rename = "import_requests_per_second", + skip_serializing_if = "Option::is_none" + )] + pub import_requests_per_second: Option, + #[serde(rename = "latency_ms", skip_serializing_if = "Option::is_none")] + pub latency_ms: Option, + #[serde( + rename = "overloaded_requests_per_second", + skip_serializing_if = "Option::is_none" + )] + pub overloaded_requests_per_second: Option, + #[serde( + rename = "pending_write_batches", + skip_serializing_if = "Option::is_none" + )] + pub pending_write_batches: Option, + #[serde( + rename = "requests_per_second", + skip_serializing_if = "Option::is_none" + )] + pub requests_per_second: Option, + #[serde(rename = "search_latency_ms", skip_serializing_if = "Option::is_none")] + pub search_latency_ms: Option, + #[serde( + rename = "search_requests_per_second", + skip_serializing_if = "Option::is_none" + )] + pub search_requests_per_second: Option, + #[serde( + rename = "total_requests_per_second", + skip_serializing_if = "Option::is_none" + )] + pub total_requests_per_second: Option, + #[serde(rename = "write_latency_ms", skip_serializing_if = "Option::is_none")] + pub write_latency_ms: Option, + #[serde( + rename = "write_requests_per_second", + skip_serializing_if = "Option::is_none" + )] + pub write_requests_per_second: Option, +} + +impl ApiStatsResponse { + pub fn new() -> ApiStatsResponse { + ApiStatsResponse { + delete_latency_ms: None, + delete_requests_per_second: None, + import_latency_ms: None, + import_requests_per_second: None, + latency_ms: None, + overloaded_requests_per_second: None, + pending_write_batches: None, + requests_per_second: None, + search_latency_ms: None, + search_requests_per_second: None, + total_requests_per_second: None, + write_latency_ms: None, + write_requests_per_second: None, + } + } +} diff --git a/typesense_codegen/src/models/collection_alias.rs b/typesense_codegen/src/models/collection_alias.rs index b5ab76e..b5a61fe 100644 --- a/typesense_codegen/src/models/collection_alias.rs +++ b/typesense_codegen/src/models/collection_alias.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionAlias { /// Name of the collection alias diff --git a/typesense_codegen/src/models/collection_alias_schema.rs b/typesense_codegen/src/models/collection_alias_schema.rs index 279e88f..b35d641 100644 --- a/typesense_codegen/src/models/collection_alias_schema.rs +++ b/typesense_codegen/src/models/collection_alias_schema.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionAliasSchema { /// Name of the collection you wish to map the alias to diff --git a/typesense_codegen/src/models/collection_aliases_response.rs b/typesense_codegen/src/models/collection_aliases_response.rs index 2bc9560..3cf2d25 100644 --- a/typesense_codegen/src/models/collection_aliases_response.rs +++ b/typesense_codegen/src/models/collection_aliases_response.rs @@ -3,19 +3,22 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionAliasesResponse { #[serde(rename = "aliases")] - pub aliases: Vec, + pub aliases: Vec, } impl CollectionAliasesResponse { - pub fn new(aliases: Vec) -> CollectionAliasesResponse { + pub fn new(aliases: Vec) -> CollectionAliasesResponse { CollectionAliasesResponse { aliases } } } diff --git a/typesense_codegen/src/models/collection_response.rs b/typesense_codegen/src/models/collection_response.rs index 8676b81..1039909 100644 --- a/typesense_codegen/src/models/collection_response.rs +++ b/typesense_codegen/src/models/collection_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionResponse { /// Name of the collection @@ -15,16 +18,19 @@ pub struct CollectionResponse { pub name: String, /// A list of fields for querying, filtering and faceting #[serde(rename = "fields")] - pub fields: Vec, + pub fields: Vec, /// The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. #[serde( rename = "default_sorting_field", skip_serializing_if = "Option::is_none" )] pub default_sorting_field: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, + /// List of synonym set names to associate with this collection + #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] + pub synonym_sets: Option>, /// Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. #[serde( rename = "enable_nested_fields", @@ -34,6 +40,11 @@ pub struct CollectionResponse { /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, + #[serde(rename = "voice_query_model", skip_serializing_if = "Option::is_none")] + pub voice_query_model: Option>, + /// Optional details about the collection, e.g., when it was created, who created it etc. + #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] + pub metadata: Option, /// Number of documents in the collection #[serde(rename = "num_documents")] pub num_documents: i64, @@ -45,7 +56,7 @@ pub struct CollectionResponse { impl CollectionResponse { pub fn new( name: String, - fields: Vec, + fields: Vec, num_documents: i64, created_at: i64, ) -> CollectionResponse { @@ -54,8 +65,11 @@ impl CollectionResponse { fields, default_sorting_field: None, token_separators: None, + synonym_sets: None, enable_nested_fields: None, symbols_to_index: None, + voice_query_model: None, + metadata: None, num_documents, created_at, } diff --git a/typesense_codegen/src/models/collection_schema.rs b/typesense_codegen/src/models/collection_schema.rs index 5a373f6..b861bee 100644 --- a/typesense_codegen/src/models/collection_schema.rs +++ b/typesense_codegen/src/models/collection_schema.rs @@ -3,11 +3,16 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(bon::Builder)] +#[builder(on(String, into))] #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionSchema { /// Name of the collection @@ -15,16 +20,19 @@ pub struct CollectionSchema { pub name: String, /// A list of fields for querying, filtering and faceting #[serde(rename = "fields")] - pub fields: Vec, + pub fields: Vec, /// The name of an int32 / float field that determines the order in which the search results are ranked when a sort_by clause is not provided during searching. This field must indicate some kind of popularity. #[serde( rename = "default_sorting_field", skip_serializing_if = "Option::is_none" )] pub default_sorting_field: Option, - /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] pub token_separators: Option>, + /// List of synonym set names to associate with this collection + #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] + pub synonym_sets: Option>, /// Enables experimental support at a collection level for nested object or object array fields. This field is only available if the Typesense server is version `0.24.0.rcn34` or later. #[serde( rename = "enable_nested_fields", @@ -34,17 +42,25 @@ pub struct CollectionSchema { /// List of symbols or special characters to be indexed. #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] pub symbols_to_index: Option>, + #[serde(rename = "voice_query_model", skip_serializing_if = "Option::is_none")] + pub voice_query_model: Option>, + /// Optional details about the collection, e.g., when it was created, who created it etc. + #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] + pub metadata: Option, } impl CollectionSchema { - pub fn new(name: String, fields: Vec) -> CollectionSchema { + pub fn new(name: String, fields: Vec) -> CollectionSchema { CollectionSchema { name, fields, default_sorting_field: None, token_separators: None, + synonym_sets: None, enable_nested_fields: None, symbols_to_index: None, + voice_query_model: None, + metadata: None, } } } diff --git a/typesense_codegen/src/models/collection_update_schema.rs b/typesense_codegen/src/models/collection_update_schema.rs index f4a4078..27a4d09 100644 --- a/typesense_codegen/src/models/collection_update_schema.rs +++ b/typesense_codegen/src/models/collection_update_schema.rs @@ -3,20 +3,33 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct CollectionUpdateSchema { /// A list of fields for querying, filtering and faceting #[serde(rename = "fields")] - pub fields: Vec, + pub fields: Vec, + /// List of synonym set names to associate with this collection + #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] + pub synonym_sets: Option>, + /// Optional details about the collection, e.g., when it was created, who created it etc. + #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] + pub metadata: Option, } impl CollectionUpdateSchema { - pub fn new(fields: Vec) -> CollectionUpdateSchema { - CollectionUpdateSchema { fields } + pub fn new(fields: Vec) -> CollectionUpdateSchema { + CollectionUpdateSchema { + fields, + synonym_sets: None, + metadata: None, + } } } diff --git a/typesense_codegen/src/models/conversation_model_create_schema.rs b/typesense_codegen/src/models/conversation_model_create_schema.rs new file mode 100644 index 0000000..fc587c3 --- /dev/null +++ b/typesense_codegen/src/models/conversation_model_create_schema.rs @@ -0,0 +1,63 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ConversationModelCreateSchema { + /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + #[serde(rename = "id", skip_serializing_if = "Option::is_none")] + pub id: Option, + /// Name of the LLM model offered by OpenAI, Cloudflare or vLLM + #[serde(rename = "model_name")] + pub model_name: String, + /// The LLM service's API Key + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Typesense collection that stores the historical conversations + #[serde(rename = "history_collection")] + pub history_collection: String, + /// LLM service's account ID (only applicable for Cloudflare) + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// The system prompt that contains special instructions to the LLM + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] + pub ttl: Option, + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + #[serde(rename = "max_bytes")] + pub max_bytes: i32, + /// URL of vLLM service + #[serde(rename = "vllm_url", skip_serializing_if = "Option::is_none")] + pub vllm_url: Option, +} + +impl ConversationModelCreateSchema { + pub fn new( + model_name: String, + history_collection: String, + max_bytes: i32, + ) -> ConversationModelCreateSchema { + ConversationModelCreateSchema { + id: None, + model_name, + api_key: None, + history_collection, + account_id: None, + system_prompt: None, + ttl: None, + max_bytes, + vllm_url: None, + } + } +} diff --git a/typesense_codegen/src/models/conversation_model_schema.rs b/typesense_codegen/src/models/conversation_model_schema.rs new file mode 100644 index 0000000..1738f77 --- /dev/null +++ b/typesense_codegen/src/models/conversation_model_schema.rs @@ -0,0 +1,64 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ConversationModelSchema { + /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + #[serde(rename = "id")] + pub id: String, + /// Name of the LLM model offered by OpenAI, Cloudflare or vLLM + #[serde(rename = "model_name")] + pub model_name: String, + /// The LLM service's API Key + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Typesense collection that stores the historical conversations + #[serde(rename = "history_collection")] + pub history_collection: String, + /// LLM service's account ID (only applicable for Cloudflare) + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// The system prompt that contains special instructions to the LLM + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] + pub ttl: Option, + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + #[serde(rename = "max_bytes")] + pub max_bytes: i32, + /// URL of vLLM service + #[serde(rename = "vllm_url", skip_serializing_if = "Option::is_none")] + pub vllm_url: Option, +} + +impl ConversationModelSchema { + pub fn new( + id: String, + model_name: String, + history_collection: String, + max_bytes: i32, + ) -> ConversationModelSchema { + ConversationModelSchema { + id, + model_name, + api_key: None, + history_collection, + account_id: None, + system_prompt: None, + ttl: None, + max_bytes, + vllm_url: None, + } + } +} diff --git a/typesense_codegen/src/models/conversation_model_update_schema.rs b/typesense_codegen/src/models/conversation_model_update_schema.rs new file mode 100644 index 0000000..1335019 --- /dev/null +++ b/typesense_codegen/src/models/conversation_model_update_schema.rs @@ -0,0 +1,59 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ConversationModelUpdateSchema { + /// An explicit id for the model, otherwise the API will return a response with an auto-generated conversation model id. + #[serde(rename = "id", skip_serializing_if = "Option::is_none")] + pub id: Option, + /// Name of the LLM model offered by OpenAI, Cloudflare or vLLM + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, + /// The LLM service's API Key + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Typesense collection that stores the historical conversations + #[serde(rename = "history_collection", skip_serializing_if = "Option::is_none")] + pub history_collection: Option, + /// LLM service's account ID (only applicable for Cloudflare) + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// The system prompt that contains special instructions to the LLM + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Time interval in seconds after which the messages would be deleted. Default: 86400 (24 hours) + #[serde(rename = "ttl", skip_serializing_if = "Option::is_none")] + pub ttl: Option, + /// The maximum number of bytes to send to the LLM in every API call. Consult the LLM's documentation on the number of bytes supported in the context window. + #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] + pub max_bytes: Option, + /// URL of vLLM service + #[serde(rename = "vllm_url", skip_serializing_if = "Option::is_none")] + pub vllm_url: Option, +} + +impl ConversationModelUpdateSchema { + pub fn new() -> ConversationModelUpdateSchema { + ConversationModelUpdateSchema { + id: None, + model_name: None, + api_key: None, + history_collection: None, + account_id: None, + system_prompt: None, + ttl: None, + max_bytes: None, + vllm_url: None, + } + } +} diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response.rs b/typesense_codegen/src/models/create_analytics_rule_200_response.rs new file mode 100644 index 0000000..80053ca --- /dev/null +++ b/typesense_codegen/src/models/create_analytics_rule_200_response.rs @@ -0,0 +1,43 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateAnalyticsRule200Response { + AnalyticsRule(Box), + Array(Vec), +} + +impl Default for CreateAnalyticsRule200Response { + fn default() -> Self { + Self::AnalyticsRule(Default::default()) + } +} +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Type { + #[serde(rename = "popular_queries")] + PopularQueries, + #[serde(rename = "nohits_queries")] + NohitsQueries, + #[serde(rename = "counter")] + Counter, + #[serde(rename = "log")] + Log, +} + +impl Default for Type { + fn default() -> Type { + Self::PopularQueries + } +} diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs new file mode 100644 index 0000000..bb9f001 --- /dev/null +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner.rs @@ -0,0 +1,67 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct CreateAnalyticsRule200ResponseOneOfInner { + #[serde(rename = "name")] + pub name: String, + #[serde(rename = "type")] + pub r#type: Type, + #[serde(rename = "collection")] + pub collection: String, + #[serde(rename = "event_type")] + pub event_type: String, + #[serde(rename = "rule_tag", skip_serializing_if = "Option::is_none")] + pub rule_tag: Option, + #[serde(rename = "params", skip_serializing_if = "Option::is_none")] + pub params: Option>, + #[serde(rename = "error", skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl CreateAnalyticsRule200ResponseOneOfInner { + pub fn new( + name: String, + r#type: Type, + collection: String, + event_type: String, + ) -> CreateAnalyticsRule200ResponseOneOfInner { + CreateAnalyticsRule200ResponseOneOfInner { + name, + r#type, + collection, + event_type, + rule_tag: None, + params: None, + error: None, + } + } +} +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Type { + #[serde(rename = "popular_queries")] + PopularQueries, + #[serde(rename = "nohits_queries")] + NohitsQueries, + #[serde(rename = "counter")] + Counter, + #[serde(rename = "log")] + Log, +} + +impl Default for Type { + fn default() -> Type { + Self::PopularQueries + } +} diff --git a/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs new file mode 100644 index 0000000..08500ef --- /dev/null +++ b/typesense_codegen/src/models/create_analytics_rule_200_response_one_of_inner_any_of.rs @@ -0,0 +1,24 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct CreateAnalyticsRule200ResponseOneOfInnerAnyOf { + #[serde(rename = "error", skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl CreateAnalyticsRule200ResponseOneOfInnerAnyOf { + pub fn new() -> CreateAnalyticsRule200ResponseOneOfInnerAnyOf { + CreateAnalyticsRule200ResponseOneOfInnerAnyOf { error: None } + } +} diff --git a/typesense_codegen/src/models/create_analytics_rule_request.rs b/typesense_codegen/src/models/create_analytics_rule_request.rs new file mode 100644 index 0000000..262570e --- /dev/null +++ b/typesense_codegen/src/models/create_analytics_rule_request.rs @@ -0,0 +1,43 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CreateAnalyticsRuleRequest { + AnalyticsRuleCreate(Box), + Array(Vec), +} + +impl Default for CreateAnalyticsRuleRequest { + fn default() -> Self { + Self::AnalyticsRuleCreate(Default::default()) + } +} +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Type { + #[serde(rename = "popular_queries")] + PopularQueries, + #[serde(rename = "nohits_queries")] + NohitsQueries, + #[serde(rename = "counter")] + Counter, + #[serde(rename = "log")] + Log, +} + +impl Default for Type { + fn default() -> Type { + Self::PopularQueries + } +} diff --git a/typesense_codegen/src/models/debug_200_response.rs b/typesense_codegen/src/models/debug_200_response.rs index 365fc42..946d84e 100644 --- a/typesense_codegen/src/models/debug_200_response.rs +++ b/typesense_codegen/src/models/debug_200_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct Debug200Response { #[serde(rename = "version", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/delete_documents_200_response.rs b/typesense_codegen/src/models/delete_documents_200_response.rs index a509291..169020c 100644 --- a/typesense_codegen/src/models/delete_documents_200_response.rs +++ b/typesense_codegen/src/models/delete_documents_200_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct DeleteDocuments200Response { #[serde(rename = "num_deleted")] diff --git a/typesense_codegen/src/models/delete_documents_delete_documents_parameters_parameter.rs b/typesense_codegen/src/models/delete_documents_delete_documents_parameters_parameter.rs deleted file mode 100644 index 722bdc4..0000000 --- a/typesense_codegen/src/models/delete_documents_delete_documents_parameters_parameter.rs +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct DeleteDocumentsDeleteDocumentsParametersParameter { - #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] - pub filter_by: Option, - /// Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. - #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] - pub batch_size: Option, -} - -impl DeleteDocumentsDeleteDocumentsParametersParameter { - pub fn new() -> DeleteDocumentsDeleteDocumentsParametersParameter { - DeleteDocumentsDeleteDocumentsParametersParameter { - filter_by: None, - batch_size: None, - } - } -} diff --git a/typesense_codegen/src/models/delete_documents_parameters.rs b/typesense_codegen/src/models/delete_documents_parameters.rs new file mode 100644 index 0000000..55e8241 --- /dev/null +++ b/typesense_codegen/src/models/delete_documents_parameters.rs @@ -0,0 +1,37 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct DeleteDocumentsParameters { + #[serde(rename = "filter_by")] + pub filter_by: String, + /// Batch size parameter controls the number of documents that should be deleted at a time. A larger value will speed up deletions, but will impact performance of other operations running on the server. + #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] + pub batch_size: Option, + #[serde(rename = "ignore_not_found", skip_serializing_if = "Option::is_none")] + pub ignore_not_found: Option, + /// When true, removes all documents from the collection while preserving the collection and its schema. + #[serde(rename = "truncate", skip_serializing_if = "Option::is_none")] + pub truncate: Option, +} + +impl DeleteDocumentsParameters { + pub fn new(filter_by: String) -> DeleteDocumentsParameters { + DeleteDocumentsParameters { + filter_by, + batch_size: None, + ignore_not_found: None, + truncate: None, + } + } +} diff --git a/typesense_codegen/src/models/delete_stopwords_set_200_response.rs b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs new file mode 100644 index 0000000..03b93ef --- /dev/null +++ b/typesense_codegen/src/models/delete_stopwords_set_200_response.rs @@ -0,0 +1,24 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct DeleteStopwordsSet200Response { + #[serde(rename = "id")] + pub id: String, +} + +impl DeleteStopwordsSet200Response { + pub fn new(id: String) -> DeleteStopwordsSet200Response { + DeleteStopwordsSet200Response { id } + } +} diff --git a/typesense_codegen/src/models/dirty_values.rs b/typesense_codegen/src/models/dirty_values.rs new file mode 100644 index 0000000..8caeab9 --- /dev/null +++ b/typesense_codegen/src/models/dirty_values.rs @@ -0,0 +1,42 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum DirtyValues { + #[serde(rename = "coerce_or_reject")] + CoerceOrReject, + #[serde(rename = "coerce_or_drop")] + CoerceOrDrop, + #[serde(rename = "drop")] + Drop, + #[serde(rename = "reject")] + Reject, +} + +impl std::fmt::Display for DirtyValues { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::CoerceOrReject => write!(f, "coerce_or_reject"), + Self::CoerceOrDrop => write!(f, "coerce_or_drop"), + Self::Drop => write!(f, "drop"), + Self::Reject => write!(f, "reject"), + } + } +} + +impl Default for DirtyValues { + fn default() -> DirtyValues { + Self::CoerceOrReject + } +} diff --git a/typesense_codegen/src/models/drop_tokens_mode.rs b/typesense_codegen/src/models/drop_tokens_mode.rs new file mode 100644 index 0000000..5b8ba01 --- /dev/null +++ b/typesense_codegen/src/models/drop_tokens_mode.rs @@ -0,0 +1,40 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// DropTokensMode : Dictates the direction in which the words in the query must be dropped when the original words in the query do not appear in any document. Values: right_to_left (default), left_to_right, both_sides:3 A note on both_sides:3 - for queries 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 +/// 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 +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum DropTokensMode { + #[serde(rename = "right_to_left")] + RightToLeft, + #[serde(rename = "left_to_right")] + LeftToRight, + #[serde(rename = "both_sides:3")] + BothSidesColon3, +} + +impl std::fmt::Display for DropTokensMode { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::RightToLeft => write!(f, "right_to_left"), + Self::LeftToRight => write!(f, "left_to_right"), + Self::BothSidesColon3 => write!(f, "both_sides:3"), + } + } +} + +impl Default for DropTokensMode { + fn default() -> DropTokensMode { + Self::RightToLeft + } +} diff --git a/typesense_codegen/src/models/error_response.rs b/typesense_codegen/src/models/error_response.rs deleted file mode 100644 index ec2ef82..0000000 --- a/typesense_codegen/src/models/error_response.rs +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct ErrorResponse { - #[serde(rename = "message", skip_serializing_if = "Option::is_none")] - pub message: Option, -} - -impl ErrorResponse { - pub fn new() -> ErrorResponse { - ErrorResponse { message: None } - } -} diff --git a/typesense_codegen/src/models/export_documents_export_documents_parameters_parameter.rs b/typesense_codegen/src/models/export_documents_parameters.rs similarity index 52% rename from typesense_codegen/src/models/export_documents_export_documents_parameters_parameter.rs rename to typesense_codegen/src/models/export_documents_parameters.rs index c798028..36984f8 100644 --- a/typesense_codegen/src/models/export_documents_export_documents_parameters_parameter.rs +++ b/typesense_codegen/src/models/export_documents_parameters.rs @@ -3,33 +3,33 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct ExportDocumentsExportDocumentsParametersParameter { +pub struct ExportDocumentsParameters { /// Filter conditions for refining your search results. Separate multiple conditions with &&. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, /// List of fields from the document to include in the search result - #[serde(rename = "include_fields")] - pub include_fields: String, + #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] + pub include_fields: Option, /// List of fields from the document to exclude in the search result - #[serde(rename = "exclude_fields")] - pub exclude_fields: String, + #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] + pub exclude_fields: Option, } -impl ExportDocumentsExportDocumentsParametersParameter { - pub fn new( - include_fields: String, - exclude_fields: String, - ) -> ExportDocumentsExportDocumentsParametersParameter { - ExportDocumentsExportDocumentsParametersParameter { +impl ExportDocumentsParameters { + pub fn new() -> ExportDocumentsParameters { + ExportDocumentsParameters { filter_by: None, - include_fields, - exclude_fields, + include_fields: None, + exclude_fields: None, } } } diff --git a/typesense_codegen/src/models/facet_counts.rs b/typesense_codegen/src/models/facet_counts.rs index 3e0a930..d9cbdf3 100644 --- a/typesense_codegen/src/models/facet_counts.rs +++ b/typesense_codegen/src/models/facet_counts.rs @@ -3,19 +3,22 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FacetCounts { #[serde(rename = "counts", skip_serializing_if = "Option::is_none")] - pub counts: Option>, + pub counts: Option>, #[serde(rename = "field_name", skip_serializing_if = "Option::is_none")] pub field_name: Option, #[serde(rename = "stats", skip_serializing_if = "Option::is_none")] - pub stats: Option>, + pub stats: Option>, } impl FacetCounts { diff --git a/typesense_codegen/src/models/facet_counts_counts_inner.rs b/typesense_codegen/src/models/facet_counts_counts_inner.rs index a4dca2e..bc6ede2 100644 --- a/typesense_codegen/src/models/facet_counts_counts_inner.rs +++ b/typesense_codegen/src/models/facet_counts_counts_inner.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FacetCountsCountsInner { #[serde(rename = "count", skip_serializing_if = "Option::is_none")] @@ -16,6 +19,8 @@ pub struct FacetCountsCountsInner { pub highlighted: Option, #[serde(rename = "value", skip_serializing_if = "Option::is_none")] pub value: Option, + #[serde(rename = "parent", skip_serializing_if = "Option::is_none")] + pub parent: Option, } impl FacetCountsCountsInner { @@ -24,6 +29,7 @@ impl FacetCountsCountsInner { count: None, highlighted: None, value: None, + parent: None, } } } diff --git a/typesense_codegen/src/models/facet_counts_stats.rs b/typesense_codegen/src/models/facet_counts_stats.rs index 142d2ce..7f0d9dd 100644 --- a/typesense_codegen/src/models/facet_counts_stats.rs +++ b/typesense_codegen/src/models/facet_counts_stats.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FacetCountsStats { #[serde(rename = "max", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/field.rs b/typesense_codegen/src/models/field.rs index 454ae90..39bacbb 100644 --- a/typesense_codegen/src/models/field.rs +++ b/typesense_codegen/src/models/field.rs @@ -3,11 +3,16 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(bon::Builder)] +#[builder(on(String, into))] #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct Field { #[serde(rename = "name")] @@ -26,12 +31,36 @@ pub struct Field { pub sort: Option, #[serde(rename = "infix", skip_serializing_if = "Option::is_none")] pub infix: Option, + /// Name of a field in another collection that should be linked to this collection so that it can be joined during query. + #[serde(rename = "reference", skip_serializing_if = "Option::is_none")] + pub reference: Option, #[serde(rename = "num_dim", skip_serializing_if = "Option::is_none")] pub num_dim: Option, #[serde(rename = "drop", skip_serializing_if = "Option::is_none")] pub drop: Option, + /// When set to false, the field value will not be stored on disk. Default: true. + #[serde(rename = "store", skip_serializing_if = "Option::is_none")] + pub store: Option, + /// The distance metric to be used for vector search. Default: `cosine`. You can also use `ip` for inner product. + #[serde(rename = "vec_dist", skip_serializing_if = "Option::is_none")] + pub vec_dist: Option, + /// Enables an index optimized for range filtering on numerical fields (e.g. rating:>3.5). Default: false. + #[serde(rename = "range_index", skip_serializing_if = "Option::is_none")] + pub range_index: Option, + /// Values are stemmed before indexing in-memory. Default: false. + #[serde(rename = "stem", skip_serializing_if = "Option::is_none")] + pub stem: Option, + /// Name of the stemming dictionary to use for this field + #[serde(rename = "stem_dictionary", skip_serializing_if = "Option::is_none")] + pub stem_dictionary: Option, + /// List of symbols or special characters to be used for splitting the text into individual words in addition to space and new-line characters. + #[serde(rename = "token_separators", skip_serializing_if = "Option::is_none")] + pub token_separators: Option>, + /// List of symbols or special characters to be indexed. + #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] + pub symbols_to_index: Option>, #[serde(rename = "embed", skip_serializing_if = "Option::is_none")] - pub embed: Option>, + pub embed: Option>, } impl Field { @@ -45,8 +74,16 @@ impl Field { locale: None, sort: None, infix: None, + reference: None, num_dim: None, drop: None, + store: None, + vec_dist: None, + range_index: None, + stem: None, + stem_dictionary: None, + token_separators: None, + symbols_to_index: None, embed: None, } } diff --git a/typesense_codegen/src/models/field_embed.rs b/typesense_codegen/src/models/field_embed.rs index fcb68e4..0e84fd9 100644 --- a/typesense_codegen/src/models/field_embed.rs +++ b/typesense_codegen/src/models/field_embed.rs @@ -3,24 +3,24 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FieldEmbed { #[serde(rename = "from")] pub from: Vec, #[serde(rename = "model_config")] - pub model_config: Box, + pub model_config: Box, } impl FieldEmbed { - pub fn new( - from: Vec, - model_config: crate::models::FieldEmbedModelConfig, - ) -> FieldEmbed { + pub fn new(from: Vec, model_config: models::FieldEmbedModelConfig) -> FieldEmbed { FieldEmbed { from, model_config: Box::new(model_config), diff --git a/typesense_codegen/src/models/field_embed_model_config.rs b/typesense_codegen/src/models/field_embed_model_config.rs index a7af536..ee40bea 100644 --- a/typesense_codegen/src/models/field_embed_model_config.rs +++ b/typesense_codegen/src/models/field_embed_model_config.rs @@ -3,25 +3,36 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct FieldEmbedModelConfig { #[serde(rename = "model_name")] pub model_name: String, #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] pub api_key: Option, + #[serde(rename = "url", skip_serializing_if = "Option::is_none")] + pub url: Option, #[serde(rename = "access_token", skip_serializing_if = "Option::is_none")] pub access_token: Option, + #[serde(rename = "refresh_token", skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, #[serde(rename = "client_id", skip_serializing_if = "Option::is_none")] pub client_id: Option, #[serde(rename = "client_secret", skip_serializing_if = "Option::is_none")] pub client_secret: Option, #[serde(rename = "project_id", skip_serializing_if = "Option::is_none")] pub project_id: Option, + #[serde(rename = "indexing_prefix", skip_serializing_if = "Option::is_none")] + pub indexing_prefix: Option, + #[serde(rename = "query_prefix", skip_serializing_if = "Option::is_none")] + pub query_prefix: Option, } impl FieldEmbedModelConfig { @@ -29,10 +40,14 @@ impl FieldEmbedModelConfig { FieldEmbedModelConfig { model_name, api_key: None, + url: None, access_token: None, + refresh_token: None, client_id: None, client_secret: None, project_id: None, + indexing_prefix: None, + query_prefix: None, } } } diff --git a/typesense_codegen/src/models/get_collections_parameters.rs b/typesense_codegen/src/models/get_collections_parameters.rs new file mode 100644 index 0000000..02497f6 --- /dev/null +++ b/typesense_codegen/src/models/get_collections_parameters.rs @@ -0,0 +1,35 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct GetCollectionsParameters { + /// Comma-separated list of fields from the collection to exclude from the response + #[serde(rename = "exclude_fields", skip_serializing_if = "Option::is_none")] + pub exclude_fields: Option, + /// Number of collections to fetch. Default: returns all collections. + #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] + pub limit: Option, + /// Identifies the starting point to return collections when paginating. + #[serde(rename = "offset", skip_serializing_if = "Option::is_none")] + pub offset: Option, +} + +impl GetCollectionsParameters { + pub fn new() -> GetCollectionsParameters { + GetCollectionsParameters { + exclude_fields: None, + limit: None, + offset: None, + } + } +} diff --git a/typesense_codegen/src/models/health_status.rs b/typesense_codegen/src/models/health_status.rs index b33a2ba..66cdf6b 100644 --- a/typesense_codegen/src/models/health_status.rs +++ b/typesense_codegen/src/models/health_status.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct HealthStatus { #[serde(rename = "ok")] diff --git a/typesense_codegen/src/models/import_documents_import_documents_parameters_parameter.rs b/typesense_codegen/src/models/import_documents_parameters.rs similarity index 50% rename from typesense_codegen/src/models/import_documents_import_documents_parameters_parameter.rs rename to typesense_codegen/src/models/import_documents_parameters.rs index 9dd0edb..e17494a 100644 --- a/typesense_codegen/src/models/import_documents_import_documents_parameters_parameter.rs +++ b/typesense_codegen/src/models/import_documents_parameters.rs @@ -3,51 +3,43 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct ImportDocumentsImportDocumentsParametersParameter { - #[serde(rename = "action", skip_serializing_if = "Option::is_none")] - pub action: Option, +pub struct ImportDocumentsParameters { #[serde(rename = "batch_size", skip_serializing_if = "Option::is_none")] pub batch_size: Option, - #[serde(rename = "dirty_values", skip_serializing_if = "Option::is_none")] - pub dirty_values: Option, + /// Returning the id of the imported documents. If you want the import response to return the ingested document's id in the response, you can use the return_id parameter. + #[serde(rename = "return_id", skip_serializing_if = "Option::is_none")] + pub return_id: Option, #[serde( rename = "remote_embedding_batch_size", skip_serializing_if = "Option::is_none" )] pub remote_embedding_batch_size: Option, + #[serde(rename = "return_doc", skip_serializing_if = "Option::is_none")] + pub return_doc: Option, + #[serde(rename = "action", skip_serializing_if = "Option::is_none")] + pub action: Option, + #[serde(rename = "dirty_values", skip_serializing_if = "Option::is_none")] + pub dirty_values: Option, } -impl ImportDocumentsImportDocumentsParametersParameter { - pub fn new() -> ImportDocumentsImportDocumentsParametersParameter { - ImportDocumentsImportDocumentsParametersParameter { - action: None, +impl ImportDocumentsParameters { + pub fn new() -> ImportDocumentsParameters { + ImportDocumentsParameters { batch_size: None, - dirty_values: None, + return_id: None, remote_embedding_batch_size: None, + return_doc: None, + action: None, + dirty_values: None, } } } - -#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] -pub enum DirtyValues { - #[serde(rename = "coerce_or_reject")] - CoerceOrReject, - #[serde(rename = "coerce_or_drop")] - CoerceOrDrop, - #[serde(rename = "drop")] - Drop, - #[serde(rename = "reject")] - Reject, -} - -impl Default for DirtyValues { - fn default() -> DirtyValues { - Self::CoerceOrReject - } -} diff --git a/typesense_codegen/src/models/index_action.rs b/typesense_codegen/src/models/index_action.rs new file mode 100644 index 0000000..eb52174 --- /dev/null +++ b/typesense_codegen/src/models/index_action.rs @@ -0,0 +1,42 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum IndexAction { + #[serde(rename = "create")] + Create, + #[serde(rename = "update")] + Update, + #[serde(rename = "upsert")] + Upsert, + #[serde(rename = "emplace")] + Emplace, +} + +impl std::fmt::Display for IndexAction { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::Create => write!(f, "create"), + Self::Update => write!(f, "update"), + Self::Upsert => write!(f, "upsert"), + Self::Emplace => write!(f, "emplace"), + } + } +} + +impl Default for IndexAction { + fn default() -> IndexAction { + Self::Create + } +} diff --git a/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs new file mode 100644 index 0000000..9985e0d --- /dev/null +++ b/typesense_codegen/src/models/list_stemming_dictionaries_200_response.rs @@ -0,0 +1,24 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ListStemmingDictionaries200Response { + #[serde(rename = "dictionaries", skip_serializing_if = "Option::is_none")] + pub dictionaries: Option>, +} + +impl ListStemmingDictionaries200Response { + pub fn new() -> ListStemmingDictionaries200Response { + ListStemmingDictionaries200Response { dictionaries: None } + } +} diff --git a/typesense_codegen/src/models/mod.rs b/typesense_codegen/src/models/mod.rs index f8fb452..40ce6f2 100644 --- a/typesense_codegen/src/models/mod.rs +++ b/typesense_codegen/src/models/mod.rs @@ -1,21 +1,35 @@ -pub mod analytics_rule_parameters; -pub use self::analytics_rule_parameters::AnalyticsRuleParameters; -pub mod analytics_rule_parameters_destination; -pub use self::analytics_rule_parameters_destination::AnalyticsRuleParametersDestination; -pub mod analytics_rule_parameters_source; -pub use self::analytics_rule_parameters_source::AnalyticsRuleParametersSource; -pub mod analytics_rule_schema; -pub use self::analytics_rule_schema::AnalyticsRuleSchema; -pub mod analytics_rules_retrieve_schema; -pub use self::analytics_rules_retrieve_schema::AnalyticsRulesRetrieveSchema; +pub mod analytics_event; +pub use self::analytics_event::AnalyticsEvent; +pub mod analytics_event_create_response; +pub use self::analytics_event_create_response::AnalyticsEventCreateResponse; +pub mod analytics_event_data; +pub use self::analytics_event_data::AnalyticsEventData; +pub mod analytics_events_response; +pub use self::analytics_events_response::AnalyticsEventsResponse; +pub mod analytics_events_response_events_inner; +pub use self::analytics_events_response_events_inner::AnalyticsEventsResponseEventsInner; +pub mod analytics_rule; +pub use self::analytics_rule::AnalyticsRule; +pub mod analytics_rule_create; +pub use self::analytics_rule_create::AnalyticsRuleCreate; +pub mod analytics_rule_create_params; +pub use self::analytics_rule_create_params::AnalyticsRuleCreateParams; +pub mod analytics_rule_update; +pub use self::analytics_rule_update::AnalyticsRuleUpdate; +pub mod analytics_status; +pub use self::analytics_status::AnalyticsStatus; pub mod api_key; pub use self::api_key::ApiKey; +pub mod api_key_delete_response; +pub use self::api_key_delete_response::ApiKeyDeleteResponse; pub mod api_key_schema; pub use self::api_key_schema::ApiKeySchema; pub mod api_keys_response; pub use self::api_keys_response::ApiKeysResponse; pub mod api_response; pub use self::api_response::ApiResponse; +pub mod api_stats_response; +pub use self::api_stats_response::ApiStatsResponse; pub mod collection_alias; pub use self::collection_alias::CollectionAlias; pub mod collection_alias_schema; @@ -28,16 +42,34 @@ pub mod collection_schema; pub use self::collection_schema::CollectionSchema; pub mod collection_update_schema; pub use self::collection_update_schema::CollectionUpdateSchema; +pub mod conversation_model_create_schema; +pub use self::conversation_model_create_schema::ConversationModelCreateSchema; +pub mod conversation_model_schema; +pub use self::conversation_model_schema::ConversationModelSchema; +pub mod conversation_model_update_schema; +pub use self::conversation_model_update_schema::ConversationModelUpdateSchema; +pub mod create_analytics_rule_200_response; +pub use self::create_analytics_rule_200_response::CreateAnalyticsRule200Response; +pub mod create_analytics_rule_200_response_one_of_inner; +pub use self::create_analytics_rule_200_response_one_of_inner::CreateAnalyticsRule200ResponseOneOfInner; +pub mod create_analytics_rule_200_response_one_of_inner_any_of; +pub use self::create_analytics_rule_200_response_one_of_inner_any_of::CreateAnalyticsRule200ResponseOneOfInnerAnyOf; +pub mod create_analytics_rule_request; +pub use self::create_analytics_rule_request::CreateAnalyticsRuleRequest; pub mod debug_200_response; pub use self::debug_200_response::Debug200Response; pub mod delete_documents_200_response; pub use self::delete_documents_200_response::DeleteDocuments200Response; -pub mod delete_documents_delete_documents_parameters_parameter; -pub use self::delete_documents_delete_documents_parameters_parameter::DeleteDocumentsDeleteDocumentsParametersParameter; -pub mod error_response; -pub use self::error_response::ErrorResponse; -pub mod export_documents_export_documents_parameters_parameter; -pub use self::export_documents_export_documents_parameters_parameter::ExportDocumentsExportDocumentsParametersParameter; +pub mod delete_documents_parameters; +pub use self::delete_documents_parameters::DeleteDocumentsParameters; +pub mod delete_stopwords_set_200_response; +pub use self::delete_stopwords_set_200_response::DeleteStopwordsSet200Response; +pub mod dirty_values; +pub use self::dirty_values::DirtyValues; +pub mod drop_tokens_mode; +pub use self::drop_tokens_mode::DropTokensMode; +pub mod export_documents_parameters; +pub use self::export_documents_parameters::ExportDocumentsParameters; pub mod facet_counts; pub use self::facet_counts::FacetCounts; pub mod facet_counts_counts_inner; @@ -50,26 +82,54 @@ pub mod field_embed; pub use self::field_embed::FieldEmbed; pub mod field_embed_model_config; pub use self::field_embed_model_config::FieldEmbedModelConfig; +pub mod get_collections_parameters; +pub use self::get_collections_parameters::GetCollectionsParameters; pub mod health_status; pub use self::health_status::HealthStatus; -pub mod import_documents_import_documents_parameters_parameter; -pub use self::import_documents_import_documents_parameters_parameter::ImportDocumentsImportDocumentsParametersParameter; +pub mod import_documents_parameters; +pub use self::import_documents_parameters::ImportDocumentsParameters; +pub mod index_action; +pub use self::index_action::IndexAction; +pub mod list_stemming_dictionaries_200_response; +pub use self::list_stemming_dictionaries_200_response::ListStemmingDictionaries200Response; pub mod multi_search_collection_parameters; pub use self::multi_search_collection_parameters::MultiSearchCollectionParameters; pub mod multi_search_parameters; pub use self::multi_search_parameters::MultiSearchParameters; pub mod multi_search_result; pub use self::multi_search_result::MultiSearchResult; +pub mod multi_search_result_item; +pub use self::multi_search_result_item::MultiSearchResultItem; pub mod multi_search_searches_parameter; pub use self::multi_search_searches_parameter::MultiSearchSearchesParameter; -pub mod scoped_key_parameters; -pub use self::scoped_key_parameters::ScopedKeyParameters; +pub mod nl_search_model_base; +pub use self::nl_search_model_base::NlSearchModelBase; +pub mod nl_search_model_create_schema; +pub use self::nl_search_model_create_schema::NlSearchModelCreateSchema; +pub mod nl_search_model_delete_schema; +pub use self::nl_search_model_delete_schema::NlSearchModelDeleteSchema; +pub mod nl_search_model_schema; +pub use self::nl_search_model_schema::NlSearchModelSchema; +pub mod preset_delete_schema; +pub use self::preset_delete_schema::PresetDeleteSchema; +pub mod preset_schema; +pub use self::preset_schema::PresetSchema; +pub mod preset_upsert_schema; +pub use self::preset_upsert_schema::PresetUpsertSchema; +pub mod preset_upsert_schema_value; +pub use self::preset_upsert_schema_value::PresetUpsertSchemaValue; +pub mod presets_retrieve_schema; +pub use self::presets_retrieve_schema::PresetsRetrieveSchema; +pub mod schema_change_status; +pub use self::schema_change_status::SchemaChangeStatus; pub mod search_grouped_hit; pub use self::search_grouped_hit::SearchGroupedHit; pub mod search_highlight; pub use self::search_highlight::SearchHighlight; pub mod search_override; pub use self::search_override::SearchOverride; +pub mod search_override_delete_response; +pub use self::search_override_delete_response::SearchOverrideDeleteResponse; pub mod search_override_exclude; pub use self::search_override_exclude::SearchOverrideExclude; pub mod search_override_include; @@ -82,23 +142,57 @@ pub mod search_overrides_response; pub use self::search_overrides_response::SearchOverridesResponse; pub mod search_parameters; pub use self::search_parameters::SearchParameters; +pub mod search_request_params; +pub use self::search_request_params::SearchRequestParams; +pub mod search_request_params_voice_query; +pub use self::search_request_params_voice_query::SearchRequestParamsVoiceQuery; pub mod search_result; pub use self::search_result::SearchResult; +pub mod search_result_conversation; +pub use self::search_result_conversation::SearchResultConversation; pub mod search_result_hit; pub use self::search_result_hit::SearchResultHit; -pub mod search_result_request_params; -pub use self::search_result_request_params::SearchResultRequestParams; +pub mod search_result_hit_hybrid_search_info; +pub use self::search_result_hit_hybrid_search_info::SearchResultHitHybridSearchInfo; +pub mod search_result_hit_text_match_info; +pub use self::search_result_hit_text_match_info::SearchResultHitTextMatchInfo; pub mod search_synonym; pub use self::search_synonym::SearchSynonym; +pub mod search_synonym_delete_response; +pub use self::search_synonym_delete_response::SearchSynonymDeleteResponse; pub mod search_synonym_schema; pub use self::search_synonym_schema::SearchSynonymSchema; pub mod search_synonyms_response; pub use self::search_synonyms_response::SearchSynonymsResponse; -pub mod snapshot_parameters; -pub use self::snapshot_parameters::SnapshotParameters; +pub mod stemming_dictionary; +pub use self::stemming_dictionary::StemmingDictionary; +pub mod stemming_dictionary_words_inner; +pub use self::stemming_dictionary_words_inner::StemmingDictionaryWordsInner; +pub mod stopwords_set_retrieve_schema; +pub use self::stopwords_set_retrieve_schema::StopwordsSetRetrieveSchema; +pub mod stopwords_set_schema; +pub use self::stopwords_set_schema::StopwordsSetSchema; +pub mod stopwords_set_upsert_schema; +pub use self::stopwords_set_upsert_schema::StopwordsSetUpsertSchema; +pub mod stopwords_sets_retrieve_all_schema; +pub use self::stopwords_sets_retrieve_all_schema::StopwordsSetsRetrieveAllSchema; pub mod success_status; pub use self::success_status::SuccessStatus; +pub mod synonym_item_schema; +pub use self::synonym_item_schema::SynonymItemSchema; +pub mod synonym_set_create_schema; +pub use self::synonym_set_create_schema::SynonymSetCreateSchema; +pub mod synonym_set_delete_schema; +pub use self::synonym_set_delete_schema::SynonymSetDeleteSchema; +pub mod synonym_set_schema; +pub use self::synonym_set_schema::SynonymSetSchema; +pub mod synonym_sets_retrieve_schema; +pub use self::synonym_sets_retrieve_schema::SynonymSetsRetrieveSchema; +pub mod toggle_slow_request_log_request; +pub use self::toggle_slow_request_log_request::ToggleSlowRequestLogRequest; pub mod update_documents_200_response; pub use self::update_documents_200_response::UpdateDocuments200Response; -pub mod update_documents_update_documents_parameters_parameter; -pub use self::update_documents_update_documents_parameters_parameter::UpdateDocumentsUpdateDocumentsParametersParameter; +pub mod update_documents_parameters; +pub use self::update_documents_parameters::UpdateDocumentsParameters; +pub mod voice_query_model_collection_config; +pub use self::voice_query_model_collection_config::VoiceQueryModelCollectionConfig; diff --git a/typesense_codegen/src/models/multi_search_collection_parameters.rs b/typesense_codegen/src/models/multi_search_collection_parameters.rs index 97a99fd..76f99e0 100644 --- a/typesense_codegen/src/models/multi_search_collection_parameters.rs +++ b/typesense_codegen/src/models/multi_search_collection_parameters.rs @@ -3,11 +3,16 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(bon::Builder)] +#[builder(on(String, into))] #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchCollectionParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. @@ -58,7 +63,7 @@ pub struct MultiSearchCollectionParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -70,6 +75,12 @@ pub struct MultiSearchCollectionParameters { /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde( + rename = "group_missing_values", + skip_serializing_if = "Option::is_none" + )] + pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] pub include_fields: Option, @@ -106,22 +117,51 @@ pub struct MultiSearchCollectionParameters { skip_serializing_if = "Option::is_none" )] pub drop_tokens_threshold: Option, + #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] + pub drop_tokens_mode: Option, /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 #[serde( rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none" )] pub typo_tokens_threshold: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde( + rename = "enable_typos_for_alpha_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] + pub enable_typos_for_alpha_numerical_tokens: Option, + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] + pub filter_curated_hits: Option, + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] + pub enable_synonyms: Option, + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] + pub enable_analytics: Option, + /// Allow synonym resolution on word prefixes in the query. Default: false + #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] + pub synonym_prefix: Option, + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] + pub synonym_num_typos: Option, + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// Comma separated list of tags to trigger the curations rules that match the tags. + #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] + pub override_tags: Option, + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same #[serde( rename = "pre_segmented_query", skip_serializing_if = "Option::is_none" @@ -139,22 +179,40 @@ pub struct MultiSearchCollectionParameters { skip_serializing_if = "Option::is_none" )] pub prioritize_exact_match: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde( + rename = "prioritize_token_position", + skip_serializing_if = "Option::is_none" + )] + pub prioritize_token_position: Option, + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde( + rename = "prioritize_num_matching_fields", + skip_serializing_if = "Option::is_none" + )] + pub prioritize_num_matching_fields: Option, + /// Make Typesense disable typos for numerical tokens. + #[serde( + rename = "enable_typos_for_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] + pub enable_typos_for_numerical_tokens: Option, + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, /// Vector query expression for fetching documents \"closest\" to a given query/document vector. @@ -172,13 +230,52 @@ pub struct MultiSearchCollectionParameters { skip_serializing_if = "Option::is_none" )] pub remote_embedding_num_tries: Option, + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] + pub facet_strategy: Option, + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] + pub stopwords: Option, + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde( + rename = "facet_return_parent", + skip_serializing_if = "Option::is_none" + )] + pub facet_return_parent: Option, + /// The base64 encoded audio file in 16 khz 16-bit WAV format. + #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] + pub voice_query: Option, + /// Enable conversational search. + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option, + /// The Id of Conversation Model to be used. + #[serde( + rename = "conversation_model_id", + skip_serializing_if = "Option::is_none" + )] + pub conversation_model_id: Option, + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] + pub conversation_id: Option, /// The collection to search in. - #[serde(rename = "collection")] - pub collection: String, + #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] + pub collection: Option, + /// A separate search API key for each search within a multi_search request + #[serde( + rename = "x-typesense-api-key", + skip_serializing_if = "Option::is_none" + )] + pub x_typesense_api_key: Option, + /// When true, computes both text match and vector distance scores for all matches in hybrid search. Documents found only through keyword search will get a vector distance score, and documents found only through vector search will get a text match score. + #[serde( + rename = "rerank_hybrid_matches", + skip_serializing_if = "Option::is_none" + )] + pub rerank_hybrid_matches: Option, } impl MultiSearchCollectionParameters { - pub fn new(collection: String) -> MultiSearchCollectionParameters { + pub fn new() -> MultiSearchCollectionParameters { MultiSearchCollectionParameters { q: None, query_by: None, @@ -200,6 +297,7 @@ impl MultiSearchCollectionParameters { offset: None, group_by: None, group_limit: None, + group_missing_values: None, include_fields: None, exclude_fields: None, highlight_full_fields: None, @@ -208,14 +306,25 @@ impl MultiSearchCollectionParameters { highlight_end_tag: None, snippet_threshold: None, drop_tokens_threshold: None, + drop_tokens_mode: None, typo_tokens_threshold: None, + enable_typos_for_alpha_numerical_tokens: None, + filter_curated_hits: None, + enable_synonyms: None, + enable_analytics: None, + synonym_prefix: None, + synonym_num_typos: None, pinned_hits: None, hidden_hits: None, + override_tags: None, highlight_fields: None, pre_segmented_query: None, preset: None, enable_overrides: None, prioritize_exact_match: None, + prioritize_token_position: None, + prioritize_num_matching_fields: None, + enable_typos_for_numerical_tokens: None, exhaustive_search: None, search_cutoff_ms: None, use_cache: None, @@ -225,7 +334,16 @@ impl MultiSearchCollectionParameters { vector_query: None, remote_embedding_timeout_ms: None, remote_embedding_num_tries: None, - collection, + facet_strategy: None, + stopwords: None, + facet_return_parent: None, + voice_query: None, + conversation: None, + conversation_model_id: None, + conversation_id: None, + collection: None, + x_typesense_api_key: None, + rerank_hybrid_matches: None, } } } diff --git a/typesense_codegen/src/models/multi_search_parameters.rs b/typesense_codegen/src/models/multi_search_parameters.rs index 409cc90..21b2db0 100644 --- a/typesense_codegen/src/models/multi_search_parameters.rs +++ b/typesense_codegen/src/models/multi_search_parameters.rs @@ -3,13 +3,17 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ -/// MultiSearchParameters : Parameters for the multi search API. +use crate::models; +use serde::{Deserialize, Serialize}; +/// MultiSearchParameters : Parameters for the multi search API. +#[derive(bon::Builder)] +#[builder(on(String, into))] #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. @@ -60,7 +64,7 @@ pub struct MultiSearchParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -72,6 +76,12 @@ pub struct MultiSearchParameters { /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde( + rename = "group_missing_values", + skip_serializing_if = "Option::is_none" + )] + pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] pub include_fields: Option, @@ -108,22 +118,51 @@ pub struct MultiSearchParameters { skip_serializing_if = "Option::is_none" )] pub drop_tokens_threshold: Option, + #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] + pub drop_tokens_mode: Option, /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 #[serde( rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none" )] pub typo_tokens_threshold: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde( + rename = "enable_typos_for_alpha_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] + pub enable_typos_for_alpha_numerical_tokens: Option, + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] + pub filter_curated_hits: Option, + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] + pub enable_synonyms: Option, + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] + pub enable_analytics: Option, + /// Allow synonym resolution on word prefixes in the query. Default: false + #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] + pub synonym_prefix: Option, + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] + pub synonym_num_typos: Option, + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// Comma separated list of tags to trigger the curations rules that match the tags. + #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] + pub override_tags: Option, + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same #[serde( rename = "pre_segmented_query", skip_serializing_if = "Option::is_none" @@ -141,22 +180,40 @@ pub struct MultiSearchParameters { skip_serializing_if = "Option::is_none" )] pub prioritize_exact_match: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Make Typesense prioritize documents where the query words appear earlier in the text. + #[serde( + rename = "prioritize_token_position", + skip_serializing_if = "Option::is_none" + )] + pub prioritize_token_position: Option, + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde( + rename = "prioritize_num_matching_fields", + skip_serializing_if = "Option::is_none" + )] + pub prioritize_num_matching_fields: Option, + /// Make Typesense disable typos for numerical tokens. + #[serde( + rename = "enable_typos_for_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] + pub enable_typos_for_numerical_tokens: Option, + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, /// Vector query expression for fetching documents \"closest\" to a given query/document vector. @@ -174,6 +231,33 @@ pub struct MultiSearchParameters { skip_serializing_if = "Option::is_none" )] pub remote_embedding_num_tries: Option, + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] + pub facet_strategy: Option, + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] + pub stopwords: Option, + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde( + rename = "facet_return_parent", + skip_serializing_if = "Option::is_none" + )] + pub facet_return_parent: Option, + /// The base64 encoded audio file in 16 khz 16-bit WAV format. + #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] + pub voice_query: Option, + /// Enable conversational search. + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option, + /// The Id of Conversation Model to be used. + #[serde( + rename = "conversation_model_id", + skip_serializing_if = "Option::is_none" + )] + pub conversation_model_id: Option, + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] + pub conversation_id: Option, } impl MultiSearchParameters { @@ -200,6 +284,7 @@ impl MultiSearchParameters { offset: None, group_by: None, group_limit: None, + group_missing_values: None, include_fields: None, exclude_fields: None, highlight_full_fields: None, @@ -208,14 +293,25 @@ impl MultiSearchParameters { highlight_end_tag: None, snippet_threshold: None, drop_tokens_threshold: None, + drop_tokens_mode: None, typo_tokens_threshold: None, + enable_typos_for_alpha_numerical_tokens: None, + filter_curated_hits: None, + enable_synonyms: None, + enable_analytics: None, + synonym_prefix: None, + synonym_num_typos: None, pinned_hits: None, hidden_hits: None, + override_tags: None, highlight_fields: None, pre_segmented_query: None, preset: None, enable_overrides: None, prioritize_exact_match: None, + prioritize_token_position: None, + prioritize_num_matching_fields: None, + enable_typos_for_numerical_tokens: None, exhaustive_search: None, search_cutoff_ms: None, use_cache: None, @@ -225,6 +321,13 @@ impl MultiSearchParameters { vector_query: None, remote_embedding_timeout_ms: None, remote_embedding_num_tries: None, + facet_strategy: None, + stopwords: None, + facet_return_parent: None, + voice_query: None, + conversation: None, + conversation_model_id: None, + conversation_id: None, } } } diff --git a/typesense_codegen/src/models/multi_search_result.rs b/typesense_codegen/src/models/multi_search_result.rs index 1bab924..bef6780 100644 --- a/typesense_codegen/src/models/multi_search_result.rs +++ b/typesense_codegen/src/models/multi_search_result.rs @@ -3,19 +3,27 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchResult { #[serde(rename = "results")] - pub results: Vec>, + pub results: Vec>, + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option>, } impl MultiSearchResult { - pub fn new(results: Vec>) -> Self { - Self { results } + pub fn new(results: Vec>) -> MultiSearchResult { + MultiSearchResult { + results, + conversation: None, + } } } diff --git a/typesense_codegen/src/models/multi_search_result_item.rs b/typesense_codegen/src/models/multi_search_result_item.rs new file mode 100644 index 0000000..64794c8 --- /dev/null +++ b/typesense_codegen/src/models/multi_search_result_item.rs @@ -0,0 +1,77 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct MultiSearchResultItem { + #[serde(rename = "facet_counts", skip_serializing_if = "Option::is_none")] + pub facet_counts: Option>, + /// The number of documents found + #[serde(rename = "found", skip_serializing_if = "Option::is_none")] + pub found: Option, + #[serde(rename = "found_docs", skip_serializing_if = "Option::is_none")] + pub found_docs: Option, + /// The number of milliseconds the search took + #[serde(rename = "search_time_ms", skip_serializing_if = "Option::is_none")] + pub search_time_ms: Option, + /// The total number of documents in the collection + #[serde(rename = "out_of", skip_serializing_if = "Option::is_none")] + pub out_of: Option, + /// Whether the search was cut off + #[serde(rename = "search_cutoff", skip_serializing_if = "Option::is_none")] + pub search_cutoff: Option, + /// The search result page number + #[serde(rename = "page", skip_serializing_if = "Option::is_none")] + pub page: Option, + #[serde(rename = "grouped_hits", skip_serializing_if = "Option::is_none")] + pub grouped_hits: Option>>, + /// The documents that matched the search query + #[serde(rename = "hits", skip_serializing_if = "Option::is_none")] + pub hits: Option>>, + #[serde(rename = "request_params", skip_serializing_if = "Option::is_none")] + pub request_params: Option>, + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option>, + /// Returned only for union query response. + #[serde( + rename = "union_request_params", + skip_serializing_if = "Option::is_none" + )] + pub union_request_params: Option>, + /// HTTP error code + #[serde(rename = "code", skip_serializing_if = "Option::is_none")] + pub code: Option, + /// Error description + #[serde(rename = "error", skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl MultiSearchResultItem { + pub fn new() -> MultiSearchResultItem { + MultiSearchResultItem { + facet_counts: None, + found: None, + found_docs: None, + search_time_ms: None, + out_of: None, + search_cutoff: None, + page: None, + grouped_hits: None, + hits: None, + request_params: None, + conversation: None, + union_request_params: None, + code: None, + error: None, + } + } +} diff --git a/typesense_codegen/src/models/multi_search_searches_parameter.rs b/typesense_codegen/src/models/multi_search_searches_parameter.rs index 1e11b6e..36cd062 100644 --- a/typesense_codegen/src/models/multi_search_searches_parameter.rs +++ b/typesense_codegen/src/models/multi_search_searches_parameter.rs @@ -3,21 +3,30 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct MultiSearchSearchesParameter { + /// When true, merges the search results from each search query into a single ordered set of hits. + #[serde(rename = "union", skip_serializing_if = "Option::is_none")] + pub union: Option, #[serde(rename = "searches")] - pub searches: Vec, + pub searches: Vec, } impl MultiSearchSearchesParameter { pub fn new( - searches: Vec, + searches: Vec, ) -> MultiSearchSearchesParameter { - MultiSearchSearchesParameter { searches } + MultiSearchSearchesParameter { + union: None, + searches, + } } } diff --git a/typesense_codegen/src/models/nl_search_model_base.rs b/typesense_codegen/src/models/nl_search_model_base.rs new file mode 100644 index 0000000..5bb066f --- /dev/null +++ b/typesense_codegen/src/models/nl_search_model_base.rs @@ -0,0 +1,95 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct NlSearchModelBase { + /// Name of the NL model to use + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, + /// API key for the NL model service + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Custom API URL for the NL model service + #[serde(rename = "api_url", skip_serializing_if = "Option::is_none")] + pub api_url: Option, + /// Maximum number of bytes to process + #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] + pub max_bytes: Option, + /// Temperature parameter for the NL model + #[serde(rename = "temperature", skip_serializing_if = "Option::is_none")] + pub temperature: Option, + /// System prompt for the NL model + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Top-p parameter for the NL model (Google-specific) + #[serde(rename = "top_p", skip_serializing_if = "Option::is_none")] + pub top_p: Option, + /// Top-k parameter for the NL model (Google-specific) + #[serde(rename = "top_k", skip_serializing_if = "Option::is_none")] + pub top_k: Option, + /// Stop sequences for the NL model (Google-specific) + #[serde(rename = "stop_sequences", skip_serializing_if = "Option::is_none")] + pub stop_sequences: Option>, + /// API version for the NL model service + #[serde(rename = "api_version", skip_serializing_if = "Option::is_none")] + pub api_version: Option, + /// Project ID for GCP Vertex AI + #[serde(rename = "project_id", skip_serializing_if = "Option::is_none")] + pub project_id: Option, + /// Access token for GCP Vertex AI + #[serde(rename = "access_token", skip_serializing_if = "Option::is_none")] + pub access_token: Option, + /// Refresh token for GCP Vertex AI + #[serde(rename = "refresh_token", skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, + /// Client ID for GCP Vertex AI + #[serde(rename = "client_id", skip_serializing_if = "Option::is_none")] + pub client_id: Option, + /// Client secret for GCP Vertex AI + #[serde(rename = "client_secret", skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + /// Region for GCP Vertex AI + #[serde(rename = "region", skip_serializing_if = "Option::is_none")] + pub region: Option, + /// Maximum output tokens for GCP Vertex AI + #[serde(rename = "max_output_tokens", skip_serializing_if = "Option::is_none")] + pub max_output_tokens: Option, + /// Account ID for Cloudflare-specific models + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, +} + +impl NlSearchModelBase { + pub fn new() -> NlSearchModelBase { + NlSearchModelBase { + model_name: None, + api_key: None, + api_url: None, + max_bytes: None, + temperature: None, + system_prompt: None, + top_p: None, + top_k: None, + stop_sequences: None, + api_version: None, + project_id: None, + access_token: None, + refresh_token: None, + client_id: None, + client_secret: None, + region: None, + max_output_tokens: None, + account_id: None, + } + } +} diff --git a/typesense_codegen/src/models/nl_search_model_create_schema.rs b/typesense_codegen/src/models/nl_search_model_create_schema.rs new file mode 100644 index 0000000..34cb2d4 --- /dev/null +++ b/typesense_codegen/src/models/nl_search_model_create_schema.rs @@ -0,0 +1,99 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct NlSearchModelCreateSchema { + /// Name of the NL model to use + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, + /// API key for the NL model service + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Custom API URL for the NL model service + #[serde(rename = "api_url", skip_serializing_if = "Option::is_none")] + pub api_url: Option, + /// Maximum number of bytes to process + #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] + pub max_bytes: Option, + /// Temperature parameter for the NL model + #[serde(rename = "temperature", skip_serializing_if = "Option::is_none")] + pub temperature: Option, + /// System prompt for the NL model + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Top-p parameter for the NL model (Google-specific) + #[serde(rename = "top_p", skip_serializing_if = "Option::is_none")] + pub top_p: Option, + /// Top-k parameter for the NL model (Google-specific) + #[serde(rename = "top_k", skip_serializing_if = "Option::is_none")] + pub top_k: Option, + /// Stop sequences for the NL model (Google-specific) + #[serde(rename = "stop_sequences", skip_serializing_if = "Option::is_none")] + pub stop_sequences: Option>, + /// API version for the NL model service + #[serde(rename = "api_version", skip_serializing_if = "Option::is_none")] + pub api_version: Option, + /// Project ID for GCP Vertex AI + #[serde(rename = "project_id", skip_serializing_if = "Option::is_none")] + pub project_id: Option, + /// Access token for GCP Vertex AI + #[serde(rename = "access_token", skip_serializing_if = "Option::is_none")] + pub access_token: Option, + /// Refresh token for GCP Vertex AI + #[serde(rename = "refresh_token", skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, + /// Client ID for GCP Vertex AI + #[serde(rename = "client_id", skip_serializing_if = "Option::is_none")] + pub client_id: Option, + /// Client secret for GCP Vertex AI + #[serde(rename = "client_secret", skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + /// Region for GCP Vertex AI + #[serde(rename = "region", skip_serializing_if = "Option::is_none")] + pub region: Option, + /// Maximum output tokens for GCP Vertex AI + #[serde(rename = "max_output_tokens", skip_serializing_if = "Option::is_none")] + pub max_output_tokens: Option, + /// Account ID for Cloudflare-specific models + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// Optional ID for the NL search model + #[serde(rename = "id", skip_serializing_if = "Option::is_none")] + pub id: Option, +} + +impl NlSearchModelCreateSchema { + pub fn new() -> NlSearchModelCreateSchema { + NlSearchModelCreateSchema { + model_name: None, + api_key: None, + api_url: None, + max_bytes: None, + temperature: None, + system_prompt: None, + top_p: None, + top_k: None, + stop_sequences: None, + api_version: None, + project_id: None, + access_token: None, + refresh_token: None, + client_id: None, + client_secret: None, + region: None, + max_output_tokens: None, + account_id: None, + id: None, + } + } +} diff --git a/typesense_codegen/src/models/nl_search_model_delete_schema.rs b/typesense_codegen/src/models/nl_search_model_delete_schema.rs new file mode 100644 index 0000000..f31df7d --- /dev/null +++ b/typesense_codegen/src/models/nl_search_model_delete_schema.rs @@ -0,0 +1,25 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct NlSearchModelDeleteSchema { + /// ID of the deleted NL search model + #[serde(rename = "id")] + pub id: String, +} + +impl NlSearchModelDeleteSchema { + pub fn new(id: String) -> NlSearchModelDeleteSchema { + NlSearchModelDeleteSchema { id } + } +} diff --git a/typesense_codegen/src/models/nl_search_model_schema.rs b/typesense_codegen/src/models/nl_search_model_schema.rs new file mode 100644 index 0000000..b2066e0 --- /dev/null +++ b/typesense_codegen/src/models/nl_search_model_schema.rs @@ -0,0 +1,99 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct NlSearchModelSchema { + /// Name of the NL model to use + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, + /// API key for the NL model service + #[serde(rename = "api_key", skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Custom API URL for the NL model service + #[serde(rename = "api_url", skip_serializing_if = "Option::is_none")] + pub api_url: Option, + /// Maximum number of bytes to process + #[serde(rename = "max_bytes", skip_serializing_if = "Option::is_none")] + pub max_bytes: Option, + /// Temperature parameter for the NL model + #[serde(rename = "temperature", skip_serializing_if = "Option::is_none")] + pub temperature: Option, + /// System prompt for the NL model + #[serde(rename = "system_prompt", skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, + /// Top-p parameter for the NL model (Google-specific) + #[serde(rename = "top_p", skip_serializing_if = "Option::is_none")] + pub top_p: Option, + /// Top-k parameter for the NL model (Google-specific) + #[serde(rename = "top_k", skip_serializing_if = "Option::is_none")] + pub top_k: Option, + /// Stop sequences for the NL model (Google-specific) + #[serde(rename = "stop_sequences", skip_serializing_if = "Option::is_none")] + pub stop_sequences: Option>, + /// API version for the NL model service + #[serde(rename = "api_version", skip_serializing_if = "Option::is_none")] + pub api_version: Option, + /// Project ID for GCP Vertex AI + #[serde(rename = "project_id", skip_serializing_if = "Option::is_none")] + pub project_id: Option, + /// Access token for GCP Vertex AI + #[serde(rename = "access_token", skip_serializing_if = "Option::is_none")] + pub access_token: Option, + /// Refresh token for GCP Vertex AI + #[serde(rename = "refresh_token", skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, + /// Client ID for GCP Vertex AI + #[serde(rename = "client_id", skip_serializing_if = "Option::is_none")] + pub client_id: Option, + /// Client secret for GCP Vertex AI + #[serde(rename = "client_secret", skip_serializing_if = "Option::is_none")] + pub client_secret: Option, + /// Region for GCP Vertex AI + #[serde(rename = "region", skip_serializing_if = "Option::is_none")] + pub region: Option, + /// Maximum output tokens for GCP Vertex AI + #[serde(rename = "max_output_tokens", skip_serializing_if = "Option::is_none")] + pub max_output_tokens: Option, + /// Account ID for Cloudflare-specific models + #[serde(rename = "account_id", skip_serializing_if = "Option::is_none")] + pub account_id: Option, + /// ID of the NL search model + #[serde(rename = "id")] + pub id: String, +} + +impl NlSearchModelSchema { + pub fn new(id: String) -> NlSearchModelSchema { + NlSearchModelSchema { + model_name: None, + api_key: None, + api_url: None, + max_bytes: None, + temperature: None, + system_prompt: None, + top_p: None, + top_k: None, + stop_sequences: None, + api_version: None, + project_id: None, + access_token: None, + refresh_token: None, + client_id: None, + client_secret: None, + region: None, + max_output_tokens: None, + account_id: None, + id, + } + } +} diff --git a/typesense_codegen/src/models/preset_delete_schema.rs b/typesense_codegen/src/models/preset_delete_schema.rs new file mode 100644 index 0000000..5203796 --- /dev/null +++ b/typesense_codegen/src/models/preset_delete_schema.rs @@ -0,0 +1,24 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct PresetDeleteSchema { + #[serde(rename = "name")] + pub name: String, +} + +impl PresetDeleteSchema { + pub fn new(name: String) -> PresetDeleteSchema { + PresetDeleteSchema { name } + } +} diff --git a/typesense_codegen/src/models/preset_schema.rs b/typesense_codegen/src/models/preset_schema.rs new file mode 100644 index 0000000..c12caca --- /dev/null +++ b/typesense_codegen/src/models/preset_schema.rs @@ -0,0 +1,29 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct PresetSchema { + #[serde(rename = "value")] + pub value: Box, + #[serde(rename = "name")] + pub name: String, +} + +impl PresetSchema { + pub fn new(value: models::PresetUpsertSchemaValue, name: String) -> PresetSchema { + PresetSchema { + value: Box::new(value), + name, + } + } +} diff --git a/typesense_codegen/src/models/preset_upsert_schema.rs b/typesense_codegen/src/models/preset_upsert_schema.rs new file mode 100644 index 0000000..92eff0d --- /dev/null +++ b/typesense_codegen/src/models/preset_upsert_schema.rs @@ -0,0 +1,26 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct PresetUpsertSchema { + #[serde(rename = "value")] + pub value: Box, +} + +impl PresetUpsertSchema { + pub fn new(value: models::PresetUpsertSchemaValue) -> PresetUpsertSchema { + PresetUpsertSchema { + value: Box::new(value), + } + } +} diff --git a/typesense_codegen/src/models/preset_upsert_schema_value.rs b/typesense_codegen/src/models/preset_upsert_schema_value.rs new file mode 100644 index 0000000..43335aa --- /dev/null +++ b/typesense_codegen/src/models/preset_upsert_schema_value.rs @@ -0,0 +1,25 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PresetUpsertSchemaValue { + SearchParameters(Box), + MultiSearchSearchesParameter(Box), +} + +impl Default for PresetUpsertSchemaValue { + fn default() -> Self { + Self::SearchParameters(Default::default()) + } +} diff --git a/typesense_codegen/src/models/presets_retrieve_schema.rs b/typesense_codegen/src/models/presets_retrieve_schema.rs new file mode 100644 index 0000000..e64ecf1 --- /dev/null +++ b/typesense_codegen/src/models/presets_retrieve_schema.rs @@ -0,0 +1,24 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct PresetsRetrieveSchema { + #[serde(rename = "presets")] + pub presets: Vec, +} + +impl PresetsRetrieveSchema { + pub fn new(presets: Vec) -> PresetsRetrieveSchema { + PresetsRetrieveSchema { presets } + } +} diff --git a/typesense_codegen/src/models/schema_change_status.rs b/typesense_codegen/src/models/schema_change_status.rs new file mode 100644 index 0000000..22bb410 --- /dev/null +++ b/typesense_codegen/src/models/schema_change_status.rs @@ -0,0 +1,35 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SchemaChangeStatus { + /// Name of the collection being modified + #[serde(rename = "collection", skip_serializing_if = "Option::is_none")] + pub collection: Option, + /// Number of documents that have been validated + #[serde(rename = "validated_docs", skip_serializing_if = "Option::is_none")] + pub validated_docs: Option, + /// Number of documents that have been altered + #[serde(rename = "altered_docs", skip_serializing_if = "Option::is_none")] + pub altered_docs: Option, +} + +impl SchemaChangeStatus { + pub fn new() -> SchemaChangeStatus { + SchemaChangeStatus { + collection: None, + validated_docs: None, + altered_docs: None, + } + } +} diff --git a/typesense_codegen/src/models/scoped_key_parameters.rs b/typesense_codegen/src/models/scoped_key_parameters.rs deleted file mode 100644 index 4a88ffd..0000000 --- a/typesense_codegen/src/models/scoped_key_parameters.rs +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct ScopedKeyParameters { - #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] - pub filter_by: Option, - #[serde(rename = "expires_at", skip_serializing_if = "Option::is_none")] - pub expires_at: Option, -} - -impl ScopedKeyParameters { - pub fn new() -> ScopedKeyParameters { - ScopedKeyParameters { - filter_by: None, - expires_at: None, - } - } -} diff --git a/typesense_codegen/src/models/search_grouped_hit.rs b/typesense_codegen/src/models/search_grouped_hit.rs index b9e19cd..434b8fc 100644 --- a/typesense_codegen/src/models/search_grouped_hit.rs +++ b/typesense_codegen/src/models/search_grouped_hit.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchGroupedHit { #[serde(rename = "found", skip_serializing_if = "Option::is_none")] @@ -16,15 +19,15 @@ pub struct SearchGroupedHit { pub group_key: Vec, /// The documents that matched the search query #[serde(rename = "hits")] - pub hits: Vec>, + pub hits: Vec>, } impl SearchGroupedHit { pub fn new( group_key: Vec, - hits: Vec>, - ) -> Self { - Self { + hits: Vec>, + ) -> SearchGroupedHit { + SearchGroupedHit { found: None, group_key, hits, diff --git a/typesense_codegen/src/models/search_highlight.rs b/typesense_codegen/src/models/search_highlight.rs index f5b7e2a..c45afcc 100644 --- a/typesense_codegen/src/models/search_highlight.rs +++ b/typesense_codegen/src/models/search_highlight.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchHighlight { #[serde(rename = "field", skip_serializing_if = "Option::is_none")] diff --git a/typesense_codegen/src/models/search_override.rs b/typesense_codegen/src/models/search_override.rs index ed41718..b1f8353 100644 --- a/typesense_codegen/src/models/search_override.rs +++ b/typesense_codegen/src/models/search_override.rs @@ -3,21 +3,24 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverride { #[serde(rename = "rule")] - pub rule: Box, + pub rule: Box, /// List of document `id`s that should be included in the search results with their corresponding `position`s. #[serde(rename = "includes", skip_serializing_if = "Option::is_none")] - pub includes: Option>, + pub includes: Option>, /// List of document `id`s that should be excluded from the search results. #[serde(rename = "excludes", skip_serializing_if = "Option::is_none")] - pub excludes: Option>, + pub excludes: Option>, /// A filter by clause that is applied to any search query that matches the override rule. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, @@ -27,18 +30,49 @@ pub struct SearchOverride { skip_serializing_if = "Option::is_none" )] pub remove_matched_tokens: Option, + /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] + pub metadata: Option, + /// A sort by clause that is applied to any search query that matches the override rule. + #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] + pub sort_by: Option, + /// Replaces the current search query with this value, when the search query matches the override rule. + #[serde(rename = "replace_query", skip_serializing_if = "Option::is_none")] + pub replace_query: Option, + /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] + pub filter_curated_hits: Option, + /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + #[serde(rename = "effective_from_ts", skip_serializing_if = "Option::is_none")] + pub effective_from_ts: Option, + /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + #[serde(rename = "effective_to_ts", skip_serializing_if = "Option::is_none")] + pub effective_to_ts: Option, + /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + #[serde(rename = "stop_processing", skip_serializing_if = "Option::is_none")] + pub stop_processing: Option, #[serde(rename = "id")] pub id: String, } impl SearchOverride { - pub fn new(rule: crate::models::SearchOverrideRule, id: String) -> SearchOverride { + pub fn new(rule: models::SearchOverrideRule, id: String) -> SearchOverride { SearchOverride { rule: Box::new(rule), includes: None, excludes: None, filter_by: None, remove_matched_tokens: None, + metadata: None, + sort_by: None, + replace_query: None, + filter_curated_hits: None, + effective_from_ts: None, + effective_to_ts: None, + stop_processing: None, id, } } diff --git a/typesense_codegen/src/models/search_override_delete_response.rs b/typesense_codegen/src/models/search_override_delete_response.rs new file mode 100644 index 0000000..3949320 --- /dev/null +++ b/typesense_codegen/src/models/search_override_delete_response.rs @@ -0,0 +1,25 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchOverrideDeleteResponse { + /// The id of the override that was deleted + #[serde(rename = "id")] + pub id: String, +} + +impl SearchOverrideDeleteResponse { + pub fn new(id: String) -> SearchOverrideDeleteResponse { + SearchOverrideDeleteResponse { id } + } +} diff --git a/typesense_codegen/src/models/search_override_exclude.rs b/typesense_codegen/src/models/search_override_exclude.rs index 1cea902..58b01b9 100644 --- a/typesense_codegen/src/models/search_override_exclude.rs +++ b/typesense_codegen/src/models/search_override_exclude.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideExclude { /// document id that should be excluded from the search results. diff --git a/typesense_codegen/src/models/search_override_include.rs b/typesense_codegen/src/models/search_override_include.rs index 3cdbff2..7756358 100644 --- a/typesense_codegen/src/models/search_override_include.rs +++ b/typesense_codegen/src/models/search_override_include.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideInclude { /// document id that should be included diff --git a/typesense_codegen/src/models/search_override_rule.rs b/typesense_codegen/src/models/search_override_rule.rs index f5a339b..de9ebf5 100644 --- a/typesense_codegen/src/models/search_override_rule.rs +++ b/typesense_codegen/src/models/search_override_rule.rs @@ -3,27 +3,40 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideRule { + /// List of tag values to associate with this override rule. + #[serde(rename = "tags", skip_serializing_if = "Option::is_none")] + pub tags: Option>, /// Indicates what search queries should be overridden - #[serde(rename = "query")] - pub query: String, + #[serde(rename = "query", skip_serializing_if = "Option::is_none")] + pub query: Option, /// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. - #[serde(rename = "match")] - pub r#match: Match, + #[serde(rename = "match", skip_serializing_if = "Option::is_none")] + pub r#match: Option, + /// Indicates that the override should apply when the filter_by parameter in a search query exactly matches the string specified here (including backticks, spaces, brackets, etc). + #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] + pub filter_by: Option, } impl SearchOverrideRule { - pub fn new(query: String, r#match: Match) -> SearchOverrideRule { - SearchOverrideRule { query, r#match } + pub fn new() -> SearchOverrideRule { + SearchOverrideRule { + tags: None, + query: None, + r#match: None, + filter_by: None, + } } } - /// Indicates whether the match on the query term should be `exact` or `contains`. If we want to match all queries that contained the word `apple`, we will use the `contains` match instead. #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Match { diff --git a/typesense_codegen/src/models/search_override_schema.rs b/typesense_codegen/src/models/search_override_schema.rs index 7b3eedb..1b0eede 100644 --- a/typesense_codegen/src/models/search_override_schema.rs +++ b/typesense_codegen/src/models/search_override_schema.rs @@ -3,21 +3,24 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverrideSchema { #[serde(rename = "rule")] - pub rule: Box, + pub rule: Box, /// List of document `id`s that should be included in the search results with their corresponding `position`s. #[serde(rename = "includes", skip_serializing_if = "Option::is_none")] - pub includes: Option>, + pub includes: Option>, /// List of document `id`s that should be excluded from the search results. #[serde(rename = "excludes", skip_serializing_if = "Option::is_none")] - pub excludes: Option>, + pub excludes: Option>, /// A filter by clause that is applied to any search query that matches the override rule. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, @@ -27,16 +30,47 @@ pub struct SearchOverrideSchema { skip_serializing_if = "Option::is_none" )] pub remove_matched_tokens: Option, + /// Return a custom JSON object in the Search API response, when this rule is triggered. This can can be used to display a pre-defined message (eg: a promotion banner) on the front-end when a particular rule is triggered. + #[serde(rename = "metadata", skip_serializing_if = "Option::is_none")] + pub metadata: Option, + /// A sort by clause that is applied to any search query that matches the override rule. + #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] + pub sort_by: Option, + /// Replaces the current search query with this value, when the search query matches the override rule. + #[serde(rename = "replace_query", skip_serializing_if = "Option::is_none")] + pub replace_query: Option, + /// When set to true, the filter conditions of the query is applied to the curated records as well. Default: false. + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] + pub filter_curated_hits: Option, + /// A Unix timestamp that indicates the date/time from which the override will be active. You can use this to create override rules that start applying from a future point in time. + #[serde(rename = "effective_from_ts", skip_serializing_if = "Option::is_none")] + pub effective_from_ts: Option, + /// A Unix timestamp that indicates the date/time until which the override will be active. You can use this to create override rules that stop applying after a period of time. + #[serde(rename = "effective_to_ts", skip_serializing_if = "Option::is_none")] + pub effective_to_ts: Option, + /// When set to true, override processing will stop at the first matching rule. When set to false override processing will continue and multiple override actions will be triggered in sequence. Overrides are processed in the lexical sort order of their id field. Default: true. + #[serde(rename = "stop_processing", skip_serializing_if = "Option::is_none")] + pub stop_processing: Option, } impl SearchOverrideSchema { - pub fn new(rule: crate::models::SearchOverrideRule) -> SearchOverrideSchema { + pub fn new(rule: models::SearchOverrideRule) -> SearchOverrideSchema { SearchOverrideSchema { rule: Box::new(rule), includes: None, excludes: None, filter_by: None, remove_matched_tokens: None, + metadata: None, + sort_by: None, + replace_query: None, + filter_curated_hits: None, + effective_from_ts: None, + effective_to_ts: None, + stop_processing: None, } } } diff --git a/typesense_codegen/src/models/search_overrides_response.rs b/typesense_codegen/src/models/search_overrides_response.rs index 1c4e49b..fd8aba3 100644 --- a/typesense_codegen/src/models/search_overrides_response.rs +++ b/typesense_codegen/src/models/search_overrides_response.rs @@ -3,19 +3,22 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchOverridesResponse { #[serde(rename = "overrides")] - pub overrides: Vec, + pub overrides: Vec, } impl SearchOverridesResponse { - pub fn new(overrides: Vec) -> SearchOverridesResponse { + pub fn new(overrides: Vec) -> SearchOverridesResponse { SearchOverridesResponse { overrides } } } diff --git a/typesense_codegen/src/models/search_parameters.rs b/typesense_codegen/src/models/search_parameters.rs index 3c1fb07..860beff 100644 --- a/typesense_codegen/src/models/search_parameters.rs +++ b/typesense_codegen/src/models/search_parameters.rs @@ -3,19 +3,30 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(bon::Builder)] +#[builder(on(String, into))] #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchParameters { /// The query text to search for in the collection. Use * as the search string to return all documents. This is typically useful when used in conjunction with filter_by. - #[serde(rename = "q")] - pub q: String, + #[serde(rename = "q", skip_serializing_if = "Option::is_none")] + pub q: Option, /// A list of `string` fields that should be queried against. Multiple fields are separated with a comma. - #[serde(rename = "query_by")] - pub query_by: String, + #[serde(rename = "query_by", skip_serializing_if = "Option::is_none")] + pub query_by: Option, + /// Whether to use natural language processing to parse the query. + #[serde(rename = "nl_query", skip_serializing_if = "Option::is_none")] + pub nl_query: Option, + /// The ID of the natural language model to use. + #[serde(rename = "nl_model_id", skip_serializing_if = "Option::is_none")] + pub nl_model_id: Option, /// The relative weight to give each `query_by` field when ranking results. This can be used to boost fields in priority, when looking for matches. Multiple fields are separated with a comma. #[serde(rename = "query_by_weights", skip_serializing_if = "Option::is_none")] pub query_by_weights: Option, @@ -34,9 +45,15 @@ pub struct SearchParameters { /// 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. #[serde(rename = "max_extra_suffix", skip_serializing_if = "Option::is_none")] pub max_extra_suffix: Option, - /// 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 &&. #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, + /// Controls the number of similar words that Typesense considers during fuzzy search on filter_by values. Useful for controlling prefix matches like company_name:Acm*. + #[serde( + rename = "max_filter_by_candidates", + skip_serializing_if = "Option::is_none" + )] + pub max_filter_by_candidates: Option, /// A list of numerical fields and their corresponding sort orders that will be used for ordering your results. Up to 3 sort fields can be specified. The text similarity score is exposed as a special `_text_match` field that you can use in the list of sorting fields. If no `sort_by` parameter is specified, results are sorted by `_text_match:desc,default_sorting_field:desc` #[serde(rename = "sort_by", skip_serializing_if = "Option::is_none")] pub sort_by: Option, @@ -58,7 +75,7 @@ pub struct SearchParameters { /// Number of results to fetch per page. Default: 10 #[serde(rename = "per_page", skip_serializing_if = "Option::is_none")] pub per_page: Option, - /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. + /// Number of hits to fetch. Can be used as an alternative to the per_page parameter. Default: 10. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option, /// Identifies the starting point to return hits from a result set. Can be used as an alternative to the page parameter. @@ -70,6 +87,12 @@ pub struct SearchParameters { /// Maximum number of hits to be returned for every group. If the `group_limit` is set as `K` then only the top K hits in each group are returned in the response. Default: 3 #[serde(rename = "group_limit", skip_serializing_if = "Option::is_none")] pub group_limit: Option, + /// Setting this parameter to true will place all documents that have a null value in the group_by field, into a single group. Setting this parameter to false, will cause each document with a null value in the group_by field to not be grouped with other documents. Default: true + #[serde( + rename = "group_missing_values", + skip_serializing_if = "Option::is_none" + )] + pub group_missing_values: Option, /// List of fields from the document to include in the search result #[serde(rename = "include_fields", skip_serializing_if = "Option::is_none")] pub include_fields: Option, @@ -103,34 +126,66 @@ pub struct SearchParameters { skip_serializing_if = "Option::is_none" )] pub enable_highlight_v1: Option, + /// Flag for enabling/disabling analytics aggregation for specific search queries (for e.g. those originating from a test script). + #[serde(rename = "enable_analytics", skip_serializing_if = "Option::is_none")] + pub enable_analytics: Option, /// Field values under this length will be fully highlighted, instead of showing a snippet of relevant portion. Default: 30 #[serde(rename = "snippet_threshold", skip_serializing_if = "Option::is_none")] pub snippet_threshold: Option, + /// List of synonym set names to associate with this search query + #[serde(rename = "synonym_sets", skip_serializing_if = "Option::is_none")] + pub synonym_sets: Option, /// If the number of results found for a specific query is less than this number, Typesense will attempt to drop the tokens in the query until enough results are found. Tokens that have the least individual hits are dropped first. Set to 0 to disable. Default: 10 #[serde( rename = "drop_tokens_threshold", skip_serializing_if = "Option::is_none" )] pub drop_tokens_threshold: Option, + #[serde(rename = "drop_tokens_mode", skip_serializing_if = "Option::is_none")] + pub drop_tokens_mode: Option, /// If the number of results found for a specific query is less than this number, Typesense will attempt to look for tokens with more typos until enough results are found. Default: 100 #[serde( rename = "typo_tokens_threshold", skip_serializing_if = "Option::is_none" )] pub typo_tokens_threshold: Option, - /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. + /// Set this parameter to false to disable typos on alphanumerical query tokens. Default: true. + #[serde( + rename = "enable_typos_for_alpha_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] + pub enable_typos_for_alpha_numerical_tokens: Option, + /// Whether the filter_by condition of the search query should be applicable to curated results (override definitions, pinned hits, hidden hits, etc.). Default: false + #[serde( + rename = "filter_curated_hits", + skip_serializing_if = "Option::is_none" + )] + pub filter_curated_hits: Option, + /// If you have some synonyms defined but want to disable all of them for a particular search query, set enable_synonyms to false. Default: true + #[serde(rename = "enable_synonyms", skip_serializing_if = "Option::is_none")] + pub enable_synonyms: Option, + /// Allow synonym resolution on word prefixes in the query. Default: false + #[serde(rename = "synonym_prefix", skip_serializing_if = "Option::is_none")] + pub synonym_prefix: Option, + /// Allow synonym resolution on typo-corrected words in the query. Default: 0 + #[serde(rename = "synonym_num_typos", skip_serializing_if = "Option::is_none")] + pub synonym_num_typos: Option, + /// A list of records to unconditionally include in the search results at specific positions. An example use case would be to feature or promote certain items on the top of search results. A list of `record_id:hit_position`. Eg: to include a record with ID 123 at Position 1 and another record with ID 456 at Position 5, you'd specify `123:1,456:5`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "pinned_hits", skip_serializing_if = "Option::is_none")] pub pinned_hits: Option, /// A list of records to unconditionally hide from search results. A list of `record_id`s to hide. Eg: to hide records with IDs 123 and 456, you'd specify `123,456`. You could also use the Overrides feature to override search results based on rules. Overrides are applied first, followed by `pinned_hits` and finally `hidden_hits`. #[serde(rename = "hidden_hits", skip_serializing_if = "Option::is_none")] pub hidden_hits: Option, - /// A list of custom fields that must be highlighted even if you don't query for them + /// Comma separated list of tags to trigger the curations rules that match the tags. + #[serde(rename = "override_tags", skip_serializing_if = "Option::is_none")] + pub override_tags: Option, + /// A list of custom fields that must be highlighted even if you don't query for them #[serde(rename = "highlight_fields", skip_serializing_if = "Option::is_none")] pub highlight_fields: Option, /// Treat space as typo: search for q=basket ball if q=basketball is not found or vice-versa. Splitting/joining of tokens will only be attempted if the original query produces no results. To always trigger this behavior, set value to `always``. To disable, set value to `off`. Default is `fallback`. #[serde(rename = "split_join_tokens", skip_serializing_if = "Option::is_none")] pub split_join_tokens: Option, - /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same + /// You can index content from any logographic language into Typesense if you are able to segment / split the text into space-separated words yourself before indexing and querying. Set this parameter to true to do the same #[serde( rename = "pre_segmented_query", skip_serializing_if = "Option::is_none" @@ -157,22 +212,34 @@ pub struct SearchParameters { skip_serializing_if = "Option::is_none" )] pub prioritize_token_position: Option, - /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). + /// Make Typesense prioritize documents where the query words appear in more number of fields. + #[serde( + rename = "prioritize_num_matching_fields", + skip_serializing_if = "Option::is_none" + )] + pub prioritize_num_matching_fields: Option, + /// Make Typesense disable typos for numerical tokens. + #[serde( + rename = "enable_typos_for_numerical_tokens", + skip_serializing_if = "Option::is_none" + )] + pub enable_typos_for_numerical_tokens: Option, + /// Setting this to true will make Typesense consider all prefixes and typo corrections of the words in the query without stopping early when enough results are found (drop_tokens_threshold and typo_tokens_threshold configurations are ignored). #[serde(rename = "exhaustive_search", skip_serializing_if = "Option::is_none")] pub exhaustive_search: Option, - /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. + /// Typesense will attempt to return results early if the cutoff time has elapsed. This is not a strict guarantee and facet computation is not bound by this parameter. #[serde(rename = "search_cutoff_ms", skip_serializing_if = "Option::is_none")] pub search_cutoff_ms: Option, /// Enable server side caching of search query results. By default, caching is disabled. #[serde(rename = "use_cache", skip_serializing_if = "Option::is_none")] pub use_cache: Option, - /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. + /// The duration (in seconds) that determines how long the search query is cached. This value can be set on a per-query basis. Default: 60. #[serde(rename = "cache_ttl", skip_serializing_if = "Option::is_none")] pub cache_ttl: Option, - /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 1-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_1typo", skip_serializing_if = "Option::is_none")] pub min_len_1typo: Option, - /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. + /// Minimum word length for 2-typo correction to be applied. The value of num_typos is still treated as the maximum allowed typos. #[serde(rename = "min_len_2typo", skip_serializing_if = "Option::is_none")] pub min_len_2typo: Option, /// Vector query expression for fetching documents \"closest\" to a given query/document vector. @@ -190,13 +257,42 @@ pub struct SearchParameters { skip_serializing_if = "Option::is_none" )] pub remote_embedding_num_tries: Option, + /// Choose the underlying faceting strategy used. Comma separated string of allows values: exhaustive, top_values or automatic (default). + #[serde(rename = "facet_strategy", skip_serializing_if = "Option::is_none")] + pub facet_strategy: Option, + /// Name of the stopwords set to apply for this search, the keywords present in the set will be removed from the search query. + #[serde(rename = "stopwords", skip_serializing_if = "Option::is_none")] + pub stopwords: Option, + /// Comma separated string of nested facet fields whose parent object should be returned in facet response. + #[serde( + rename = "facet_return_parent", + skip_serializing_if = "Option::is_none" + )] + pub facet_return_parent: Option, + /// The base64 encoded audio file in 16 khz 16-bit WAV format. + #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] + pub voice_query: Option, + /// Enable conversational search. + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option, + /// The Id of Conversation Model to be used. + #[serde( + rename = "conversation_model_id", + skip_serializing_if = "Option::is_none" + )] + pub conversation_model_id: Option, + /// The Id of a previous conversation to continue, this tells Typesense to include prior context when communicating with the LLM. + #[serde(rename = "conversation_id", skip_serializing_if = "Option::is_none")] + pub conversation_id: Option, } impl SearchParameters { - pub fn new(q: String, query_by: String) -> SearchParameters { + pub fn new() -> SearchParameters { SearchParameters { - q, - query_by, + q: None, + query_by: None, + nl_query: None, + nl_model_id: None, query_by_weights: None, text_match_type: None, prefix: None, @@ -204,6 +300,7 @@ impl SearchParameters { max_extra_prefix: None, max_extra_suffix: None, filter_by: None, + max_filter_by_candidates: None, sort_by: None, facet_by: None, max_facet_values: None, @@ -215,6 +312,7 @@ impl SearchParameters { offset: None, group_by: None, group_limit: None, + group_missing_values: None, include_fields: None, exclude_fields: None, highlight_full_fields: None, @@ -222,11 +320,20 @@ impl SearchParameters { highlight_start_tag: None, highlight_end_tag: None, enable_highlight_v1: None, + enable_analytics: None, snippet_threshold: None, + synonym_sets: None, drop_tokens_threshold: None, + drop_tokens_mode: None, typo_tokens_threshold: None, + enable_typos_for_alpha_numerical_tokens: None, + filter_curated_hits: None, + enable_synonyms: None, + synonym_prefix: None, + synonym_num_typos: None, pinned_hits: None, hidden_hits: None, + override_tags: None, highlight_fields: None, split_join_tokens: None, pre_segmented_query: None, @@ -235,6 +342,8 @@ impl SearchParameters { prioritize_exact_match: None, max_candidates: None, prioritize_token_position: None, + prioritize_num_matching_fields: None, + enable_typos_for_numerical_tokens: None, exhaustive_search: None, search_cutoff_ms: None, use_cache: None, @@ -244,6 +353,13 @@ impl SearchParameters { vector_query: None, remote_embedding_timeout_ms: None, remote_embedding_num_tries: None, + facet_strategy: None, + stopwords: None, + facet_return_parent: None, + voice_query: None, + conversation: None, + conversation_model_id: None, + conversation_id: None, } } } diff --git a/typesense_codegen/src/models/search_result_request_params.rs b/typesense_codegen/src/models/search_request_params.rs similarity index 58% rename from typesense_codegen/src/models/search_result_request_params.rs rename to typesense_codegen/src/models/search_request_params.rs index 94e323b..7e67048 100644 --- a/typesense_codegen/src/models/search_result_request_params.rs +++ b/typesense_codegen/src/models/search_request_params.rs @@ -3,27 +3,33 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct SearchResultRequestParams { +pub struct SearchRequestParams { #[serde(rename = "collection_name")] pub collection_name: String, #[serde(rename = "q")] pub q: String, #[serde(rename = "per_page")] pub per_page: i32, + #[serde(rename = "voice_query", skip_serializing_if = "Option::is_none")] + pub voice_query: Option>, } -impl SearchResultRequestParams { - pub fn new(collection_name: String, q: String, per_page: i32) -> SearchResultRequestParams { - SearchResultRequestParams { +impl SearchRequestParams { + pub fn new(collection_name: String, q: String, per_page: i32) -> SearchRequestParams { + SearchRequestParams { collection_name, q, per_page, + voice_query: None, } } } diff --git a/typesense_codegen/src/models/search_request_params_voice_query.rs b/typesense_codegen/src/models/search_request_params_voice_query.rs new file mode 100644 index 0000000..97e78ef --- /dev/null +++ b/typesense_codegen/src/models/search_request_params_voice_query.rs @@ -0,0 +1,26 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchRequestParamsVoiceQuery { + #[serde(rename = "transcribed_query", skip_serializing_if = "Option::is_none")] + pub transcribed_query: Option, +} + +impl SearchRequestParamsVoiceQuery { + pub fn new() -> SearchRequestParamsVoiceQuery { + SearchRequestParamsVoiceQuery { + transcribed_query: None, + } + } +} diff --git a/typesense_codegen/src/models/search_result.rs b/typesense_codegen/src/models/search_result.rs index 11527ab..f5ea5b5 100644 --- a/typesense_codegen/src/models/search_result.rs +++ b/typesense_codegen/src/models/search_result.rs @@ -3,18 +3,23 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchResult { #[serde(rename = "facet_counts", skip_serializing_if = "Option::is_none")] - pub facet_counts: Option>, + pub facet_counts: Option>, /// The number of documents found #[serde(rename = "found", skip_serializing_if = "Option::is_none")] pub found: Option, + #[serde(rename = "found_docs", skip_serializing_if = "Option::is_none")] + pub found_docs: Option, /// The number of milliseconds the search took #[serde(rename = "search_time_ms", skip_serializing_if = "Option::is_none")] pub search_time_ms: Option, @@ -28,19 +33,28 @@ pub struct SearchResult { #[serde(rename = "page", skip_serializing_if = "Option::is_none")] pub page: Option, #[serde(rename = "grouped_hits", skip_serializing_if = "Option::is_none")] - pub grouped_hits: Option>>, + pub grouped_hits: Option>>, /// The documents that matched the search query #[serde(rename = "hits", skip_serializing_if = "Option::is_none")] - pub hits: Option>>, + pub hits: Option>>, #[serde(rename = "request_params", skip_serializing_if = "Option::is_none")] - pub request_params: Option>, + pub request_params: Option>, + #[serde(rename = "conversation", skip_serializing_if = "Option::is_none")] + pub conversation: Option>, + /// Returned only for union query response. + #[serde( + rename = "union_request_params", + skip_serializing_if = "Option::is_none" + )] + pub union_request_params: Option>, } impl SearchResult { - pub fn new() -> Self { - Self { + pub fn new() -> SearchResult { + SearchResult { facet_counts: None, found: None, + found_docs: None, search_time_ms: None, out_of: None, search_cutoff: None, @@ -48,6 +62,8 @@ impl SearchResult { grouped_hits: None, hits: None, request_params: None, + conversation: None, + union_request_params: None, } } } diff --git a/typesense_codegen/src/models/search_result_conversation.rs b/typesense_codegen/src/models/search_result_conversation.rs new file mode 100644 index 0000000..380be44 --- /dev/null +++ b/typesense_codegen/src/models/search_result_conversation.rs @@ -0,0 +1,40 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchResultConversation { + #[serde(rename = "answer")] + pub answer: String, + #[serde(rename = "conversation_history")] + pub conversation_history: Vec, + #[serde(rename = "conversation_id")] + pub conversation_id: String, + #[serde(rename = "query")] + pub query: String, +} + +impl SearchResultConversation { + pub fn new( + answer: String, + conversation_history: Vec, + conversation_id: String, + query: String, + ) -> SearchResultConversation { + SearchResultConversation { + answer, + conversation_history, + conversation_id, + query, + } + } +} diff --git a/typesense_codegen/src/models/search_result_hit.rs b/typesense_codegen/src/models/search_result_hit.rs index d637e65..abe92e4 100644 --- a/typesense_codegen/src/models/search_result_hit.rs +++ b/typesense_codegen/src/models/search_result_hit.rs @@ -3,44 +3,57 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchResultHit { /// (Deprecated) Contains highlighted portions of the search fields #[serde(rename = "highlights", skip_serializing_if = "Option::is_none")] - pub highlights: Option>, + pub highlights: Option>, /// Highlighted version of the matching document #[serde(rename = "highlight", skip_serializing_if = "Option::is_none")] - pub highlight: Option<::std::collections::HashMap>, + pub highlight: Option>, /// Can be any key-value pair #[serde(rename = "document", skip_serializing_if = "Option::is_none")] pub document: Option, #[serde(rename = "text_match", skip_serializing_if = "Option::is_none")] pub text_match: Option, + #[serde(rename = "text_match_info", skip_serializing_if = "Option::is_none")] + pub text_match_info: Option>, /// Can be any key-value pair #[serde( rename = "geo_distance_meters", skip_serializing_if = "Option::is_none" )] - pub geo_distance_meters: Option<::std::collections::HashMap>, + pub geo_distance_meters: Option>, /// Distance between the query vector and matching document's vector value #[serde(rename = "vector_distance", skip_serializing_if = "Option::is_none")] pub vector_distance: Option, + #[serde(rename = "hybrid_search_info", skip_serializing_if = "Option::is_none")] + pub hybrid_search_info: Option>, + /// Returned only for union query response. Indicates the index of the query which this document matched to. + #[serde(rename = "search_index", skip_serializing_if = "Option::is_none")] + pub search_index: Option, } impl SearchResultHit { - pub fn new() -> Self { - Self { + pub fn new() -> SearchResultHit { + SearchResultHit { highlights: None, highlight: None, document: None, text_match: None, + text_match_info: None, geo_distance_meters: None, vector_distance: None, + hybrid_search_info: None, + search_index: None, } } } diff --git a/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs new file mode 100644 index 0000000..ed0bea0 --- /dev/null +++ b/typesense_codegen/src/models/search_result_hit_hybrid_search_info.rs @@ -0,0 +1,29 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// SearchResultHitHybridSearchInfo : Information about hybrid search scoring +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchResultHitHybridSearchInfo { + /// Combined score from rank fusion of text and vector search + #[serde(rename = "rank_fusion_score", skip_serializing_if = "Option::is_none")] + pub rank_fusion_score: Option, +} + +impl SearchResultHitHybridSearchInfo { + /// Information about hybrid search scoring + pub fn new() -> SearchResultHitHybridSearchInfo { + SearchResultHitHybridSearchInfo { + rank_fusion_score: None, + } + } +} diff --git a/typesense_codegen/src/models/search_result_hit_text_match_info.rs b/typesense_codegen/src/models/search_result_hit_text_match_info.rs new file mode 100644 index 0000000..e77c40f --- /dev/null +++ b/typesense_codegen/src/models/search_result_hit_text_match_info.rs @@ -0,0 +1,44 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchResultHitTextMatchInfo { + #[serde(rename = "best_field_score", skip_serializing_if = "Option::is_none")] + pub best_field_score: Option, + #[serde(rename = "best_field_weight", skip_serializing_if = "Option::is_none")] + pub best_field_weight: Option, + #[serde(rename = "fields_matched", skip_serializing_if = "Option::is_none")] + pub fields_matched: Option, + #[serde(rename = "num_tokens_dropped", skip_serializing_if = "Option::is_none")] + pub num_tokens_dropped: Option, + #[serde(rename = "score", skip_serializing_if = "Option::is_none")] + pub score: Option, + #[serde(rename = "tokens_matched", skip_serializing_if = "Option::is_none")] + pub tokens_matched: Option, + #[serde(rename = "typo_prefix_score", skip_serializing_if = "Option::is_none")] + pub typo_prefix_score: Option, +} + +impl SearchResultHitTextMatchInfo { + pub fn new() -> SearchResultHitTextMatchInfo { + SearchResultHitTextMatchInfo { + best_field_score: None, + best_field_weight: None, + fields_matched: None, + num_tokens_dropped: None, + score: None, + tokens_matched: None, + typo_prefix_score: None, + } + } +} diff --git a/typesense_codegen/src/models/search_synonym.rs b/typesense_codegen/src/models/search_synonym.rs index acf9fd8..3d81eb7 100644 --- a/typesense_codegen/src/models/search_synonym.rs +++ b/typesense_codegen/src/models/search_synonym.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchSynonym { /// For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. @@ -16,6 +19,12 @@ pub struct SearchSynonym { /// Array of words that should be considered as synonyms. #[serde(rename = "synonyms")] pub synonyms: Vec, + /// Locale for the synonym, leave blank to use the standard tokenizer. + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, + /// By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. + #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] + pub symbols_to_index: Option>, #[serde(rename = "id")] pub id: String, } @@ -25,6 +34,8 @@ impl SearchSynonym { SearchSynonym { root: None, synonyms, + locale: None, + symbols_to_index: None, id, } } diff --git a/typesense_codegen/src/models/search_synonym_delete_response.rs b/typesense_codegen/src/models/search_synonym_delete_response.rs new file mode 100644 index 0000000..c69e47b --- /dev/null +++ b/typesense_codegen/src/models/search_synonym_delete_response.rs @@ -0,0 +1,25 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchSynonymDeleteResponse { + /// The id of the synonym that was deleted + #[serde(rename = "id")] + pub id: String, +} + +impl SearchSynonymDeleteResponse { + pub fn new(id: String) -> SearchSynonymDeleteResponse { + SearchSynonymDeleteResponse { id } + } +} diff --git a/typesense_codegen/src/models/search_synonym_schema.rs b/typesense_codegen/src/models/search_synonym_schema.rs index eab5596..192829f 100644 --- a/typesense_codegen/src/models/search_synonym_schema.rs +++ b/typesense_codegen/src/models/search_synonym_schema.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchSynonymSchema { /// For 1-way synonyms, indicates the root word that words in the `synonyms` parameter map to. @@ -16,6 +19,12 @@ pub struct SearchSynonymSchema { /// Array of words that should be considered as synonyms. #[serde(rename = "synonyms")] pub synonyms: Vec, + /// Locale for the synonym, leave blank to use the standard tokenizer. + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, + /// By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is. + #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] + pub symbols_to_index: Option>, } impl SearchSynonymSchema { @@ -23,6 +32,8 @@ impl SearchSynonymSchema { SearchSynonymSchema { root: None, synonyms, + locale: None, + symbols_to_index: None, } } } diff --git a/typesense_codegen/src/models/search_synonyms_response.rs b/typesense_codegen/src/models/search_synonyms_response.rs index a3fefdf..40434ca 100644 --- a/typesense_codegen/src/models/search_synonyms_response.rs +++ b/typesense_codegen/src/models/search_synonyms_response.rs @@ -3,19 +3,22 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SearchSynonymsResponse { #[serde(rename = "synonyms")] - pub synonyms: Vec, + pub synonyms: Vec, } impl SearchSynonymsResponse { - pub fn new(synonyms: Vec) -> SearchSynonymsResponse { + pub fn new(synonyms: Vec) -> SearchSynonymsResponse { SearchSynonymsResponse { synonyms } } } diff --git a/typesense_codegen/src/models/snapshot_parameters.rs b/typesense_codegen/src/models/snapshot_parameters.rs deleted file mode 100644 index aa2c6a5..0000000 --- a/typesense_codegen/src/models/snapshot_parameters.rs +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Typesense API - * - * An open source search engine for building delightful search experiences. - * - * The version of the OpenAPI document: 0.25.0 - * - * Generated by: https://openapi-generator.tech - */ - -#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct SnapshotParameters { - #[serde(rename = "snapshot_path", skip_serializing_if = "Option::is_none")] - pub snapshot_path: Option, -} - -impl SnapshotParameters { - pub fn new() -> SnapshotParameters { - SnapshotParameters { - snapshot_path: None, - } - } -} diff --git a/typesense_codegen/src/models/stemming_dictionary.rs b/typesense_codegen/src/models/stemming_dictionary.rs new file mode 100644 index 0000000..e90942c --- /dev/null +++ b/typesense_codegen/src/models/stemming_dictionary.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StemmingDictionary { + /// Unique identifier for the dictionary + #[serde(rename = "id")] + pub id: String, + /// List of word mappings in the dictionary + #[serde(rename = "words")] + pub words: Vec, +} + +impl StemmingDictionary { + pub fn new(id: String, words: Vec) -> StemmingDictionary { + StemmingDictionary { id, words } + } +} diff --git a/typesense_codegen/src/models/stemming_dictionary_words_inner.rs b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs new file mode 100644 index 0000000..30cbd40 --- /dev/null +++ b/typesense_codegen/src/models/stemming_dictionary_words_inner.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StemmingDictionaryWordsInner { + /// The word form to be stemmed + #[serde(rename = "word")] + pub word: String, + /// The root form of the word + #[serde(rename = "root")] + pub root: String, +} + +impl StemmingDictionaryWordsInner { + pub fn new(word: String, root: String) -> StemmingDictionaryWordsInner { + StemmingDictionaryWordsInner { word, root } + } +} diff --git a/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs new file mode 100644 index 0000000..b1b6913 --- /dev/null +++ b/typesense_codegen/src/models/stopwords_set_retrieve_schema.rs @@ -0,0 +1,26 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StopwordsSetRetrieveSchema { + #[serde(rename = "stopwords")] + pub stopwords: Box, +} + +impl StopwordsSetRetrieveSchema { + pub fn new(stopwords: models::StopwordsSetSchema) -> StopwordsSetRetrieveSchema { + StopwordsSetRetrieveSchema { + stopwords: Box::new(stopwords), + } + } +} diff --git a/typesense_codegen/src/models/stopwords_set_schema.rs b/typesense_codegen/src/models/stopwords_set_schema.rs new file mode 100644 index 0000000..8f13dee --- /dev/null +++ b/typesense_codegen/src/models/stopwords_set_schema.rs @@ -0,0 +1,32 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StopwordsSetSchema { + #[serde(rename = "id")] + pub id: String, + #[serde(rename = "stopwords")] + pub stopwords: Vec, + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, +} + +impl StopwordsSetSchema { + pub fn new(id: String, stopwords: Vec) -> StopwordsSetSchema { + StopwordsSetSchema { + id, + stopwords, + locale: None, + } + } +} diff --git a/typesense_codegen/src/models/stopwords_set_upsert_schema.rs b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs new file mode 100644 index 0000000..1facab5 --- /dev/null +++ b/typesense_codegen/src/models/stopwords_set_upsert_schema.rs @@ -0,0 +1,29 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StopwordsSetUpsertSchema { + #[serde(rename = "stopwords")] + pub stopwords: Vec, + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, +} + +impl StopwordsSetUpsertSchema { + pub fn new(stopwords: Vec) -> StopwordsSetUpsertSchema { + StopwordsSetUpsertSchema { + stopwords, + locale: None, + } + } +} diff --git a/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs new file mode 100644 index 0000000..84703ac --- /dev/null +++ b/typesense_codegen/src/models/stopwords_sets_retrieve_all_schema.rs @@ -0,0 +1,24 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct StopwordsSetsRetrieveAllSchema { + #[serde(rename = "stopwords")] + pub stopwords: Vec, +} + +impl StopwordsSetsRetrieveAllSchema { + pub fn new(stopwords: Vec) -> StopwordsSetsRetrieveAllSchema { + StopwordsSetsRetrieveAllSchema { stopwords } + } +} diff --git a/typesense_codegen/src/models/success_status.rs b/typesense_codegen/src/models/success_status.rs index b7d3724..c88ecb9 100644 --- a/typesense_codegen/src/models/success_status.rs +++ b/typesense_codegen/src/models/success_status.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct SuccessStatus { #[serde(rename = "success")] diff --git a/typesense_codegen/src/models/synonym_item_schema.rs b/typesense_codegen/src/models/synonym_item_schema.rs new file mode 100644 index 0000000..bb03da3 --- /dev/null +++ b/typesense_codegen/src/models/synonym_item_schema.rs @@ -0,0 +1,43 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SynonymItemSchema { + /// Unique identifier for the synonym item + #[serde(rename = "id")] + pub id: String, + /// Array of words that should be considered as synonyms + #[serde(rename = "synonyms")] + pub synonyms: Vec, + /// For 1-way synonyms, indicates the root word that words in the synonyms parameter map to + #[serde(rename = "root", skip_serializing_if = "Option::is_none")] + pub root: Option, + /// Locale for the synonym, leave blank to use the standard tokenizer + #[serde(rename = "locale", skip_serializing_if = "Option::is_none")] + pub locale: Option, + /// By default, special characters are dropped from synonyms. Use this attribute to specify which special characters should be indexed as is + #[serde(rename = "symbols_to_index", skip_serializing_if = "Option::is_none")] + pub symbols_to_index: Option>, +} + +impl SynonymItemSchema { + pub fn new(id: String, synonyms: Vec) -> SynonymItemSchema { + SynonymItemSchema { + id, + synonyms, + root: None, + locale: None, + symbols_to_index: None, + } + } +} diff --git a/typesense_codegen/src/models/synonym_set_create_schema.rs b/typesense_codegen/src/models/synonym_set_create_schema.rs new file mode 100644 index 0000000..818ae98 --- /dev/null +++ b/typesense_codegen/src/models/synonym_set_create_schema.rs @@ -0,0 +1,25 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SynonymSetCreateSchema { + /// Array of synonym items + #[serde(rename = "items")] + pub items: Vec, +} + +impl SynonymSetCreateSchema { + pub fn new(items: Vec) -> SynonymSetCreateSchema { + SynonymSetCreateSchema { items } + } +} diff --git a/typesense_codegen/src/models/synonym_set_delete_schema.rs b/typesense_codegen/src/models/synonym_set_delete_schema.rs new file mode 100644 index 0000000..e127040 --- /dev/null +++ b/typesense_codegen/src/models/synonym_set_delete_schema.rs @@ -0,0 +1,25 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SynonymSetDeleteSchema { + /// Name of the deleted synonym set + #[serde(rename = "name")] + pub name: String, +} + +impl SynonymSetDeleteSchema { + pub fn new(name: String) -> SynonymSetDeleteSchema { + SynonymSetDeleteSchema { name } + } +} diff --git a/typesense_codegen/src/models/synonym_set_schema.rs b/typesense_codegen/src/models/synonym_set_schema.rs new file mode 100644 index 0000000..f9e171c --- /dev/null +++ b/typesense_codegen/src/models/synonym_set_schema.rs @@ -0,0 +1,28 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SynonymSetSchema { + /// Array of synonym items + #[serde(rename = "items")] + pub items: Vec, + /// Name of the synonym set + #[serde(rename = "name")] + pub name: String, +} + +impl SynonymSetSchema { + pub fn new(items: Vec, name: String) -> SynonymSetSchema { + SynonymSetSchema { items, name } + } +} diff --git a/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs new file mode 100644 index 0000000..612c1a5 --- /dev/null +++ b/typesense_codegen/src/models/synonym_sets_retrieve_schema.rs @@ -0,0 +1,25 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct SynonymSetsRetrieveSchema { + /// Array of synonym sets + #[serde(rename = "synonym_sets")] + pub synonym_sets: Vec, +} + +impl SynonymSetsRetrieveSchema { + pub fn new(synonym_sets: Vec) -> SynonymSetsRetrieveSchema { + SynonymSetsRetrieveSchema { synonym_sets } + } +} diff --git a/typesense_codegen/src/models/toggle_slow_request_log_request.rs b/typesense_codegen/src/models/toggle_slow_request_log_request.rs new file mode 100644 index 0000000..2957298 --- /dev/null +++ b/typesense_codegen/src/models/toggle_slow_request_log_request.rs @@ -0,0 +1,26 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct ToggleSlowRequestLogRequest { + #[serde(rename = "log-slow-requests-time-ms")] + pub log_slow_requests_time_ms: i32, +} + +impl ToggleSlowRequestLogRequest { + pub fn new(log_slow_requests_time_ms: i32) -> ToggleSlowRequestLogRequest { + ToggleSlowRequestLogRequest { + log_slow_requests_time_ms, + } + } +} diff --git a/typesense_codegen/src/models/update_documents_200_response.rs b/typesense_codegen/src/models/update_documents_200_response.rs index eff0990..88cc7b4 100644 --- a/typesense_codegen/src/models/update_documents_200_response.rs +++ b/typesense_codegen/src/models/update_documents_200_response.rs @@ -3,11 +3,14 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] pub struct UpdateDocuments200Response { /// The number of documents that have been updated diff --git a/typesense_codegen/src/models/update_documents_update_documents_parameters_parameter.rs b/typesense_codegen/src/models/update_documents_parameters.rs similarity index 52% rename from typesense_codegen/src/models/update_documents_update_documents_parameters_parameter.rs rename to typesense_codegen/src/models/update_documents_parameters.rs index aacf476..cf49cbb 100644 --- a/typesense_codegen/src/models/update_documents_update_documents_parameters_parameter.rs +++ b/typesense_codegen/src/models/update_documents_parameters.rs @@ -3,19 +3,22 @@ * * An open source search engine for building delightful search experiences. * - * The version of the OpenAPI document: 0.25.0 + * The version of the OpenAPI document: 30.0 * * Generated by: https://openapi-generator.tech */ +use crate::models; +use serde::{Deserialize, Serialize}; + #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] -pub struct UpdateDocumentsUpdateDocumentsParametersParameter { +pub struct UpdateDocumentsParameters { #[serde(rename = "filter_by", skip_serializing_if = "Option::is_none")] pub filter_by: Option, } -impl UpdateDocumentsUpdateDocumentsParametersParameter { - pub fn new() -> UpdateDocumentsUpdateDocumentsParametersParameter { - UpdateDocumentsUpdateDocumentsParametersParameter { filter_by: None } +impl UpdateDocumentsParameters { + pub fn new() -> UpdateDocumentsParameters { + UpdateDocumentsParameters { filter_by: None } } } diff --git a/typesense_codegen/src/models/voice_query_model_collection_config.rs b/typesense_codegen/src/models/voice_query_model_collection_config.rs new file mode 100644 index 0000000..38044c9 --- /dev/null +++ b/typesense_codegen/src/models/voice_query_model_collection_config.rs @@ -0,0 +1,26 @@ +/* + * Typesense API + * + * An open source search engine for building delightful search experiences. + * + * The version of the OpenAPI document: 30.0 + * + * Generated by: https://openapi-generator.tech + */ + +use crate::models; +use serde::{Deserialize, Serialize}; + +/// VoiceQueryModelCollectionConfig : Configuration for the voice query model +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct VoiceQueryModelCollectionConfig { + #[serde(rename = "model_name", skip_serializing_if = "Option::is_none")] + pub model_name: Option, +} + +impl VoiceQueryModelCollectionConfig { + /// Configuration for the voice query model + pub fn new() -> VoiceQueryModelCollectionConfig { + VoiceQueryModelCollectionConfig { model_name: None } + } +} diff --git a/typesense_derive/src/lib.rs b/typesense_derive/src/lib.rs index 4b1d70f..a4fc97e 100644 --- a/typesense_derive/src/lib.rs +++ b/typesense_derive/src/lib.rs @@ -63,7 +63,7 @@ fn impl_typesense_collection(item: ItemStruct) -> syn::Result { let default_sorting_field = if let Some(v) = default_sorting_field { quote! { - builder = builder.default_sorting_field(#v); + let builder = builder.default_sorting_field(#v); } } else { proc_macro2::TokenStream::new() @@ -71,19 +71,21 @@ fn impl_typesense_collection(item: ItemStruct) -> syn::Result { let enable_nested_fields = if let Some(v) = enable_nested_fields { quote! { - builder = builder.enable_nested_fields(Some(#v)); + let builder = builder.enable_nested_fields(#v); } } else { proc_macro2::TokenStream::new() }; let generated_code = quote! { - impl #impl_generics typesense::document::Document for #ident #ty_generics #where_clause { - fn collection_schema() -> typesense::collection_schema::CollectionSchema { - let name = #collection_name.to_owned(); + impl #impl_generics typesense::prelude::Document for #ident #ty_generics #where_clause { + const COLLECTION_NAME: &str = #collection_name; + + fn collection_schema() -> typesense::models::CollectionSchema { + let name = Self::COLLECTION_NAME.to_owned(); let fields = vec![#(#typesense_fields,)*]; - let mut builder = typesense::collection_schema::CollectionSchemaBuilder::new(name, fields); + let builder = typesense::models::CollectionSchema::builder().name(name).fields(fields); #default_sorting_field #enable_nested_fields @@ -285,13 +287,13 @@ fn to_typesense_field_type(field: &Field) -> syn::Result::to_typesense_type().to_owned() + <#ty as typesense::prelude::ToTypesenseField>::to_typesense_type().to_owned() ); Ok(quote! { - typesense::field::FieldBuilder::new(std::string::String::from(stringify!(#name)), #typesense_field_type) - .optional(#optional) - .facet(#facet) + typesense::models::Field::builder().name(std::string::String::from(stringify!(#name))).r#type(#typesense_field_type) + .maybe_optional(#optional) + .maybe_facet(#facet) .build() }) } diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 994b250..f13f365 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -5,8 +5,8 @@ version = "0.0.0" edition.workspace = true [dependencies] -reqwest = { version = "0.11", features = ["blocking"] } # "blocking" is simpler for scripts -anyhow = "1.0" -clap = { version = "4.0", features = ["derive"] } -serde = { version = "1.0", features = ["derive"] } -serde_yaml = "0.9" +anyhow = { workspace = true } +clap = { workspace = true } +reqwest = { version = "0.12", features = ["blocking"] } # "blocking" is simpler for scripts +serde = { workspace = true } +serde_yaml = { workspace = true } diff --git a/xtask/src/add_vendor_attributes.rs b/xtask/src/add_vendor_attributes.rs new file mode 100644 index 0000000..b6fa561 --- /dev/null +++ b/xtask/src/add_vendor_attributes.rs @@ -0,0 +1,66 @@ +use crate::vendor_attributes::VendorAttributes; +use serde_yaml::Mapping; + +pub fn add_vendor_attributes(doc_root: &mut Mapping) -> Result<(), String> { + println!("Adding custom x-* vendor attributes..."); + let mut attrs = VendorAttributes::new(doc_root); + + // Schemas + attrs.schema_builder([ + "CollectionSchema", + "Field", + "SearchParameters", + "MultiSearchParameters", + "MultiSearchCollectionParameters", + ])?; + + attrs.schema_generic_parameter([ + ("SearchResult", ""), + ("SearchGroupedHit", ""), + ("SearchResultHit", ""), + ("MultiSearchResult", ""), + ("MultiSearchResultItem", ""), + ])?; + + attrs.schema_field_type_overrides( + "SearchResult", + [ + ("hits", "Option>>"), + ("grouped_hits", "Option>>"), + ], + )?; + attrs.schema_field_type_overrides( + "SearchGroupedHit", + [("hits", "Vec>")], + )?; + attrs.schema_field_type_overrides("SearchResultHit", [("document", "Option")])?; + attrs.schema_field_type_overrides( + "MultiSearchResult", + [("results", "Vec>")], + )?; + + // Operations + attrs + .operation("/collections/{collectionName}/documents/search", "get") + .generic_parameter(" serde::Deserialize<'de> + Serialize>") + .return_type("models::SearchResult") + .done()?; + + attrs + .operation("/multi_search", "post") + .return_type("serde_json::Value") + .done()?; + + attrs + .operation("/collections/{collectionName}/documents/import", "post") + .body_is_raw_text() + .supports_plain_text() + .done()?; + + attrs + .operation("/collections/{collectionName}/documents/export", "get") + .supports_plain_text() + .done()?; + + Ok(()) +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 0fd68d2..1ef8017 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,9 +1,9 @@ use anyhow::{Context, Result}; use clap::{Parser, ValueEnum}; -use std::env; -use std::fs; -use std::process::Command; +use std::{env, fs, process::Command}; +mod add_vendor_attributes; mod preprocess_openapi; +mod vendor_attributes; use preprocess_openapi::preprocess_openapi_file; const SPEC_URL: &str = @@ -12,6 +12,7 @@ const SPEC_URL: &str = // Input spec file, expected in the project root. const INPUT_SPEC_FILE: &str = "openapi.yml"; const OUTPUT_PREPROCESSED_FILE: &str = "./preprocessed_openapi.yml"; +const CUSTOM_TEMPLATES_DIR: &str = "openapi-generator-template"; // Directory containing our custom templates // Output directory for the generated code. const OUTPUT_DIR: &str = "typesense_codegen"; @@ -117,14 +118,14 @@ fn task_codegen() -> Result<()> { .arg("rust") .arg("-o") .arg(format!("/local/{}", OUTPUT_DIR)) // Output path inside the container + .arg("-t") // specify the template directory + .arg(format!("/local/{}", CUSTOM_TEMPLATES_DIR)) .arg("--additional-properties") .arg("library=reqwest") .arg("--additional-properties") .arg("supportMiddleware=true") .arg("--additional-properties") .arg("useSingleRequestParameter=true") - // .arg("--additional-properties") - // .arg("useBonBuilder=true") .status() .context("Failed to execute Docker command. Is Docker installed and running?")?; @@ -135,5 +136,20 @@ fn task_codegen() -> Result<()> { println!("✅ Codegen task finished successfully."); println!(" Generated code is available in '{}'", OUTPUT_DIR); + + // Run cargo fmt after codegen + println!("▶️ Running cargo fmt..."); + let fmt_status = Command::new("cargo") + .arg("fmt") + .arg("--all") + .status() + .context("Failed to run cargo fmt")?; + + if !fmt_status.success() { + eprintln!("⚠️ cargo fmt failed (check your Rust installation)."); + } else { + println!("✅ Successfully formatted the code."); + } + Ok(()) } diff --git a/xtask/src/preprocess_openapi.rs b/xtask/src/preprocess_openapi.rs index 4189481..1e49ad5 100644 --- a/xtask/src/preprocess_openapi.rs +++ b/xtask/src/preprocess_openapi.rs @@ -1,6 +1,8 @@ use serde_yaml::{Mapping, Value}; use std::fs; +use crate::add_vendor_attributes::add_vendor_attributes; + // --- Main function to orchestrate the file reading, processing, and writing --- pub fn preprocess_openapi_file( input_path: &str, @@ -19,6 +21,10 @@ pub fn preprocess_openapi_file( // --- Step 2: Apply all the required transformations --- println!("Preprocessing the spec..."); + + add_vendor_attributes(doc_root)?; + + println!("Unwrapping parameters..."); unwrap_search_parameters(doc_root)?; unwrap_multi_search_parameters(doc_root)?; unwrap_parameters_by_path( @@ -33,21 +39,28 @@ pub fn preprocess_openapi_file( "/collections/{collectionName}/documents/export", "get", "exportDocumentsParameters", - Some("ExportDocumentsParameters"), // Copy schema to components + Some("ExportDocumentsParameters"), )?; unwrap_parameters_by_path( doc_root, "/collections/{collectionName}/documents", "patch", "updateDocumentsParameters", - Some("UpdateDocumentsParameters"), // Copy schema to components + Some("UpdateDocumentsParameters"), )?; unwrap_parameters_by_path( doc_root, "/collections/{collectionName}/documents", "delete", "deleteDocumentsParameters", - Some("DeleteDocumentsParameters"), // Copy schema to components + Some("DeleteDocumentsParameters"), + )?; + unwrap_parameters_by_path( + doc_root, + "/collections", + "get", + "getCollectionsParameters", + Some("GetCollectionsParameters"), )?; println!("Preprocessing complete."); diff --git a/xtask/src/vendor_attributes.rs b/xtask/src/vendor_attributes.rs new file mode 100644 index 0000000..17d411e --- /dev/null +++ b/xtask/src/vendor_attributes.rs @@ -0,0 +1,196 @@ +use serde_yaml::{Mapping, Value}; + +/// Where to apply a vendor (x-*) attribute. +pub enum VendorLocation<'a> { + Schema(&'a str), + SchemaField { schema: &'a str, field: &'a str }, + Operation { path: &'a str, method: &'a str }, +} + +/// Main helper struct that holds a mutable borrow of the OpenAPI root mapping. +pub struct VendorAttributes<'a> { + doc: &'a mut Mapping, +} + +impl<'a> VendorAttributes<'a> { + pub fn new(doc: &'a mut Mapping) -> Self { + Self { doc } + } + + // internal helpers + + fn traverse_value_mut(&mut self, keys: &[&str]) -> Option<&mut Value> { + if keys.is_empty() { + return None; + } + let mut cur: Option<&mut Value> = self.doc.get_mut(keys[0]); + for k in &keys[1..] { + cur = cur.and_then(|v| v.get_mut(k)); + } + cur + } + + fn get_map_mut(&mut self, keys: &[&str]) -> Result<&mut Mapping, String> { + self.traverse_value_mut(keys) + .and_then(|v| v.as_mapping_mut()) + .ok_or_else(|| format!("expected mapping at path: {}", keys.join("."))) + } + + #[inline] + fn insert_into_map(map: &mut Mapping, attr: &str, val: Value) { + map.insert(Value::String(attr.to_string()), val); + } + + fn set_attr( + &mut self, + location: VendorLocation<'_>, + attr: &str, + val: Value, + ) -> Result<&mut Self, String> { + match location { + VendorLocation::Schema(schema_name) => { + let map = self.get_map_mut(&["components", "schemas", schema_name])?; + Self::insert_into_map(map, attr, val); + Ok(self) + } + VendorLocation::SchemaField { schema, field } => { + let props_map = self + .get_map_mut(&["components", "schemas", schema, "properties"]) + .map_err(|_| format!("schema '{}' has no properties mapping", schema))?; + + let prop_key = Value::String(field.to_string()); + match props_map.get_mut(&prop_key) { + Some(existing_val) => { + if let Some(field_map) = existing_val.as_mapping_mut() { + Self::insert_into_map(field_map, attr, val); + Ok(self) + } else { + Err(format!( + "property '{}' in schema '{}' exists but is not a mapping; cannot set '{}'", + field, schema, attr + )) + } + } + None => { + let mut new_field_map = Mapping::new(); + new_field_map.insert(Value::String(attr.to_string()), val); + props_map.insert(prop_key, Value::Mapping(new_field_map)); + Ok(self) + } + } + } + VendorLocation::Operation { path, method } => { + let op_map = self + .get_map_mut(&["paths", path, method]) + .map_err(|_| format!("operation not found: {} {}", method, path))?; + Self::insert_into_map(op_map, attr, val); + Ok(self) + } + } + } + + pub fn schema_generic_parameter( + &mut self, + items: [(&str, &str); N], + ) -> Result<&mut Self, String> { + for (schema, generic) in items { + self.set_attr( + VendorLocation::Schema(schema), + "x-rust-generic-parameter", + Value::String(generic.into()), + )?; + } + Ok(self) + } + + pub fn schema_builder( + &mut self, + schemas: [&str; N], + ) -> Result<&mut Self, String> { + for schema in schemas { + self.set_attr( + VendorLocation::Schema(schema), + "x-rust-builder", + Value::Bool(true), + )?; + } + Ok(self) + } + + pub fn schema_field_type_overrides( + &mut self, + schema: &str, + overrides: [(&str, &str); N], + ) -> Result<&mut Self, String> { + for (field, rust_type) in overrides { + self.set_attr( + VendorLocation::SchemaField { schema, field }, + "x-rust-type", + Value::String(rust_type.into()), + )?; + } + Ok(self) + } + + pub fn operation<'b>(&'b mut self, path: &'b str, method: &'b str) -> OperationContext<'a, 'b> { + OperationContext { + vendor: self, + path, + method, + error: None, + } + } +} + +pub struct OperationContext<'a, 'b> { + vendor: &'b mut VendorAttributes<'a>, + path: &'b str, + method: &'b str, + error: Option, +} + +impl<'a, 'b> OperationContext<'a, 'b> { + fn try_set(&mut self, attr: &str, val: Value) { + if self.error.is_some() { + return; + } + if let Err(e) = self.vendor.set_attr( + VendorLocation::Operation { + path: self.path, + method: self.method, + }, + attr, + val, + ) { + self.error = Some(e); + } + } + + pub fn generic_parameter(mut self, generic: &str) -> Self { + self.try_set("x-rust-generic-parameter", Value::String(generic.into())); + self + } + + pub fn return_type(mut self, rust_type: &str) -> Self { + self.try_set("x-rust-return-type", Value::String(rust_type.into())); + self + } + + pub fn body_is_raw_text(mut self) -> Self { + self.try_set("x-rust-body-is-raw-text", Value::Bool(true)); + self + } + + pub fn supports_plain_text(mut self) -> Self { + self.try_set("x-supports-plain-text", Value::Bool(true)); + self + } + + /// Return to VendorAttributes if no errors, or propagate the first error + pub fn done(self) -> Result<&'b mut VendorAttributes<'a>, String> { + match self.error { + Some(err) => Err(err), + None => Ok(self.vendor), + } + } +}