### Direct API Call Examples in Ruby
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/api_call.md
Demonstrates how to perform direct GET, POST, and DELETE requests to the Typesense API using the client's internal api_call object. Ensure the Typesense client is initialized before use.
```ruby
require 'typesense'
client = Typesense::Client.new(
api_key: 'xyz',
nodes: [{ host: 'localhost', port: 8108, protocol: 'http' }]
)
api_call = client.instance_variable_get(:@api_call)
# Direct GET
collections = api_call.get('/collections')
# Direct POST with body
result = api_call.post(
'/collections',
{ 'name' => 'products', 'fields' => [...] }
)
# DELETE with query params
result = api_call.delete('/collections/products', { 'truncate' => true })
```
--------------------------------
### Create Typesense Client for a Cluster
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/configuration.md
Configure a Typesense client to connect to a multi-node cluster. This example assumes a 3-node setup and uses HTTP protocol.
```ruby
def create_cluster_client
# Assuming 3-node cluster
Typesense::Client.new(
api_key: ENV['TYPESENSE_API_KEY'],
nodes: [
{
host: 'node1.cluster.local',
port: 8108,
protocol: 'http'
},
{
host: 'node2.cluster.local',
port: 8108,
protocol: 'http'
},
{
host: 'node3.cluster.local',
port: 8108,
protocol: 'http'
}
],
connection_timeout_seconds: 5,
healthcheck_interval_seconds: 15,
num_retries: 3,
retry_interval_seconds: 0.1
)
end
```
--------------------------------
### Stemming Dictionary Example
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/types.md
An example of a stemming dictionary, showing a root word 'run' and its variants.
```ruby
{
'root' => 'run',
'words' => ['running', 'runs', 'ran', 'runningly']
}
```
--------------------------------
### Example Typesense Document
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/types.md
An example illustrating a typical document structure with various data types for fields.
```ruby
{
'id' => '1',
'title' => 'The Great Gatsby',
'author' => 'F. Scott Fitzgerald',
'year' => 1925,
'rating' => 4.5,
'genres' => ['fiction', 'classic', 'romance'],
'in_stock' => true
}
```
--------------------------------
### Complete Collection Workflow Example
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/collections.md
Demonstrates a typical sequence of operations for managing a collection, from creation to deletion, including retrieval and updates.
```ruby
# Create a collection
client.collections.create({
'name' => 'books',
'fields' => [
{ 'name' => 'id', 'type' => 'string' },
{ 'name' => 'title', 'type' => 'string', 'infix' => true },
{ 'name' => 'author', 'type' => 'string' },
{ 'name' => 'year', 'type' => 'int32' },
{ 'name' => 'rating', 'type' => 'float' }
],
'default_sorting_field' => 'rating'
})
# List all collections
all_collections = client.collections.retrieve
# Get a specific collection
books = client.collections['books']
# View collection details
collection_info = books.retrieve
# Update default sorting
books.update({
'default_sorting_field' => 'year'
})
# Delete the collection
books.delete
```
--------------------------------
### Install Typesense Ruby Gem
Source: https://github.com/typesense/typesense-ruby/blob/master/README.md
Add the typesense gem to your application's Gemfile for installation.
```ruby
gem 'typesense'
```
--------------------------------
### Initialize Typesense Client with Basic Configuration
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/client.md
Use this snippet to initialize the Typesense client with a single node. Ensure you have the 'typesense' gem installed.
```ruby
require 'typesense'
client = Typesense::Client.new(
api_key: 'xyz',
nodes: [
{
host: 'localhost',
port: 8108,
protocol: 'http'
}
]
)
```
--------------------------------
### List, Retrieve, and Delete All Keys
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/keys.md
Provides examples for listing all existing API keys, retrieving details of a specific key by its ID, and subsequently deleting it.
```ruby
# List all keys
all_keys = client.keys.retrieve
# Find a specific key
target_key_id = all_keys.find { |k| k['description'] == 'Old search key' }['id']
# Get key details
key_details = client.keys[target_key_id].retrieve
# Delete the key
client.keys[target_key_id].delete
```
--------------------------------
### Minimal Typesense Client Configuration
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/README.md
Use this minimal configuration for basic setups, providing only the API key and a single node.
```ruby
client = Typesense::Client.new(
api_key: 'xyz',
nodes: [
{ host: 'localhost', port: 8108, protocol: 'http' }
]
)
```
--------------------------------
### Get System Resource Stats
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/server_operations.md
Get disk and memory statistics from the Typesense server. Helps in monitoring resource utilization and preventing issues like full disks.
```ruby
# Get disk and memory stats
stats = client.stats.retrieve
disk_used_gb = stats['disk_used_bytes'].to_f / (1024 ** 3)
disk_total_gb = stats['disk_total_bytes'].to_f / (1024 ** 3)
disk_percent = (disk_used_gb / disk_total_gb) * 100
puts "Disk usage: #{disk_used_gb.round(2)}GB / #{disk_total_gb.round(2)}GB (#{disk_percent.round(1)}%)"
# Check if disk is getting full
if disk_percent > 80
puts "WARNING: Disk usage is above 80%"
# Implement cleanup or alerting
end
```
--------------------------------
### Configure Product Type Synonyms
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/overrides_and_synonyms.md
Set up synonyms to map common product type terms to their canonical names, improving search accuracy. For example, mapping 'mobile' to 'phone'.
```ruby
# Users searching 'mobile' find results for 'phone'
client.collections['products'].synonyms.upsert('mobile_synonyms', {
'root' => 'mobile',
'synonyms' => ['phone', 'cellular', 'handset']
})
# Users searching 'notebook' find results for 'laptop'
client.collections['products'].synonyms.upsert('laptop_synonyms', {
'root' => 'notebook',
'synonyms' => ['laptop', 'computer', 'device']
})
```
--------------------------------
### Get Detailed Debug Information
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/server_operations.md
Get detailed debug information for troubleshooting, including version and commit hash. Logs this information to a file for support purposes.
```ruby
# Get detailed debug information for troubleshooting
debug = client.debug.retrieve
puts "Typesense Version: #{debug['version']}"
puts "Commit Hash: #{debug['commit_hash']}"
# Log debug info for support
File.write('debug_info.json', JSON.pretty_generate(debug))
```
--------------------------------
### Initialize Typesense Client with Multiple Nodes and Retries
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/client.md
Configure the client to connect to multiple Typesense nodes for high availability. This example also sets the number of retries for requests.
```ruby
client = Typesense::Client.new(
api_key: 'xyz',
nodes: [
{
host: 'typesense-1.example.com',
port: 443,
protocol: 'https'
},
{
host: 'typesense-2.example.com',
port: 443,
protocol: 'https'
}
],
num_retries: 2
)
```
--------------------------------
### Batch Search with Highlighting
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/multi_search.md
Perform a multi-search with highlighting enabled to show search terms within the results. This example searches for 'python' in 'books' and 'courses', applying custom highlight tags.
```ruby
searches = [
{
'collection' => 'books',
'q' => 'python',
'query_by' => 'title,author,description',
'highlight_fields' => 'title,description',
'highlight_pre_tag' => '',
'highlight_post_tag' => '',
'limit' => 10
},
{
'collection' => 'courses',
'q' => 'python',
'query_by' => 'title,content',
'highlight_fields' => 'title,content',
'limit' => 10
}
]
results = client.multi_search.perform(searches)
results.each_with_index do |result, idx|
collection = searches[idx]['collection']
puts "\n=== #{collection.upcase} ==="
result['hits'].each do |hit|
doc = hit['document']
highlight = hit['highlight'] || {}
# Use highlighted version if available
title = highlight['title'] ? highlight['title'][0] : doc['title']
puts title
end
end
```
--------------------------------
### Generate a Scoped Search Key for Client-Side Usage
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/keys.md
This example shows how to create a master search key with limited permissions and then generate a scoped search key from it. The scoped key can be securely provided to client applications for specific search operations with predefined filters and expiration.
```ruby
# Create a master search key with minimal permissions
master_search_key = client.keys.create({
'description' => 'Master search key for scoping',
'actions' => ['documents:search'],
'collections' => ['products', 'categories']
})
# Generate a scoped key for specific user
scoped_key = client.keys.generate_scoped_search_key(
master_search_key['value'],
{
'collections' => ['products'],
'filter_by' => 'user_id:= 123 && status:= published',
'expires_at' => Time.now.to_i + 3600
}
)
# Return scoped_key to client application for frontend search
# The client can only search products collection with the specified filters
{
'search_key' => scoped_key,
'expires_at' => Time.now.to_i + 3600
}
```
--------------------------------
### Typesense::Presets#[]
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/advanced_features.md
Get a reference to a specific preset. Presets allow you to save search parameter configurations for reuse.
```APIDOC
## Typesense::Presets#[] (index operator)
### Description
Get a reference to a specific preset. Presets allow you to save search parameter configurations for reuse.
### Method
```ruby
Presets[preset_name]
```
### Parameters
#### Path Parameters
- **preset_name** (String) - Required - Name of the preset
### Response
`Typesense::Preset` instance
```
--------------------------------
### Multi-Search with Different Parameters
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/multi_search.md
Execute a multi-search where each query to a collection uses distinct parameters like filtering, sorting, and limits. This example searches for 'iphone' in 'products' with price constraints and in 'reviews' with rating filters.
```ruby
results = client.multi_search.perform([
{
'collection' => 'products',
'q' => 'iphone',
'query_by' => 'title,description',
'filter_by' => 'price:>500 && price:<2000',
'sort_by' => 'price:asc',
'limit' => 10
},
{
'collection' => 'reviews',
'q' => 'iphone',
'query_by' => 'title,content',
'filter_by' => 'rating:>4',
'sort_by' => 'rating:desc,helpful_count:desc',
'limit' => 5
}
])
# Access results with proper collection context
products = results[0]
reviews = results[1]
puts "Products found: #{products['found']}"
puts "Reviews found: #{reviews['found']}"
```
--------------------------------
### Retrieve Natural Language Search Model Details
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/advanced_features.md
Get the configuration details for a specific natural language search model.
```ruby
NlSearchModel.retrieve
```
--------------------------------
### Retrieve System Stats
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/server_operations.md
Get system resource statistics like disk and memory usage from the Typesense server.
```APIDOC
## GET /stats
### Description
Retrieve system resource statistics, including disk and memory usage, from the Typesense server.
### Method
GET
### Endpoint
/stats
### Parameters
None
### Request Example
```ruby
stats = client.stats.retrieve
```
### Response
#### Success Response (200)
- **disk_used_bytes** (integer) - The amount of disk space used in bytes.
- **disk_total_bytes** (integer) - The total disk space available in bytes.
- **memory_used_bytes** (integer) - The amount of memory used in bytes.
- **memory_total_bytes** (integer) - The total memory available in bytes.
#### Response Example
```json
{
"disk_used_bytes": 21474836480,
"disk_total_bytes": 107374182400,
"memory_used_bytes": 104857600,
"memory_total_bytes": 1073741824
}
```
```
--------------------------------
### Retrieve Debug Information
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/server_operations.md
Get debug information including server version, configuration, and internal state. Useful for troubleshooting.
```ruby
debug_info = client.debug.retrieve
puts "Server version: #{debug_info['version']}"
puts "Configuration: #{debug_info.inspect}"
```
--------------------------------
### Get Product Recommendations with Multi-Search
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/multi_search.md
This snippet demonstrates how to fetch similar products and products from the same category in parallel using Typesense's multi-search functionality. It first retrieves a product and then performs two concurrent searches.
```ruby
def get_product_recommendations(product_id)
# Get the product first
product = client.collections['products'].documents[product_id].retrieve
# Search for similar products in parallel using multi-search
results = client.multi_search.perform([
{
'collection' => 'products',
'q' => product['title'],
'query_by' => 'title,category',
'filter_by' => "id:!= #{product_id}",
'limit' => 5
},
{
'collection' => 'products',
'q' => product['category'],
'query_by' => 'category',
'limit' => 5
}
])
{
'similar_products' => results[0]['hits'].map { |h| h['document'] },
'category_products' => results[1]['hits'].map { |h| h['document'] }
}
end
```
--------------------------------
### Retrieve Synonym Set Details
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/advanced_features.md
Call this method to get the configuration details of a specific synonym set. The synonym set ID must be specified.
```ruby
SynonymSet.retrieve
```
--------------------------------
### Retrieve Server Metrics
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/server_operations.md
Get server metrics in Prometheus format for monitoring and observability. The output contains lines detailing request counts and latency.
```ruby
metrics = client.metrics.retrieve
# Output contains lines like:
# typesense_requests_total{handler="search"} 1234
# typesense_latency_ms{handler="search"} 45.2
puts metrics
```
--------------------------------
### Initialize Client, Create Collection, Add Documents, and Search
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/README.md
This snippet demonstrates the basic workflow: initializing the Typesense client, creating a collection with specified fields, importing documents, and performing a simple search. Ensure the Typesense server is running and accessible.
```ruby
require 'typesense'
# Initialize client
client = Typesense::Client.new(
api_key: 'xyz',
nodes: [
{ host: 'localhost', port: 8108, protocol: 'http' }
]
)
# Create a collection
client.collections.create({
'name' => 'books',
'fields' => [
{ 'name' => 'id', 'type' => 'string' },
{ 'name' => 'title', 'type' => 'string', 'infix' => true },
{ 'name' => 'author', 'type' => 'string' },
{ 'name' => 'year', 'type' => 'int32' },
{ 'name' => 'rating', 'type' => 'float' }
],
'default_sorting_field' => 'rating'
})
# Add documents
client.collections['books'].documents.import([
{ 'id' => '1', 'title' => 'The Great Gatsby', 'author' => 'F. Scott Fitzgerald', 'year' => 1925, 'rating' => 4.4 },
{ 'id' => '2', 'title' => '1984', 'author' => 'George Orwell', 'year' => 1949, 'rating' => 4.2 }
])
# Search
results = client.collections['books'].documents.search({
'q' => 'gatsby',
'query_by' => 'title,author'
})
puts "Found #{results['found']} books"
results['hits'].each do |hit|
puts hit['document']['title']
end
```
--------------------------------
### Handle Configuration Errors
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/configuration.md
Demonstrates how to catch and handle missing configuration errors during client initialization. Ensure that all required parameters like api_key and nodes are provided.
```ruby
begin
client = Typesense::Client.new(
api_key: nil, # This will raise an error
nodes: [
{ host: 'localhost', port: 8108, protocol: 'http' }
]
)
rescue Typesense::Error::MissingConfiguration => e
puts "Configuration error: #{e.message}"
# Output: Configuration error: Missing required configuration. Ensure that api_key is set.
end
```
--------------------------------
### Create API Keys for Different Use Cases
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/keys.md
Demonstrates creating API keys with varying permissions for administrative, search-only, write-only, and time-limited access. Each key can be configured with specific actions and collections.
```ruby
# Admin key (full permissions)
admin_key = client.keys.create({
'description' => 'Admin key',
'actions' => ['*'],
'collections' => ['*']
})
# Search-only key
search_key = client.keys.create({
'description' => 'Search key for products',
'actions' => ['documents:search'],
'collections' => ['products']
})
# Write-only key (for data imports)
import_key = client.keys.create({
'description' => 'Import key',
'actions' => ['documents:create', 'documents:upsert', 'documents:update'],
'collections' => ['products']
})
# Key with expiration
temporary_key = client.keys.create({
'description' => 'Temporary access',
'actions' => ['documents:search'],
'collections' => ['public_data'],
'expires_at' => Time.now.to_i + (7 * 24 * 60 * 60) # 7 days
})
```
--------------------------------
### Initialize Typesense Client
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/client.md
Instantiate a new Typesense client. Pass configuration options in the `options` hash, such as API key and node details.
```ruby
Typesense::Client.new(options = {})
```
--------------------------------
### GET Request
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/api_call.md
Performs a GET request to a specified Typesense API endpoint. It accepts an endpoint path and optional query parameters. The response is parsed JSON or a string.
```APIDOC
## GET /collections
### Description
Performs a GET request to the Typesense server to retrieve data.
### Method
GET
### Endpoint
/collections
### Parameters
#### Query Parameters
- **query_parameters** (Hash) - Optional - Query string parameters
#### Path Parameters
- **endpoint** (String) - Required - API endpoint path (e.g., '/collections')
### Request Example
```ruby
result = api_call.get('/collections')
# Returns: { "collections" => [...] } or similar
```
### Response
#### Success Response
- **Parsed JSON response** (Hash or String) - The data returned from the Typesense server.
```
--------------------------------
### Get a Specific Analytics Rule by Name
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/analytics.md
Get a reference to a specific analytics rule using its name. This allows for direct access to a rule's configuration or details.
```ruby
rule = client.analytics.rules['search_queries']
```
--------------------------------
### Create Typesense Client for Development vs. Production
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/configuration.md
Dynamically configure the Typesense client based on the environment variable RACK_ENV. Production uses API key and nodes from environment variables, while development uses hardcoded local settings.
```ruby
def create_typesense_client
if ENV['RACK_ENV'] == 'production'
Typesense::Client.new(
api_key: ENV['TYPESENSE_API_KEY'],
nodes: JSON.parse(ENV['TYPESENSE_NODES']),
connection_timeout_seconds: 10,
num_retries: 3,
retry_interval_seconds: 0.2,
log_level: Logger::WARN,
keep_alive_connections: true,
keep_alive_idle_timeout_seconds: 30
)
else
Typesense::Client.new(
api_key: 'xyz9944201201201',
nodes: [
{
host: 'localhost',
port: 8108,
protocol: 'http'
}
],
connection_timeout_seconds: 30,
num_retries: 1,
log_level: Logger::DEBUG
)
end
end
```
--------------------------------
### Get Synonym Reference by ID
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/overrides_and_synonyms.md
Use the index operator with a synonym ID to get a reference to a specific synonym object within a collection. This reference can then be used to perform operations like retrieving or deleting the synonym.
```ruby
synonym = client.collections['products'].synonyms['phone_synonyms']
```
--------------------------------
### Initialize Configuration
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/configuration.md
Creates a configuration object for the Typesense client. This is typically done internally when initializing the Typesense::Client.
```ruby
Typesense::Configuration.new(options = {})
```
--------------------------------
### Get Metrics
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/api_call.md
Retrieves metrics for the Typesense instance.
```APIDOC
## GET /metrics.json
### Description
Retrieves metrics for the Typesense instance.
### Method
GET
### Endpoint
/metrics.json
```
--------------------------------
### Typesense::Client Constructor
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/client.md
Initializes a new Typesense client instance with specified configuration options. This is the main entry point for all Typesense operations.
```APIDOC
## Typesense::Client Constructor
### Description
Initializes a new client instance. This is the main entry point for interacting with a Typesense server.
### Method
`Typesense::Client.new(options = {})`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Configuration Options (passed in `options` hash)
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
| `api_key` | String | Yes | — | API key for authentication |
| `nodes` | Array | Yes | [] | Array of node configurations with `:protocol`, `:host`, `:port` |
| `nearest_node` | Hash | No | nil | Optional nearest node configuration for geographic routing |
| `connection_timeout_seconds` | Integer | No | 10 | HTTP connection timeout in seconds |
| `healthcheck_interval_seconds` | Integer | No | 15 | Interval in seconds between node health checks |
| `num_retries` | Integer | No | nodes.length + 1 | Number of retries for failed requests |
| `retry_interval_seconds` | Float | No | 0.1 | Delay in seconds between retries |
| `logger` | Logger | No | Logger.new($stdout) | Ruby Logger instance for debug output |
| `log_level` | Integer | No | Logger::WARN | Log level (Logger::DEBUG, Logger::INFO, etc.) |
| `keep_alive_connections` | Boolean | No | false | Enable persistent HTTP connections |
| `keep_alive_idle_timeout_seconds` | Integer | No | 30 | Idle timeout for keep-alive connections |
| `keep_alive_pool_size` | Integer | No | 1 | Pool size for keep-alive connections per origin |
### Returns
`Typesense::Client` instance
### Throws
`Typesense::Error::MissingConfiguration` if required configuration is missing
```
--------------------------------
### Get Stats
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/api_call.md
Retrieves statistics for the Typesense instance.
```APIDOC
## GET /stats.json
### Description
Retrieves statistics for the Typesense instance.
### Method
GET
### Endpoint
/stats.json
```
--------------------------------
### Production Configuration with HTTPS and Multiple Nodes
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/configuration.md
Sets up the client for production with HTTPS, multiple nodes for high availability, and specific connection settings. API key is loaded from an environment variable.
```ruby
client = Typesense::Client.new(
api_key: ENV['TYPESENSE_API_KEY'],
nodes: [
{
host: 'typesense-1.example.com',
port: 443,
protocol: 'https'
},
{
host: 'typesense-2.example.com',
port: 443,
protocol: 'https'
},
{
host: 'typesense-3.example.com',
port: 443,
protocol: 'https'
}
],
connection_timeout_seconds: 5,
healthcheck_interval_seconds: 10,
num_retries: 3,
retry_interval_seconds: 0.2,
log_level: Logger::INFO
)
```
--------------------------------
### Get Collection
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/api_call.md
Retrieves details of a specific collection.
```APIDOC
## GET /collections/{name}
### Description
Retrieves details of a specific collection.
### Method
GET
### Endpoint
/collections/{name}
```
--------------------------------
### create
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/keys.md
Creates a new API key with specified permissions and restrictions. The key configuration includes details like description, allowed actions, associated collections, scopes, and expiration time.
```APIDOC
## create
### Description
Create a new API key with specified permissions and restrictions.
### Method
POST (Implied by SDK method)
### Endpoint
/keys
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **parameters** (Hash) - Required - Key configuration with description, actions, collections, scopes, expires_at, etc.
### Request Example
```ruby
key = client.keys.create({
'description' => 'Search-only key for products',
'actions' => ['documents:search'],
'collections' => ['products'],
'expires_at' => Time.now.to_i + (30 * 24 * 60 * 60) # 30 days from now
})
puts key['value'] # The actual API key string
```
### Response
#### Success Response (200)
- **value** (String) - The generated API key.
- **id** (String) - The unique identifier for the key.
- **description** (String) - Description of the key.
- **actions** (Array) - List of allowed actions.
- **collections** (Array) - List of associated collections.
- **expires_at** (Integer) - Unix timestamp for key expiration.
#### Response Example
```json
{
"value": "some_generated_api_key",
"id": "some_key_id",
"description": "Search-only key for products",
"actions": ["documents:search"],
"collections": ["products"],
"expires_at": 1678886400
}
```
**Throws:** `Typesense::Error::ObjectUnprocessable` if key parameters are invalid
```
--------------------------------
### Typesense::CurationSets.[]
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/advanced_features.md
Gets a reference to a specific curation set by its name.
```APIDOC
## [] (index operator)
### Description
Get a reference to a specific curation set.
### Method
`GET` (inferred from SDK method)
### Endpoint
`/curation_sets/{curation_set_name}` (inferred from SDK method)
### Parameters
#### Path Parameters
- **curation_set_name** (String) - Required - Name of the curation set
### Response
#### Success Response
- Returns: `Typesense::CurationSet` instance
```
--------------------------------
### Get Debug Info
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/api_call.md
Retrieves debug information from the Typesense instance.
```APIDOC
## GET /debug
### Description
Retrieves debug information from the Typesense instance.
### Method
GET
### Endpoint
/debug
```
--------------------------------
### Retrieve Stemming Dictionary Details
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/advanced_features.md
Use this method to get the current configuration of the stemming dictionary.
```ruby
StemmingDictionary.retrieve
```
--------------------------------
### Managing Multiple Versioned Collections with Aliases
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/aliases.md
Illustrates how to set up and manage aliases for multiple versioned collections. This allows applications to reference the latest version through a consistent alias name.
```ruby
# Create multiple versioned collections
collections = ['products_v1', 'products_v2', 'products_v3']
# Set up aliases for each major version
client.aliases.upsert('products_latest', { 'collection_name' => 'products_v3' })
client.aliases.upsert('products_v3_alias', { 'collection_name' => 'products_v3' })
client.aliases.upsert('products_v2_alias', { 'collection_name' => 'products_v2' })
client.aliases.upsert('products_v1_alias', { 'collection_name' => 'products_v1' })
# Search through the latest alias
results = client.collections['products_latest'].documents.search({
'q' => 'laptop',
'query_by' => 'title'
})
```
--------------------------------
### Typesense::Synonyms[]
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/overrides_and_synonyms.md
Gets a reference to a specific synonym rule within a collection using its ID.
```APIDOC
## [] (index operator)
### Description
Get a reference to a specific synonym by ID.
### Method
`Synonyms[synonym_id]`
### Parameters
#### Path Parameters
- **synonym_id** (String) - Required - The unique identifier of the synonym to reference.
### Response
#### Success Response
Returns a `Typesense::Synonym` instance.
### Example
```ruby
synonym = client.collections['products'].synonyms['phone_synonyms']
```
```
--------------------------------
### Collections[collection_name]
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/collections.md
Gets a reference to a specific collection by its name, returning a `Collection` instance for further operations.
```APIDOC
## Collections[collection_name]
### Description
Get a reference to a specific collection by name. Returns a `Collection` instance for accessing documents, overrides, and synonyms.
### Method
`Collections[collection_name]`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```ruby
products = client.collections['products']
```
### Response
#### Success Response
`Typesense::Collection` instance
#### Response Example
```ruby
# products is now an instance of Typesense::Collection
```
```
--------------------------------
### Retrieve all curation set items
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/advanced_features.md
Use this method to get all items within a specific curation set.
```ruby
CurationSetItems.retrieve
```
--------------------------------
### Complete Document Workflow in Ruby
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/documents.md
Demonstrates the full lifecycle of document management, including creation, upsertion, bulk import, searching, retrieval, updates, deletion, export, and truncation.
```Ruby
require 'typesense'
# Initialize client (assumes collection 'books' exists)
client = Typesense::Client.new(
api_key: 'xyz',
nodes: [{ host: 'localhost', port: 8108, protocol: 'http' }]
)
books = client.collections['books']
# Create a single document
book1 = books.documents.create({
'id' => '1',
'title' => 'The Hobbit',
'author' => 'J.R.R. Tolkien',
'year' => 1937
})
# Upsert (create or update)
books.documents.upsert({
'id' => '1',
'title' => 'The Hobbit: Enhanced Edition',
'year' => 1937
})
# Import multiple documents
docs = [
{ 'id' => '2', 'title' => 'The Fellowship of the Ring', 'author' => 'J.R.R. Tolkien', 'year' => 1954 },
{ 'id' => '3', 'title' => 'The Two Towers', 'author' => 'J.R.R. Tolkien', 'year' => 1954 },
{ 'id' => '4', 'title' => 'The Return of the King', 'author' => 'J.R.R. Tolkien', 'year' => 1955 }
]
results = books.documents.import(docs)
# Search
search_results = books.documents.search({
'q' => 'fellowship',
'query_by' => 'title',
'limit' => 5
})
# Retrieve a specific document
doc = books.documents['1'].retrieve
# Update a specific document
books.documents['1'].update({
'author' => 'John Tolkien'
})
# Delete a specific document
books.documents['1'].delete
# Delete with filter
books.documents.delete({
'filter_by' => 'year:<1950'
})
# Export all documents
all_docs = books.documents.export
# Truncate collection
books.documents.truncate
```
--------------------------------
### Retrieve Debug Information
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/server_operations.md
Get debug information including server version, configuration, and internal state for troubleshooting.
```APIDOC
## GET /debug
### Description
Retrieve debug information about the Typesense server, including server version, configuration, and internal state.
### Method
GET
### Endpoint
/debug
### Parameters
None
### Request Example
```ruby
debug_info = client.debug.retrieve
```
### Response
#### Success Response (200)
- **version** (string) - The Typesense server version.
- **commit_hash** (string) - The commit hash of the Typesense server build.
- **build_date** (string) - The build date of the Typesense server.
- **total_peers** (integer) - The total number of peers in the cluster.
- **leader_peer** (string) - The address of the leader peer.
- **arguments** (Hash) - Server startup arguments.
- **memory_limit_bytes** (integer) - The memory limit in bytes.
- **memory_usage_bytes** (integer) - The current memory usage in bytes.
- **disk_available_bytes** (integer) - The available disk space in bytes.
- **disk_total_bytes** (integer) - The total disk space in bytes.
- **disk_used_bytes** (integer) - The used disk space in bytes.
#### Response Example
```json
{
"version": "1.5.0",
"commit_hash": "a1b2c3d4e5f6",
"build_date": "2023-10-27",
"total_peers": 1,
"leader_peer": "127.0.0.1:8108",
"arguments": {
"log_level": 2,
"data_dir": "/var/lib/typesense"
},
"memory_limit_bytes": 1073741824,
"memory_usage_bytes": 104857600,
"disk_available_bytes": 53687091200,
"disk_total_bytes": 107374182400,
"disk_used_bytes": 21474836480
}
```
```
--------------------------------
### Retrieve Server Health Status
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/server_operations.md
Get the health status of the Typesense server. This method can be used to poll for readiness.
```ruby
health = client.health.retrieve
puts health.inspect
# Typical response: { 'ok' => true } or { 'ok' => false }
```
--------------------------------
### Working with Multiple Collections
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/collections.md
Illustrates how to create, retrieve, and access multiple collections programmatically. This is useful for managing a large number of collections or performing batch operations.
```ruby
# Create multiple collections
['products', 'categories', 'reviews'].each do |name|
client.collections.create({
'name' => name,
'fields' => [
{ 'name' => 'id', 'type' => 'string' },
{ 'name' => 'title', 'type' => 'string' }
]
})
end
# Retrieve all
all = client.collections.retrieve
# Access each
all.each do |collection_meta|
collection = client.collections[collection_meta['name']]
puts "Collection: #{collection_meta['name']}"
end
```
--------------------------------
### Development Configuration with Debug Logging
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/configuration.md
Sets up the Typesense client for development with detailed debug logging directed to a file. Requires the 'logger' library.
```ruby
require 'logger'
logger = Logger.new('typesense.log')
client = Typesense::Client.new(
api_key: 'test_key',
nodes: [
{
host: 'localhost',
port: 8108,
protocol: 'http'
}
],
connection_timeout_seconds: 30,
logger: logger,
log_level: Logger::DEBUG
)
```
--------------------------------
### Get Document Reference by ID
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/documents.md
Obtain a reference to a specific document using its ID. This is useful for subsequent single-document operations.
```ruby
Documents[document_id]
```
```ruby
doc = client.collections['books'].documents['1']
```
--------------------------------
### Access Analytics Events API
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/analytics.md
Get access to the analytics events API interface. This is used to access analytics events.
```ruby
Analytics.events
```
--------------------------------
### Create, Access, and Search a Typesense Collection
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/client.md
Demonstrates the process of creating a new collection with a defined schema, accessing an existing collection by name, and performing a search operation within that collection.
```ruby
# Create a collection
collection_schema = {
'name' => 'products',
'fields' => [
{ 'name' => 'title', 'type' => 'string' },
{ 'name' => 'price', 'type' => 'float' },
{ 'name' => 'id', 'type' => 'string' }
],
'default_sorting_field' => 'price'
}
client.collections.create(collection_schema)
# Access a specific collection
products = client.collections['products']
# Search the collection
results = products.documents.search({
'q' => 'laptop',
'query_by' => 'title'
})
```
--------------------------------
### Access Analytics Rules API
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/analytics.md
Get access to the analytics rules API interface. This is used to manage analytics rules.
```ruby
Analytics.rules
```
--------------------------------
### Configuration from Environment Variables
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/configuration.md
Configures the Typesense client entirely using environment variables for flexibility and security. Provides default values for common settings.
```ruby
client = Typesense::Client.new(
api_key: ENV.fetch('TYPESENSE_API_KEY'),
nodes: [
{
host: ENV.fetch('TYPESENSE_HOST', 'localhost'),
port: ENV.fetch('TYPESENSE_PORT', 8108).to_i,
protocol: ENV.fetch('TYPESENSE_PROTOCOL', 'http')
}
],
connection_timeout_seconds: ENV.fetch('TYPESENSE_TIMEOUT', 10).to_i,
num_retries: ENV.fetch('TYPESENSE_RETRIES', 3).to_i
)
```
--------------------------------
### Manage Presets in Typesense
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/advanced_features.md
Create, list, and utilize presets for common search configurations. Presets help in applying predefined filters, sorting, and faceting rules.
```ruby
# Create a preset for budget products
client.presets.upsert('budget_products', {
'value' => {
'filter_by' => 'price:<500',
'sort_by' => 'price:asc',
'facet_by' => 'brand,condition'
}
})
# List all presets
presets = client.presets.retrieve
# Use a preset in search
results = client.collections['products'].documents.search({
'q' => 'laptop',
'query_by' => 'title',
**client.presets['budget_products'].retrieve['value']
})
```
--------------------------------
### Accessing Configuration Attributes
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/configuration.md
Demonstrates how to read various configuration values from an initialized Typesense client instance.
```ruby
client = Typesense::Client.new(...)
# Read configuration values
puts client.configuration.api_key
puts client.configuration.nodes
puts client.configuration.connection_timeout_seconds
puts client.configuration.num_retries
puts client.configuration.log_level
```
--------------------------------
### Get Curation Set Reference
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/advanced_features.md
Obtain a reference to a specific curation set using its name. This returns a Typesense::CurationSet instance.
```ruby
CurationSets[curation_set_name]
```
--------------------------------
### Promote New Arrivals in Search Results
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/overrides_and_synonyms.md
Utilize overrides to promote newly added items to the top of search results for all queries. This ensures fresh content is immediately visible to users.
```ruby
client.collections['products'].overrides.upsert('new_arrivals', {
'rule' => {
'query' => '*', # Apply to all queries
'match' => 'exact'
},
'includes' => [
{ 'id' => 'latest_iphone', 'position' => 1 },
{ 'id' => 'latest_airpods', 'position' => 2 }
]
})
```
--------------------------------
### Configure Custom Logger
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/configuration.md
Illustrates how to use a custom logger with the Typesense client, either writing to a file or using a custom class implementation. This allows for flexible log management.
```ruby
# Write logs to file
file_logger = Logger.new('typesense.log', 'daily')
file_logger.level = Logger::DEBUG
client = Typesense::Client.new(
api_key: 'key',
nodes: [{host: 'localhost', port: 8108, protocol: 'http'}],
logger: file_logger
)
# Or use a custom logging implementation
class CustomLogger
def debug(msg); puts "DEBUG: #{msg}"; end
def info(msg); puts "INFO: #{msg}"; end
def warn(msg); puts "WARN: #{msg}"; end
def error(msg); puts "ERROR: #{msg}"; end
attr_accessor :level
end
client = Typesense::Client.new(
api_key: 'key',
nodes: [{host: 'localhost', port: 8108, protocol: 'http'}],
logger: CustomLogger.new,
log_level: Logger::DEBUG
)
```
--------------------------------
### Get Specific Natural Language Search Model
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/advanced_features.md
Obtain a reference to a specific natural language search model using its ID.
```ruby
NlSearchModels[model_id]
```
--------------------------------
### Get Document by ID
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/documents.md
Retrieves a reference to a specific document using its ID. This returns a Document instance that can be used for further single-document operations.
```APIDOC
## GET Documents[document_id]
### Description
Get a reference to a specific document by ID. Returns a `Document` instance for single-document operations.
### Method
GET
### Endpoint
/collections/:collection_name/documents/:document_id
### Parameters
#### Path Parameters
- **document_id** (String) - Required - The document ID
### Request Example
```ruby
doc = client.collections['books'].documents['1']
```
### Response
#### Success Response
- **Typesense::Document** - A Document instance for single-document operations.
```
--------------------------------
### Perform a GET Request
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/api_call.md
Use this method to retrieve data from a Typesense endpoint. It accepts an endpoint path and optional query parameters.
```ruby
result = api_call.get('/collections')
# Returns: { "collections" => [...] } or similar
```
--------------------------------
### Initialize Typesense Client with Keep-Alive Connections
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/client.md
Enable keep-alive connections for improved performance by reducing connection overhead. This configuration includes connection timeouts and idle timeouts for keep-alive.
```ruby
client = Typesense::Client.new(
api_key: 'xyz',
nodes: [
{
host: 'localhost',
port: 8108,
protocol: 'https'
}
],
connection_timeout_seconds: 3,
num_retries: 1,
keep_alive_connections: true,
keep_alive_idle_timeout_seconds: 30
)
```
--------------------------------
### AnalyticsRules[rule_name]
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/analytics.md
Gets a reference to a specific analytics rule by its name. This allows for targeted operations or retrieval of individual rule details.
```APIDOC
## AnalyticsRules[rule_name]
### Description
Get a reference to a specific rule by name.
### Method
GET
### Endpoint
/analytics/rules/{rule_name}
### Parameters
#### Path Parameters
- **rule_name** (string) - Required - The name of the rule to retrieve
```
--------------------------------
### Initialize Typesense Client with Logging Enabled
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/client.md
Configure the client to log requests and responses using Ruby's standard Logger. This helps in debugging and monitoring interactions with Typesense.
```ruby
require 'logger'
logger = Logger.new($stdout)
client = Typesense::Client.new(
api_key: 'xyz',
nodes: [
{
host: 'localhost',
port: 8108,
protocol: 'http'
}
],
logger: logger,
log_level: Logger::DEBUG
)
```
--------------------------------
### Key Create
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/keys.md
Create a new API key with specified permissions and collection access. Keys can be configured with descriptions, allowed actions, collections, and an expiration timestamp.
```APIDOC
## POST /keys
### Description
Create a new API key.
### Method
POST
### Endpoint
/keys
### Parameters
#### Request Body
- **description** (string) - Optional - A description for the key.
- **actions** (array) - Required - A list of allowed actions (e.g., `["documents:search"]`, `["*"]`).
- **collections** (array) - Required - A list of collections the key has access to (e.g., `["products"]`, `["*"]`).
- **expires_at** (integer) - Optional - Unix timestamp in seconds when the key should expire.
### Request Example
```json
{
"description": "Search key for products",
"actions": ["documents:search"],
"collections": ["products"],
"expires_at": 1678886400
}
```
### Response
#### Success Response (200)
- **id** (string) - The unique identifier for the newly created key.
- **value** (string) - The actual API key value.
- **description** (string) - The description provided for the key.
- **actions** (array) - The list of actions allowed by the key.
- **collections** (array) - The list of collections the key has access to.
- **expires_at** (integer) - The Unix timestamp when the key expires, or null if it does not expire.
#### Response Example
```json
{
"id": "key_abc123",
"value": "YOUR_NEW_API_KEY_VALUE",
"description": "Search key for products",
"actions": ["documents:search"],
"collections": ["products"],
"expires_at": 1678886400
}
```
```
--------------------------------
### Typesense::Aliases#[]
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/aliases.md
Gets a reference to a specific alias by its name, returning an Alias instance. This allows for direct interaction with a particular alias.
```APIDOC
## [] (index operator)
### Description
Get a reference to a specific alias by name. Returns an `Alias` instance.
### Method
`Aliases[alias_name]`
### Parameters
#### Path Parameters
- **alias_name** (String) - Required - The alias name
### Response
`Typesense::Alias` instance
### Request Example
```ruby
alias_ref = client.aliases['products']
```
```
--------------------------------
### Get a Specific Alias Reference
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/aliases.md
Obtain a reference to a specific alias by its name. This returns an Alias instance that can be used for further operations on that alias.
```ruby
alias_ref = client.aliases['products']
```
--------------------------------
### Create API Key
Source: https://github.com/typesense/typesense-ruby/blob/master/_autodocs/api-reference/api_call.md
Creates a new API key.
```APIDOC
## POST /keys
### Description
Creates a new API key.
### Method
POST
### Endpoint
/keys
```