### Install Python Client Source: https://typesense.org/docs/30.2/api/api-clients.md Install the Typesense Python client using pip. ```shell pip install typesense ``` -------------------------------- ### Install Ruby Client Source: https://typesense.org/docs/30.2/api/api-clients.md Install the Typesense Ruby client using the gem command. ```shell gem install typesense ``` -------------------------------- ### Example Records for Bucket Size Sorting Source: https://typesense.org/docs/30.2/api/search.md These are example records used to demonstrate the effect of `bucket_size` sorting. ```json [ {"title": "Mark Antony", "points": 100}, {"title": "Marks Spencer", "points": 200}, {"title": "Mark Twain", "points": 100}, {"title": "Mark Payne", "points": 300}, {"title": "Marks Henry", "points": 200}, {"title": "Mark Aurelius", "points": 200} ] ``` -------------------------------- ### Install PHP Client Source: https://typesense.org/docs/30.2/api/api-clients.md Install the Typesense PHP client using Composer. This command includes the necessary cURL client for HTTP communication. ```shell composer require php-http/curl-client typesense/typesense-php ``` -------------------------------- ### Typesense Server Configuration File Example Source: https://typesense.org/docs/30.2/api/server-configuration.md An example of the INI format for the Typesense server configuration file. Parameters are specified without the preceding '--' used in command-line arguments. ```ini ; /etc/typesense/typesense-server.ini [server] api-key = Rhsdhas2asasdasj2 data-dir = /var/lib/typesense log-dir = /var/log/typesense api-port = 9090 ``` -------------------------------- ### Install JavaScript Client Source: https://typesense.org/docs/30.2/api/api-clients.md Install the Typesense JavaScript client using npm for Node.js environments or include the minified script for browser-based applications. ```javascript // npm install typesense @babel/runtime // Browser ``` -------------------------------- ### Presets Get Source: https://typesense.org/docs/30.2/api/api-keys.md Get preset. ```APIDOC ## GET /presets/:name ### Description Get preset. ### Method GET ### Endpoint /presets/:name ``` -------------------------------- ### Federated Search Example Source: https://typesense.org/docs/30.2/api/federated-multi-search.md This example demonstrates how to perform a federated search across multiple collections ('products' and 'brands') in a single HTTP request. Common search parameters are applied to all individual searches. ```APIDOC ## Federated Search This section details how to perform a federated search, where each search request in the multi-search payload returns results independently. ### Method POST ### Endpoint /multi_search ### Query Parameters - **query_by** (string) - Required - Specifies the fields to search within for each collection. ### Request Body - **searches** (array) - Required - An array of individual search requests. - Each object in the array should contain: - **collection** (string) - Required - The name of the collection to search. - **q** (string) - Required - The search query. - **filter_by** (string) - Optional - Filters to apply to the search. ### Request Example ```json { "searches": [ { "collection": "products", "q": "shoe", "filter_by": "price:=[50..120]" }, { "collection": "brands", "q": "Nike" } ] } ``` ### Response (Response structure depends on the individual searches performed. Each search result will be independent.) ### Example Usage (Bash) ```bash curl "http://localhost:8108/multi_search?query_by=name" \ -X POST \ -H "Content-Type: application/json" \ -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \ -d '{ \ "searches": [ \ { \ "collection": "products", \ "q": "shoe", \ "filter_by": "price:=[50..120]" \ }, \ { \ "collection": "brands", \ "q": "Nike" \ } \ ] \ }' ``` ``` -------------------------------- ### Example Data for One-to-Many Join Source: https://typesense.org/docs/30.2/api/joins.md Sample data for authors and books collections to demonstrate one-to-many join behavior. ```json {"id": "0", ",first_name": "Enid", "last_name": "Blyton"} {"id": "1", ",first_name": "JK", "last_name": "Rowling"} ``` ```json {"title": "Famous Five", "author_id": "0"} {"title": "Secret Seven", "author_id": "0"} {"title": "Harry Potter", "author_id": "1"} ``` -------------------------------- ### Import Go Client Source: https://typesense.org/docs/30.2/api/api-clients.md Import the Typesense Go client library into your project using the go get command. This includes necessary API and pointer packages. ```go // $ go get github.com/typesense/typesense-go/v3/typesense import ( "github.com/typesense/typesense-go/v3/typesense" "github.com/typesense/typesense-go/v3/typesense/api" "github.com/typesense/typesense-go/v3/typesense/api/pointer" ) ``` -------------------------------- ### Create a Log Rule in Python Source: https://typesense.org/docs/30.2/api/analytics-query-suggestions.md This Python example shows how to create a log rule for analytics events. Ensure the Typesense client is properly initialized. ```python ruleName = 'product_events_log' ruleConfiguration = { "name": ruleName, "type": "log", "collection": "products", "event_type": "click", } client.analytics.rules.upsert(ruleName, ruleConfiguration) ``` -------------------------------- ### Load Typesense Server with Configuration File Source: https://typesense.org/docs/30.2/api/server-configuration.md Use this command to load Typesense server settings from a specified configuration file. This is an alternative to using command-line arguments. ```bash ./typesense-server --config=/etc/typesense/typesense-server.ini ``` -------------------------------- ### Example Field Definition with Regex Name Source: https://typesense.org/docs/30.2/api/collections.md Defines all fields starting with 'score_' as integers, enabling indexing and faceting. ```json {"name": "score_.*", "type": "integer", "facet": true, "index": true} ``` -------------------------------- ### Start a Conversation with Multi-Search Source: https://typesense.org/docs/30.2/api/conversational-search-rag.md Initiate a conversation by sending a query with conversation parameters to the multi_search endpoint. Ensure to specify an auto-embedding field for querying. ```shell curl 'http://localhost:8108/multi_search?q=can+you+suggest+an+action+series&conversation=true&conversation_model_id=conv-model-1' \ -X POST \ -H "Content-Type: application/json" \ -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \ -d '{ "searches": [ { "collection": "tv_shows", "query_by": "embedding", "exclude_fields": "embedding" } ] }' ``` -------------------------------- ### Create a Single Analytics Event (Go) Source: https://typesense.org/docs/30.2/api/analytics-query-suggestions.md Send a single analytics event using the Typesense Go client. This example demonstrates creating a 'product_clicks' event. ```go event := map[string]interface{}{ "name": "product_clicks", "data": map[string]interface{}{ "doc_id": "1022", "user_id": "111117", }, } client.Analytics().Events().Create(context.Background(), event) ``` -------------------------------- ### Stemming Dictionary Get Source: https://typesense.org/docs/30.2/api/api-keys.md Get stemming dictionary. ```APIDOC ## GET /stemming/dictionaries/:id ### Description Get stemming dictionary. ### Method GET ### Endpoint /stemming/dictionaries/:id ``` -------------------------------- ### Operations Schema Changes Get Source: https://typesense.org/docs/30.2/api/api-keys.md Get schema changes. ```APIDOC ## GET /operations/schema_changes ### Description Get schema changes. ### Method GET ### Endpoint /operations/schema_changes ``` -------------------------------- ### Create a Search Preset in Go Source: https://typesense.org/docs/30.2/api/search.md Use this snippet to create a new search preset named 'listing-view' for the 'products' collection. It configures wildcard search and sorting by popularity. ```go preset := &api.PresetUpsertSchema{} preset.Value.FromMultiSearchSearchesParameter(api.MultiSearchSearchesParameter{ Searches: []api.MultiSearchCollectionParameters{ { Collection: pointer.Any("products"), Q: pointer.Any("*"), SortBy: pointer.Any("popularity"), }, }, }) client.Presets().Upsert(context.Background(), "listing-view", preset) ``` -------------------------------- ### Get Conversation Model Source: https://typesense.org/docs/30.2/api/api-keys.md Retrieves a specific conversation model by its ID. This operation corresponds to a GET request to the /conversations/models/:id endpoint. ```APIDOC ## GET /conversations/models/:id ### Description Get conversation model. ### Method GET ### Endpoint /conversations/models/:id #### Path Parameters - **id** (string) - Required - The ID of the conversation model to retrieve. ``` -------------------------------- ### Perform Multi-Search with Vector Query (Go) Source: https://typesense.org/docs/30.2/api/vector-search.md This Go example shows how to perform a multi-search with a vector query. It utilizes the Typesense Go client library, setting up search parameters and executing the search. ```go searchRequests := api.MultiSearchSearchesParameter{ Searches: []api.MultiSearchCollectionParameters{ { Collection: pointer.Any("docs"), Q: pointer.Any("*"), VectorQuery: pointer.Any("embedding:([0.96826, 0.94, 0.39557, 0.306488], k:100)"), ExcludeFields: pointer.Any("embedding"), }, }, } commonSearchParams := &api.MultiSearchParams{} client.MultiSearch.Perform(context.Background(), commonSearchParams, searchRequests) ``` -------------------------------- ### Perform Multi-Search for Query Suggestions (Python) Source: https://typesense.org/docs/30.2/api/analytics-query-suggestions.md This Python example shows how to perform a multi-search to retrieve query suggestions and search results concurrently. Ensure the Typesense Python client is set up. ```python let searchRequests = { 'searches': [ { 'collection': 'product_queries', 'q': 'shoe', 'query_by': 'q' }, { 'collection': 'products', 'q': 'shoe', 'query_by': 'product_name' } ] } client.multi_search.perform(searchRequests, {}) ``` -------------------------------- ### Initialize Typesense Client (PHP) Source: https://typesense.org/docs/30.2/api/authentication.md Instantiate the Typesense client for PHP applications. Ensure the correct host, port, protocol, and API key are configured. ```php use Typesense\Client; $client = new Client( [ 'api_key' => 'abcd', 'nodes' => [ [ 'host' => 'localhost', // For Typesense Cloud use xxx.a1.typesense.net 'port' => '8108', // For Typesense Cloud use 443 'protocol' => 'http', // For Typesense Cloud use https ], ], 'connection_timeout_seconds' => 2, ] ); ``` -------------------------------- ### Run Typesense Server with Environment Variables Source: https://typesense.org/docs/30.2/api/server-configuration.md Starts the Typesense server using environment variables for data directory and API key configuration. Ensure these variables are set before running the command. ```bash TYPESENSE_DATA_DIR=/var/lib/typesense TYPESENSE_API_KEY=AS3das2awQ2 ./typesense-server ``` -------------------------------- ### Search Collection Documents (GET) Source: https://typesense.org/docs/30.2/api/search.md This operation allows you to search for documents within a specified collection using GET request. Query parameters are appended to the URL. ```APIDOC ## GET /collections/:collection/documents/search ### Description Searches for documents within a collection using GET request parameters. ### Method GET ### Endpoint /collections/:collection/documents/search ### Parameters #### Query Parameters - **q** (string) - Required - The search query string. - **query_by** (string) - Required - A comma-separated list of fields to search within. - **filter_by** (string) - Optional - A comma-separated list of filter expressions. - **sort_by** (string) - Optional - A comma-separated list of fields to sort by, with optional direction (asc/desc). - **page** (integer) - Optional - The page number of results to retrieve (default: 1). - **per_page** (integer) - Optional - The number of hits to return per page (default: 10). - **offset** (integer) - Optional - The number of hits to skip (used for offset-based pagination). - **limit** (integer) - Optional - The maximum number of hits to return (used for offset-based pagination). ### Request Example ```bash curl -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \ "http://localhost:8108/collections/companies/documents/search\ ?q=stark&query_by=company_name&filter_by=num_employees:>100\ &sort_by=num_employees:desc" ``` ### Response #### Success Response (200) - **facet_counts** (array) - Counts of facets. - **found** (integer) - The total number of documents found. - **out_of** (integer) - The total number of documents available. - **page** (integer) - The current page number. - **request_params** (object) - Parameters used for the request. - **collection_name** (string) - The name of the collection searched. - **per_page** (integer) - The number of hits per page. - **q** (string) - The search query. - **search_time_ms** (integer) - The time taken for the search in milliseconds. - **hits** (array) - An array of search results. - **highlights** (array) - Information about highlighted matches in the document. - **field** (string) - The field where the match occurred. - **snippet** (string) - The highlighted snippet of text. - **matched_tokens** (array) - The tokens that matched the query. - **indices** (array) - Indices of the snippets when a string[] field is queried. - **document** (object) - The actual document that matched the query. - **text_match** (integer) - A score indicating how well the document matched the text query. #### Response Example ```json { "facet_counts": [], "found": 1, "out_of": 1, "page": 1, "request_params": { "collection_name": "companies", "per_page": 10, "q": "stark" }, "search_time_ms": 1, "hits": [ { "highlights": [ { "field": "company_name", "snippet": "Stark Industries", "matched_tokens": ["Stark"] } ], "document": { "id": "124", "company_name": "Stark Industries", "num_employees": 5215, "country": "USA" }, "text_match": 130916 } ] } ``` ``` -------------------------------- ### Create a Search Preset using cURL Source: https://typesense.org/docs/30.2/api/search.md Use this cURL command to create a new search preset named 'listing_view' for the 'products' collection. It configures wildcard search and sorting by popularity. ```bash curl "http://localhost:8108/presets/listing_view" -X PUT \ -H "Content-Type: application/json" \ -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \ -d '{ \ "value": { \ "collection": "products", \ "q": "*", \ "sort_by": "popularity" \ } \ }' ``` -------------------------------- ### Get NL Search Model Source: https://typesense.org/docs/30.2/api/api-keys.md Retrieves a specific natural language search model by its ID. This operation corresponds to a GET request to the /nl_search_models/:id endpoint. ```APIDOC ## GET /nl_search_models/:id ### Description Get NL search model. ### Method GET ### Endpoint /nl_search_models/:id #### Path Parameters - **id** (string) - Required - The ID of the NL search model to retrieve. ``` -------------------------------- ### Include Reference Fields in GET Document API Source: https://typesense.org/docs/30.2/api/joins.md Use the `include_fields` parameter with a comma-separated list of fields to retrieve specific fields from a referenced collection when getting a single document. ```bash curl -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" -X GET \ "http://localhost:8108/collections/books/documents/1?include_fields=$authors(name)" ``` -------------------------------- ### Initialize Typesense Client (Swift) Source: https://typesense.org/docs/30.2/api/authentication.md Instantiate the Typesense client for Swift applications. Configure the node, configuration, and client object. ```swift import Typesense let node = Node( host: "localhost", // For Typesense Cloud use xxx.a1.typesense.net port: "8108", // For Typesense Cloud use 443 nodeProtocol: "http" // For Typesense Cloud use https ) let config = Configuration(nodes: [node], apiKey: "", connectionTimeoutSeconds: 2) let client = Client(config: config) ``` -------------------------------- ### Import Multiple Documents using Ruby Client Source: https://typesense.org/docs/30.2/api/documents.md This Ruby example shows how to import an array of documents using the 'create' action. For imports, ensure connection_timeout_seconds is set to at least 5 minutes when creating the client. ```ruby documents = [{ 'id' => '124', 'company_name' => 'Stark Industries', 'num_employees' => 5215, 'country' => 'USA' }] # IMPORTANT: Be sure to increase connection_timeout_seconds to at least 5 minutes or more for imports, # when instantiating the client client.collections['companies'].documents.import(documents, action: 'create') ``` -------------------------------- ### Initialize Typesense Client (Python) Source: https://typesense.org/docs/30.2/api/authentication.md Instantiate the Typesense client for Python applications. Configure the nodes, API key, and connection timeout as needed. ```python import typesense client = typesense.Client({ 'nodes': [{ 'host': 'localhost', # For Typesense Cloud use xxx.a1.typesense.net 'port': '8108', # For Typesense Cloud use 443 'protocol': 'http' # For Typesense Cloud use https }], 'api_key': '', 'connection_timeout_seconds': 2 }) ``` -------------------------------- ### Authenticate and Search with cURL (API Key in GET Parameter) Source: https://typesense.org/docs/30.2/api/authentication.md Perform a search operation using cURL by passing the API key as a GET parameter. Note that this method might be less secure than using headers. ```bash export TYPESENSE_API_KEY='' export TYPESENSE_HOST='http://localhost:8108' # For Typesense Cloud use: # export TYPESENSE_HOST='https://xxx.a1.typesense.net' # b) Passing API key via GET parameter curl "http://localhost:8108/collections/companies/documents/search\n?q=stark&query_by=company_name&filter_by=num_employees:>100\n&sort_by=num_employees:desc&x-typesense-api-key=${TYPESENSE_API_KEY}" ``` -------------------------------- ### Union Search with Different Sort Fields (Error Example) Source: https://typesense.org/docs/30.2/api/federated-multi-search.md This example illustrates an error scenario in union search where sorting fields have different types across search requests. Ensure sorting fields are uniform for successful union searches. ```json { "union": true, "searches": [ { "...": "", "sort_by": "user_name:asc" }, { "...": "", "sort_by": "rating:asc" } ] } ``` -------------------------------- ### Analytics Get Source: https://typesense.org/docs/30.2/api/api-keys.md Allows for a single analytics rule to be fetched. ```APIDOC ## GET /analytics/:id ### Description Allows for a single analytics rule to be fetched. ### Method GET ### Endpoint /analytics/:id ``` -------------------------------- ### Analytics Rules Get Source: https://typesense.org/docs/30.2/api/api-keys.md Allows for a single analytics rule to be fetched. ```APIDOC ## GET /analytics/rules/:id ### Description Allows for a single analytics rule to be fetched. ### Method GET ### Endpoint /analytics/rules/:id ``` -------------------------------- ### Import Documents in Swift Source: https://typesense.org/docs/30.2/api/documents.md Import documents using the Swift client. This example demonstrates encoding documents into JSONL format and sending them as a batch. Increase connection timeout for large imports. ```swift let documents = [ Company( id: "124", company_name: "Stark Industries", num_employees: 5125, country: "USA" ) ] var jsonLStrings:[String] = [] for doc in documents { let data = try encoder.encode(doc) let str = String(data: data, encoding: .utf8)! jsonLStrings.append(str) } let jsonLString = jsonLStrings.joined(separator: "\n") let jsonL = Data(jsonLString.utf8) // IMPORTANT: Be sure to increase connectionTimeoutSeconds to at least 5 minutes or more for imports, // when instantiating the client let (data, response) = try await client.collection(name: "companies").documents().importBatch(jsonL) ``` -------------------------------- ### Getting All Stopwords Sets Source: https://typesense.org/docs/30.2/api/stopwords.md This endpoint retrieves a list of all available stopwords sets. ```APIDOC ## GET /stopwords ### Description Fetches all defined stopwords sets. ### Method GET ### Endpoint /stopwords ### Response #### Success Response (200) - (array[object]) - A list of stopwords set objects, each containing 'id', 'locale', and 'stopwords'. ``` -------------------------------- ### Perform Multi-Search using a Preset in Go Source: https://typesense.org/docs/30.2/api/search.md This Go snippet demonstrates how to perform a multi-search operation by referencing the 'listing_view' preset. ```go searchRequests := api.MultiSearchSearchesParameter{ Searches: []api.MultiSearchCollectionParameters{ { Preset: "listing_view" }, }, } commonSearchParams := &api.MultiSearchParams{} client.MultiSearch.Perform(context.Background(), commonSearchParams, searchRequests) ``` -------------------------------- ### Retrieve Health Status (cURL) Source: https://typesense.org/docs/30.2/api/cluster-operations.md Use this to get health information about a Typesense node. ```bash curl "http://localhost:8108/health" ``` -------------------------------- ### Sample Product Catalog Data Source: https://typesense.org/docs/30.2/api/natural-language-search.md This is the sample dataset used for demonstrating natural language search queries. ```json [ { "id": "1", "name": "Men's Red Cotton Shirt", "description": "Comfortable casual shirt", "price": 24.99, "category": "Apparel", "color": "Red", "in_stock": true, "rating": 4.5 }, { "id": "2", "name": "Women's Blue Denim Jeans", "description": "Classic straight-cut denim jeans", "price": 49.99, "category": "Apparel", "color": "Blue", "in_stock": true, "rating": 4.2 }, { "id": "3", "name": "Running Shoes - Green", "description": "Lightweight shoes perfect for running", "price": 89.99, "category": "Footwear", "color": "Green", "in_stock": false, "rating": 4.8 } ] ``` -------------------------------- ### Import Documents via cURL (Basic) Source: https://typesense.org/docs/30.2/api/documents.md Use cURL to import documents by sending a POST request with the documents in JSONL format. The `action` parameter defaults to `create` if not specified. ```bash curl "http://localhost:8108/collections/companies/documents/import?action=create" \ -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \ -H "Content-Type: text/plain" \ -X POST \ -d '{"id": "124","company_name": "Stark Industries","num_employees": 5215,"country": "USA"} {"id": "125","company_name": "Acme Corp","num_employees": 2133,"country": "CA"}' ``` -------------------------------- ### Get Model Details Source: https://typesense.org/docs/30.2/api/natural-language-search.md Retrieves the details of a specific natural language search model by its ID. ```APIDOC ## GET /nl_search_models/{model_id} ### Description Retrieves the details of a specific natural language search model by its ID. ### Method GET ### Endpoint /nl_search_models/{model_id} ### Parameters #### Path Parameters - **model_id** (string) - Required - The ID of the model to retrieve. ### Response #### Success Response (200) - **id** (string) - The ID of the model. - **created_at** (integer) - The timestamp when the model was created. #### Response Example ```json { "id": "gemini-model", "created_at": 1700000000 } ``` ``` -------------------------------- ### Create a Search Preset in JavaScript Source: https://typesense.org/docs/30.2/api/search.md Use this snippet to create a new search preset named 'listing_view' for the 'products' collection. It configures wildcard search and sorting by popularity. ```javascript await client.presets().upsert("listing_view", { value: { collection: "products", q: "*", sort_by: "popularity", }, }); ``` -------------------------------- ### Get Related Documents Count Source: https://typesense.org/docs/30.2/api/joins.md Use `related_docs_count` to include the number of related documents for a join in the response. ```json { "collection": "authors", "q": "*", "filter_by": "$books(id:*)", "include_fields": "$books(*, related_docs_count: foo_related_count)" } ``` -------------------------------- ### Get a Specific Stopwords Set Source: https://typesense.org/docs/30.2/api/stopwords.md This endpoint retrieves the stopwords associated with a specific stopwords set name. ```APIDOC ## GET /stopwords/{stopwords_set_name} ### Description Retrieves the stopwords for a specific stopwords set. ### Method GET ### Endpoint /stopwords/{stopwords_set_name} ### Parameters #### Path Parameters - **stopwords_set_name** (string) - Required - The name of the stopwords set to retrieve. ``` -------------------------------- ### Initialize Typesense Client (Ruby) Source: https://typesense.org/docs/30.2/api/authentication.md Instantiate the Typesense client for Ruby applications. Provide the necessary configuration for nodes, API key, and connection timeout. ```ruby require 'typesense' client = Typesense::Client.new( nodes: [{ host: 'localhost', # For Typesense Cloud use xxx.a1.typesense.net port: 8108, # For Typesense Cloud use 443 protocol: 'http' # For Typesense Cloud use https }], api_key: '', connection_timeout_seconds: 2 ) ``` -------------------------------- ### Create Query Collection using cURL Source: https://typesense.org/docs/30.2/api/analytics-query-suggestions.md Creates a collection named 'product_queries' with 'q' (string) and 'count' (int32) fields using a cURL command. ```bash curl -k "http://localhost:8108/collections" \ -X POST \ -H "Content-Type: application/json" \ -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \ -d '{ "name": "product_queries", "fields": [ {"name": "q", "type": "string" }, {"name": "count", "type": "int32" } ] }' ``` -------------------------------- ### Get All Stopwords Sets Source: https://typesense.org/docs/30.2/api/stopwords.md Retrieve a list of all configured stopwords sets by accessing the main stopwords endpoint. ```shell curl -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \ "http://localhost:8108/stopwords" ``` -------------------------------- ### Example Field Definition with Un-indexed Field Source: https://typesense.org/docs/30.2/api/collections.md Defines a field named 'metadata' as a string type, which is not indexed. ```json {"name": "metadata", "type": "string", "index": false} ``` -------------------------------- ### Perform Multi-Search using a Preset in Java Source: https://typesense.org/docs/30.2/api/search.md This Java snippet demonstrates how to perform a multi-search operation by referencing the 'listing_view' preset. ```java HashMap search1 = new HashMap<>(); search1.put("preset","listing_view"); List> searches = new ArrayList<>(); searches.add(search1); HashMap>> searchRequests = new HashMap<>(); searchRequests.put("searches",searches); HashMap commonSearchParams = new HashMap<>(); client.multiSearch.perform(searchRequests, commonSearchParams); ``` -------------------------------- ### Example Field Definition with Optional Field Source: https://typesense.org/docs/30.2/api/collections.md Defines a field named 'description' as a string type, which is optional. ```json {"name": "description", "type": "string", "optional": true} ``` -------------------------------- ### Example Field Definition Source: https://typesense.org/docs/30.2/api/collections.md Defines a field named 'title' as a string type, enabling indexing and faceting. ```json {"name": "title", "type": "string", "facet": false, "index": true} ``` -------------------------------- ### Initialize Typesense Client (Java) Source: https://typesense.org/docs/30.2/api/authentication.md Instantiate the Typesense client for Java applications. Define the nodes, configuration, and client object. ```java import org.typesense.api.*; import org.typesense.models.*; import org.typesense.resources.*; ArrayList nodes = new ArrayList<>(); nodes.add( new Node( "http", // For Typesense Cloud use https "localhost", // For Typesense Cloud use xxx.a1.typesense.net "8108" // For Typesense Cloud use 443 ) ); Configuration configuration = new Configuration(nodes, Duration.ofSeconds(2),""); Client client = new Client(configuration); ``` -------------------------------- ### Clone Collection with Documents Source: https://typesense.org/docs/30.2/api/collections.md Use this to create a new collection that includes the schema, overrides, synonyms, and all documents from a source collection. ```shell curl -X POST 'http://localhost:8108/collections?src_name=source_collection©_documents=true' \ -H 'Content-Type: application/json' \ -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \ -d '{"name": "new_collection_with_docs"}' ``` -------------------------------- ### List All Collections Source: https://typesense.org/docs/30.2/api/collections.md Use this snippet to get a summary of all collections in your Typesense instance. Pagination and field exclusion are supported. ```js client.collections().retrieve() ``` ```php $client->collections->retrieve(); ``` ```python client.collections.retrieve() ``` ```ruby client.collections.retrieve ``` ```dart await client.collections.retrieve(); ``` ```java CollectionResponse[] collectionResponses = client.collections().retrieve(); ``` ```go client.Collections().Retrieve(context.Background()) ``` ```swift let (collections, response) = try await client.collections().retrieveAll() // collections is of type [CollectionResponse] ``` ```bash curl -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \ "http://localhost:8108/collections" ``` -------------------------------- ### List Conversation Models Source: https://typesense.org/docs/30.2/api/api-keys.md Lists all available conversation models. This operation corresponds to a GET request to the /conversations/models endpoint. ```APIDOC ## GET /conversations/models ### Description List conversation models. ### Method GET ### Endpoint /conversations/models ``` -------------------------------- ### Create a Multi-Search Preset in JavaScript Source: https://typesense.org/docs/30.2/api/search.md This JavaScript snippet shows how to create a preset that includes multiple search configurations for federated/multi-search. ```javascript await client.presets().upsert("listing_view", { value: { searches: [ { collection: "products", q: "*", sort_by: "popularity", }, { collection: "blog_posts", q: "*", sort_by: "published_at:desc", } ], }, }) ``` -------------------------------- ### Create/Update Synonym Set (Simple) Source: https://typesense.org/docs/30.2/api/synonyms.md This example demonstrates how to create or update a synonym set with a list of synonyms. The `Upsert` method is used to either create a new set or replace an existing one. ```APIDOC ## PUT /synonym_sets/:synonymSetName ### Description Creates or updates a synonym set with a given name. If a synonym set with the same name already exists, it will be overwritten. ### Method PUT ### Endpoint `${TYPESENSE_HOST}/synonym_sets/:synonymSetName` ### Parameters #### Path Parameters - **synonymSetName** (string) - Required - The name of the synonym set to create or update. #### Request Body - **items** (array) - Required - A list of synonym items to be included in the set. - **id** (string) - Required - A unique identifier for the synonym group within the set. - **synonyms** (array of strings) - Required - A list of words that are considered synonyms. ### Request Example ```json { "items": [ { "id": "coat-synonyms", "synonyms": ["blazer", "coat", "jacket"] } ] } ``` ### Response #### Success Response (200) - **name** (string) - The name of the synonym set. - **items** (array) - The list of synonym items in the set. - **id** (string) - The identifier for the synonym group. - **synonyms** (array of strings) - The list of synonyms. #### Response Example ```json { "name": "clothing-synonyms", "items": [ { "id": "coat-synonyms", "synonyms": ["blazer", "coat", "jacket"] } ] } ``` ``` -------------------------------- ### Get Debug Information Source: https://typesense.org/docs/30.2/api/cluster-operations.md Retrieves debugging information about a Typesense node, including its version and role (leader or follower). ```APIDOC ## GET /debug ### Description Get debugging information about a Typesense node. ### Method GET ### Endpoint /debug ### Request Example ```bash curl "http://localhost:8108/debug" \ -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" ``` ### Response #### Success Response (200) - **state** (integer) - Indicates the role of the node: 1 for LEADER, 4 for FOLLOWER. - **version** (string) - The version of Typesense running on the node. #### Response Example ```json { "state": 1, "version": "28.0" } ``` ``` -------------------------------- ### Get a Specific Stopwords Set Source: https://typesense.org/docs/30.2/api/stopwords.md Fetch the stopwords associated with a particular stopwords set by providing its ID in the URL. ```shell curl -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \ "http://localhost:8108/stopwords/countries" ``` -------------------------------- ### Perform Multi-Search for Query Suggestions (Go) Source: https://typesense.org/docs/30.2/api/analytics-query-suggestions.md Use this Go snippet to execute a multi-search operation, fetching query suggestions and relevant results in parallel. Requires the Typesense Go client and context. ```go searchRequests := api.MultiSearchSearchesParameter{ Searches: []api.MultiSearchCollectionParameters{ { Collection: pointer.Any("product_queries"), Q: pointer.Any("shoe"), QueryBy: pointer.Any("q"), }, { Collection: pointer.Any("products"), Q: pointer.Any("shoe"), QueryBy: pointer.Any("product_name"), }, }, } client.MultiSearch.Perform(context.Background(), &api.MultiSearchParams{}, searchRequests) ``` -------------------------------- ### Sample Response for Alias Creation/Update Source: https://typesense.org/docs/30.2/api/collection-alias.md This is a sample JSON response when an alias is successfully created or updated. ```json { "name": "companies", "collection_name": "companies_june11", } ``` -------------------------------- ### Define Synonym Dictionary Source: https://typesense.org/docs/30.2/api/curation.md Example of a synonym dictionary where 'credit card', 'payment card', and 'cc' are defined as synonyms. ```json { "id": "card-synonyms", "synonyms": ["credit card", "payment card", "cc"] } ``` -------------------------------- ### Join Result Without Forced Array Source: https://typesense.org/docs/30.2/api/joins.md Example response showing that the 'books' field can be a single object or an array. ```json [ { "document": { "id": "1", "first_name": "JK", "last_name": "Rowling", "books": { "author_id": "1", "id": "2", "title": "Harry Potter" } } }, { "document": { "id": "0", "first_name": "Enid", "last_name": "Blyton", "books": [ { "author_id": "0", "id": "0", "title": "Famous Five" }, { "author_id": "0", "id": "1", "title": "Secret Seven" } ] } } ] ``` -------------------------------- ### Initialize Typesense Search Client (JavaScript) Source: https://typesense.org/docs/30.2/api/authentication.md Instantiate the Typesense Search client library for search-only operations, which can help reduce bundle size. This is recommended for browser environments. ```javascript import { SearchClient as TypesenseSearchClient } from "typesense"; let client = new TypesenseSearchClient({ 'nodes': [{ 'host': 'localhost', // For Typesense Cloud use xxx.a1.typesense.net 'port': '8108', // For Typesense Cloud use 443 'protocol': 'http' // For Typesense Cloud use https }], 'apiKey': '', 'connectionTimeoutSeconds': 2 }) ``` -------------------------------- ### Create Admin API Key in Go Source: https://typesense.org/docs/30.2/api/api-keys.md Use this snippet to create an API key with administrative privileges, granting universal access. Store the generated key securely as it's only returned during creation. ```go key, err := client.Keys().Create(context.Background(), &api.ApiKeySchema{ Description: "Admin key.", Actions: []string{"*"}, Collections: []string{"*"}, }) ``` -------------------------------- ### List all aliases Source: https://typesense.org/docs/30.2/api/collection-alias.md Retrieve a list of all defined aliases and the collections they map to. This helps in understanding the current alias setup. ```js client.aliases().retrieve() ``` ```php $client->aliases->retrieve() ``` ```python client.aliases.retrieve() ``` ```ruby client.aliases.retrieve ``` ```dart await client.aliases.retrieve(); ``` ```java CollectionAliasesResponse collectionAliasesResponse = client.aliases().retrieve(); ``` ```go client.Aliases().Retrieve(context.Background()) ``` ```swift let (collectionAliases, response) = try await client.aliases().retrieve() ``` -------------------------------- ### Retrieve Health Status (Swift) Source: https://typesense.org/docs/30.2/api/cluster-operations.md Use this to get health information about a Typesense node. Requires an initialized Typesense client. ```swift let (healthStatus, response) = try await client.operations().getHealth() ``` -------------------------------- ### Create Snapshot (Go) Source: https://typesense.org/docs/30.2/api/cluster-operations.md Use this snippet to create a point-in-time snapshot of a Typesense node's data. The snapshot will be saved to the specified directory. ```go client.Operations().Snapshot(context.Background(), "/tmp/typesense-data-snapshot") ``` -------------------------------- ### Retrieve Health Status (Dart) Source: https://typesense.org/docs/30.2/api/cluster-operations.md Use this to get health information about a Typesense node. Requires an initialized Typesense client. ```dart await client.health.retrieve(); ``` -------------------------------- ### Perform Multi-Search for Query Suggestions (Ruby) Source: https://typesense.org/docs/30.2/api/analytics-query-suggestions.md This Ruby code demonstrates how to perform a multi-search to fetch query suggestions and actual search results simultaneously. Ensure the Typesense client is installed. ```ruby search_requests = { 'searches' => [ { 'collection' => 'product_queries', 'q' => 'shoe', 'query_by' => 'q' }, { 'collection' => 'products', 'q' => 'shoe', 'query_by' => 'q' } ] } client.multi_search.perform(search_requests, {}) ``` -------------------------------- ### List all synonym sets Source: https://typesense.org/docs/30.2/api/synonyms.md List all available synonym sets. ```APIDOC ## List all synonym sets ### Description List all available synonym sets. ### Method GET ### Endpoint `/synonym_sets` ### Request Example ```bash curl -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \ "http://localhost:8108/synonym_sets" ``` ### Response #### Success Response (200) - **name** (string) - The name of the synonym set. - **items** (array) - A list of synonym items. - **id** (string) - The ID of the synonym item. - **synonyms** (array) - A list of synonyms for the item. #### Response Example ```json [ { "name": "clothing-synonyms", "items": [ { "id": "coat-synonyms", "synonyms": ["blazer", "coat", "jacket"] } ] } ] ``` ``` -------------------------------- ### Example Field Definition to Prevent Storing on Disk Source: https://typesense.org/docs/30.2/api/collections.md Defines a field named 'internal_id' as a string type, which will not be stored on disk. ```json {"name": "internal_id", "type": "string", "store": false} ``` -------------------------------- ### Example Field Definition with Basic Stemming Source: https://typesense.org/docs/30.2/api/collections.md Defines a field named 'content' as a string type, enabling basic stemming. ```json {"name": "content", "type": "string", "stem": true} ``` -------------------------------- ### Perform Multi-Search using a Preset in Python Source: https://typesense.org/docs/30.2/api/search.md This Python snippet demonstrates how to perform a multi-search operation by referencing the 'listing_view' preset. ```python search_requests = { 'searches': [ { 'preset': 'listing_view' } ] } client.multi_search.perform(search_requests, {}) ``` -------------------------------- ### Create Snapshot (PHP) Source: https://typesense.org/docs/30.2/api/cluster-operations.md Use this snippet to create a point-in-time snapshot of a Typesense node's data. The snapshot will be saved to the specified directory. ```php $client->operations->perform("snapshot", ["snapshot_path" => "/tmp/typesense-data-snapshot"]); ``` -------------------------------- ### Response with Related Documents Count Source: https://typesense.org/docs/30.2/api/joins.md Example response showing the added field `foo_related_count` indicating the number of related books. ```json [ { "document": { "id": "1", "first_name": "JK", "last_name": "Rowling", "books": { "author_id": "1", "id": "2", "title": "Harry Potter" }, "foo_related_count": 1 } }, { "document": { "id": "0", "first_name": "Enid", "last_name": "Blyton", "books": [ { "author_id": "0", "id": "0", "title": "Famous Five" }, { "author_id": "0", "id": "1", "title": "Secret Seven" } ], "foo_related_count": 2 } } ] ``` -------------------------------- ### Join Result with Forced Array Source: https://typesense.org/docs/30.2/api/joins.md Example response where the 'books' field is consistently an array of objects due to the `nest_array` strategy. ```json [ { "document": { "id": "1", "first_name": "JK", "last_name": "Rowling", "books": [ { "author_id": "1", "id": "2", "title": "Harry Potter" } ] } }, { "document": { "id": "0", "first_name": "Enid", "last_name": "Blyton", "books": [ { "author_id": "0", "id": "0", "title": "Famous Five" }, { "author_id": "0", "id": "1", "title": "Secret Seven" } ] } } ] ``` -------------------------------- ### Create Collection using cURL Source: https://typesense.org/docs/30.2/api/collections.md This example demonstrates how to create a new collection using a cURL command. It includes the endpoint, HTTP method, headers, and the JSON payload for the collection schema. ```APIDOC ## POST /collections ### Description Creates a new collection with the specified schema. All fields mentioned in the schema will be indexed in memory. ### Method POST ### Endpoint `http://localhost:8108/collections` ### Parameters #### Request Body - **name** (string) - Required - The name of the collection. - **fields** (array) - Required - An array of field definitions for the collection. - **name** (string) - Required - The name of the field. - **type** (string) - Required - The data type of the field. See [Field Types](#field-types) for available options. - **facet** (boolean) - Optional - Whether the field should be enabled for faceting. - **default_sorting_field** (string) - Optional - The field to use for sorting documents by default. ### Request Example ```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" } ``` ### Response #### Success Response (200) - **name** (string) - The name of the collection. - **num_documents** (integer) - The number of documents in the collection. - **fields** (array) - An array of field definitions for the collection. - **default_sorting_field** (string) - The field used for sorting documents by default. #### Response Example ```json { "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" } ``` ```