### Base Template Setup
Source: https://github.com/acseo/typesensebundle/blob/master/doc/cookbook/autocomplete.md
Include necessary Bootstrap and jQuery dependencies in the base template.
```html
{% block body %}{% endblock %}
{% block javascripts %}{% endblock %}
```
--------------------------------
### Install ACSEOTypesenseBundle via Composer
Source: https://github.com/acseo/typesensebundle/blob/master/README.md
Use this command to add the bundle dependency to your Symfony project.
```bash
composer require acseo/typesense-bundle
```
--------------------------------
### Build a Basic Typesense Query
Source: https://context7.com/acseo/typesensebundle/llms.txt
Instantiate TypesenseQuery with a search term and fields to search within. This is the starting point for constructing more complex queries.
```php
client->getMetrics()->retrieve();
}
```
--------------------------------
### Get Server Health with TypesenseClient
Source: https://context7.com/acseo/typesensebundle/llms.txt
Retrieves the health status of the Typesense server using the TypesenseClient. Ensure the TypesenseClient is injected into your service.
```php
client->getHealth()->retrieve();
// ['ok' => true]
}
// ... other methods
```
--------------------------------
### Get Typesense Base URL
Source: https://context7.com/acseo/typesensebundle/llms.txt
Retrieves the base URL of the Typesense server from the client configuration. This can be useful for debugging or external integrations.
```php
public function getBaseUrl(): ?string
{
return $this->client->getBaseUrl();
// 'http://localhost:8108'
}
}
```
--------------------------------
### Run bundle tests
Source: https://github.com/acseo/typesensebundle/blob/master/README.md
Commands to execute unit and functional tests for the bundle.
```bash
# Unit test
$ php ./vendor/bin/phpunit tests/Unit
# Functional test
# First, start a Typesense server with Docker
$ composer run-script typesenseServer
$ php ./vendor/bin/phpunit tests/Functional
```
--------------------------------
### Configure and Implement Autocomplete
Source: https://context7.com/acseo/typesensebundle/llms.txt
Define the autocomplete route and use the bootstrap-autocomplete library on the frontend to query the built-in endpoint.
```yaml
# config/routes.yaml
autocomplete:
path: /api/autocomplete
controller: typesense.autocomplete_controller:autocomplete
```
```php
```
--------------------------------
### Create Typesense Collections
Source: https://github.com/acseo/typesensebundle/blob/master/README.md
Command to create the collection structures in Typesense based on the bundle's configuration. Ensure your Typesense connection is properly configured.
```bash
php bin/console typesense:create
```
--------------------------------
### Configure Typesense Environment Variables
Source: https://github.com/acseo/typesensebundle/blob/master/README.md
Set the Typesense URL and API key in your .env file.
```text
# .env
TYPESENSE_URL=http://localhost:8108
TYPESENSE_KEY=123
```
--------------------------------
### Execute Console Commands for Collections and Imports
Source: https://context7.com/acseo/typesensebundle/llms.txt
Use Symfony console commands to create collection schemas and perform bulk data imports with pagination and action control.
```bash
# Create all configured collections (deletes existing first)
php bin/console typesense:create
# Create specific collections only
php bin/console typesense:create --indexes=books,authors
# Import all entities into Typesense
php bin/console typesense:import
# Import specific collections with pagination control
php bin/console typesense:import --indexes=books --max-per-page=500 --first-page=1 --last-page=10
# Import with different actions
php bin/console typesense:import --action=create # Fail if document exists
php bin/console typesense:import --action=upsert # Create or update (default)
php bin/console typesense:import --action=update # Fail if document doesn't exist
# Verbose output for debugging
php bin/console typesense:import -vvv
```
--------------------------------
### Implement Search Controller with Specific Finders
Source: https://context7.com/acseo/typesensebundle/llms.txt
Inject specific collection finders into a controller to perform pre-configured or raw searches.
```php
autocompleteBookFinder->search($term);
$suggestions = array_map(
fn($book) => ['id' => $book->getId(), 'title' => $book->getTitle()],
$response->getResults()
);
return new JsonResponse($suggestions);
}
public function featured(): array
{
// Search with additional query on top of pre-configured params
$query = new TypesenseQuery('*', null); // Match all
$response = $this->featuredBookFinder->query($query);
return $response->getResults();
}
public function rawAutocomplete(string $term): JsonResponse
{
$query = new TypesenseQuery($term, 'title');
$response = $this->autocompleteBookFinder->rawQuery($query);
return new JsonResponse($response->getRawResults());
}
}
```
--------------------------------
### Enable ACSEOTypesenseBundle in Symfony
Source: https://github.com/acseo/typesensebundle/blob/master/README.md
Register the bundle in your config/bundles.php file.
```php
['all' => true],
```
--------------------------------
### Create API Key with TypesenseClient
Source: https://context7.com/acseo/typesensebundle/llms.txt
Generates a new API key for Typesense with specified actions and collection access. The key is configured with a description, allowed actions, collections, and an expiration time.
```php
public function createApiKey(array $actions, array $collections): array
{
return $this->client->getKeys()->create([
'description' => 'Search-only key',
'actions' => $actions, // ['documents:search']
'collections' => $collections, // ['books', 'authors']
'expires_at' => time() + 86400, // 24 hours
]);
}
```
--------------------------------
### Autocomplete Search Implementation
Source: https://github.com/acseo/typesensebundle/blob/master/doc/cookbook/autocomplete.md
Configure the autocomplete input field and handle the AJAX response using bootstrap-autocomplete.
```html
{% extends 'base.html.twig' %}
{% block body %}
{% endblock %}
{% block javascripts %}
{% endblock %}
```
--------------------------------
### Configure Typesense Collections in YAML
Source: https://context7.com/acseo/typesensebundle/llms.txt
Define collection entities, sorting fields, and finder parameters within the bundle configuration.
```yaml
acseo_typesense:
collections:
books:
entity: 'App\Entity\Book'
default_sorting_field: sortable_id
fields:
# ... field definitions ...
finders:
autocomplete:
finder_parameters:
query_by: title
prefix: true
num_typos: 1
limit: 10
drop_tokens_threshold: 1
featured:
finder_parameters:
query_by: title,description
filter_by: 'is_featured:=true'
sort_by: 'featured_rank:asc'
per_page: 6
```
--------------------------------
### Build a Complex Typesense Query with All Options
Source: https://context7.com/acseo/typesensebundle/llms.txt
Utilize the fluent interface of TypesenseQuery to chain multiple methods for advanced search configurations including filtering, sorting, faceting, pagination, and custom parameters. Enable prefix and infix matching for enhanced search capabilities.
```php
filterBy('author_country:=France && published_at:>1609459200')
->sortBy('published_at:desc,_text_match:desc')
->facetBy('author_country,genres')
->maxFacetValues(100)
->facetQuery('author_country:Fran')
->page(1)
->perPage(20)
->numTypos(2)
->prefix(true) // Enable prefix matching for autocomplete
->infix('always') // Enable infix search
->groupBy('author_country')
->groupLimit(3)
->includeFields('id,title,author,published_at')
->excludeFields('embeddings')
->highlightFullFields('title')
->snippetThreshold(30)
->dropTokensThreshold(1)
->typoTokensThreshold(1)
->pinnedHits('123:1,456:2') // Pin document 123 to position 1
->hiddenHits('789,012') // Hide specific documents
->maxHits(100)
->addParameter('vector_query', 'embeddings:([], k:10)'); // Custom parameter
// Get query parameters for debugging
$params = $query->getParameters();
// Result: ['q' => 'fantasy adventure', 'query_by' => 'title,description,genres', 'filter_by' => '...', ...]
```
--------------------------------
### Enable Autocomplete Route
Source: https://github.com/acseo/typesensebundle/blob/master/doc/cookbook/autocomplete.md
Register the autocomplete controller route in your application configuration.
```yaml
# config/routes.yaml
autocomplete:
path: /autocomplete
controller: typesense.autocomplete_controller:autocomplete
```
--------------------------------
### Perform Multi-Search and Collection Operations
Source: https://context7.com/acseo/typesensebundle/llms.txt
Use the CollectionClient for federated multi-search across collections and direct collection management.
```php
addParameter('collection', 'books')
->perPage(5),
(new TypesenseQuery($term, 'name'))
->addParameter('collection', 'authors')
->perPage(5),
(new TypesenseQuery($term, 'name'))
->addParameter('collection', 'publishers')
->perPage(3),
];
// Common params applied to all searches
$commonParams = (new TypesenseQuery(null, null))
->numTypos(1)
->prefix(true);
$response = $this->collectionClient->multiSearch($searchRequests, $commonParams);
// Response structure:
// [
// 'results' => [
// ['hits' => [...], 'found' => 42, 'search_time_ms' => 5], // books
// ['hits' => [...], 'found' => 12, 'search_time_ms' => 3], // authors
// ['hits' => [...], 'found' => 8, 'search_time_ms' => 2], // publishers
// ]
// ]
return [
'books' => $response['results'][0]['hits'] ?? [],
'authors' => $response['results'][1]['hits'] ?? [],
'publishers' => $response['results'][2]['hits'] ?? [],
];
}
public function searchSingleCollection(string $collection, string $term): array
{
$query = (new TypesenseQuery($term, 'title,description'))
->filterBy('status:=published')
->sortBy('_text_match:desc');
return $this->collectionClient->search($collection, $query);
}
public function listCollections(): array
{
return $this->collectionClient->list();
// Returns: [['name' => 'books', 'num_documents' => 1500, ...], ...]
}
}
```
--------------------------------
### Use Specific Finder in Controller
Source: https://github.com/acseo/typesensebundle/blob/master/README.md
Utilize the injected specific finder to perform searches.
```php
autocompleteBookFinder = $autocompleteBookFinder;
}
public function autocomplete($term = '')
{
$results = $this->autocompleteBookFinder->search($term)->getResults();
// or if you want raw results
$rawResults = $this->autocompleteBookFinder->search($term)->getRawResults();
}
```
--------------------------------
### Query Typesense in a Controller
Source: https://github.com/acseo/typesensebundle/blob/master/README.md
Use the injected finder to perform searches and retrieve either hydrated Doctrine objects or raw Typesense results.
```php
bookFinder = $bookFinder;
}
public function search()
{
$query = new TypesenseQuery('Jules Vernes', 'author');
// Get Doctrine Hydrated objects
$results = $this->bookFinder->query($query)->getResults();
// dump($results)
// array:2 [▼
// 0 => App\Entity\Book {#522 ▶}
// 1 => App\Entity\Book {#525 ▶}
//]
// Get raw results from Typesence
$rawResults = $this->bookFinder->rawQuery($query)->getResults();
// dump($rawResults)
// array:2 [▼
// 0 => array:3 [▼
// "document" => array:4 [▼
// "author" => "Jules Vernes"
// "id" => "100"
// "published_at" => 1443744000
// "title" => "Voyage au centre de la Terre "
// ]
// "highlights" => array:1 [▶]
// "seq_id" => 4
// ]
// 1 => array:3 [▼
// "document" => array:4 [▶]
// "highlights" => array:1 [▶]
// "seq_id" => 6
// ]
// ]
}
```
--------------------------------
### Configure Typesense Connection and Collections
Source: https://context7.com/acseo/typesensebundle/llms.txt
Defines the Typesense connection parameters and maps Doctrine entities to Typesense collections. Ensure Typesense URL and API key are set in environment variables. Collection-specific settings like default sorting, symbols to index, token separators, and field mappings are configured here.
```yaml
# config/packages/acseo_typesense.yml
acseo_typesense:
typesense:
url: '%env(resolve:TYPESENSE_URL)%'
key: '%env(resolve:TYPESENSE_KEY)%'
collection_prefix: 'app_' # Optional prefix for all collections
collections:
books: # Collection name
entity: 'App\Entity\Book' # Doctrine entity class
default_sorting_field: sortable_id # Required: must be int32 or float
symbols_to_index: ['+'] # Index symbols like c++
token_separators: ['+', '-', '@', '.'] # Split tokens on these chars
enable_nested_fields: true # Enable nested object support
fields:
id:
name: id
type: primary # Maps to string, used for sync
sortable_id:
entity_attribute: id
name: sortable_id
type: int32 # Used for default sorting
title:
name: title
type: string
author:
name: author
type: object # Uses __toString() method
author_country:
entity_attribute: author.country # Nested property access
name: author_country
type: string
facet: true # Enable faceting/grouping
genres:
name: genres
type: collection # ArrayCollection to string[]
collection_field: name # Field to extract from items
published_at:
name: published_at
type: datetime # Converts to int64 timestamp
optional: true # Field can be null
cover_url:
name: cover_url
type: string
entity_attribute: App\Service\BookService::getCoverUrl # Service converter
embeddings:
name: embeddings
type: float[]
embed:
from: [title, description]
model_config:
model_name: ts/e5-small # Typesense Cloud embedding model
```
--------------------------------
### Configure Typesense Connection and Collections
Source: https://github.com/acseo/typesensebundle/blob/master/README.md
Defines Typesense connection parameters (URL, API key) and collection configurations, including entity mapping and field definitions for 'books' and 'users' collections. Supports advanced field types and configurations like facets, optional fields, and embeddings.
```yaml
acseo_typesense:
# Typesense host settings
typesense:
url: '%env(resolve:TYPESENSE_URL)%'
key: '%env(resolve:TYPESENSE_KEY)%'
collection_prefix: 'test_' # Optional : add prefix to all collection
# names in Typesense
# Collection settings
collections:
books: # Typesense collection name
entity: 'App\Entity\Book' # Doctrine Entity class
fields:
#
# Keeping Database and Typesense synchronized with ids
#
id: # Entity attribute name
name: id # Typesense attribute name
type: primary # Attribute type
#
# Using again id as a sortable field (int32 required)
#
sortable_id:
entity_attribute: id # Entity attribute name forced
name: sortable_id # Typesense field name
type: int32
title:
name: title
type: string
description:
name: title
type: description
author:
name: author
type: object # Object conversion with __toString()
author.country:
name: author_country
type: string
facet: true # Declare field as facet (required to use "group_by" query option)
entity_attribute: author.country # Equivalent of $book->getAuthor()->getCountry()
genres:
name: genres
type: collection # Convert ArrayCollection to array of strings
publishedAt:
name: publishedAt
type: datetime
optional: true # Declare field as optional
cover_image_url:
name: cover_image_url
type: string
optional: true
entity_attribute: ACSEO\Service\BookConverter::getCoverImageURL # use a service converter instead of an attribute
embeddings: # Since Typesense 0.25, you can generate Embeddings on the fly
name: embeddings # and retrieve your documents using an vectorial search
type: float[] # more info : https://typesense.org/docs/27.0/api/vector-search.html
embed:
from:
- title
- description
model_config:
model_name: ts/e5-small # Typesense Cloud model (requires Typesense Cloud)
# For custom embedding services (Ollama, local models, etc.):
# model_name: 'openai/your-model-name'
# url: 'http://your-embedding-service:port'
# api_key: 'your-api-key' # Optional
default_sorting_field: sortable_id # Default sorting field. Must be int32 or float
symbols_to_index: ['+'] # Optional - You can add + to this list to make the word c++ indexable verbatim.
users:
entity: App\Entity\User
fields:
id:
name: id
type: primary
sortable_id:
entity_attribute: id
name: sortable_id
type: int32
email:
name: email
type: string
default_sorting_field: sortable_id
token_separators: ['+', '-', '@', '.'] # Optional - This will cause contact+docs-example@typesense.org to be indexed as contact, docs, example, typesense and org.
```
--------------------------------
### Construct Typesense Queries
Source: https://github.com/acseo/typesensebundle/blob/master/README.md
Create simple or complex search queries using the TypesenseQuery class.
```php
filterBy('theme: [adventure, thriller]')
->addParameter('key', 'value')
->sortBy('year:desc');
```
--------------------------------
### Perform multisearch with collectionClient
Source: https://github.com/acseo/typesensebundle/blob/master/README.md
Use the collectionClient service to execute federated multisearch requests across multiple collections.
```php
// Peform multisearch
$searchRequests = [
(new TypesenseQuery('Jules'))->addParameter('collection', 'author'),
(new TypesenseQuery('Paris'))->addParameter('collection', 'library')
];
$commonParams = new TypesenseQuery()->addParameter('query_by', 'name');
$response = $this->collectionClient->multisearch($searchRequests, $commonParams);
```
--------------------------------
### Declare a Typesense Finder
Source: https://github.com/acseo/typesensebundle/blob/master/doc/cookbook/autocomplete.md
Define a specific finder within the TypesenseBundle configuration to handle search parameters.
```yaml
# config/packages/acseo_typesense.yml
acseo_typesense:
# ...
# Collection settings
collections:
books: # Typesense collection name
# ... # Colleciton fields definition
# ...
finders: # Declare your specific finder
books_autocomplete: # Finder name
finder_parameters: # Parameters used by the finder
query_by: title #
limit: 10 # You can add as key / valuesspecifications
prefix: true # based on Typesense Request
num_typos: 1 #
drop_tokens_threshold: 1 #
```
--------------------------------
### Import Doctrine Entities to Typesense
Source: https://github.com/acseo/typesensebundle/blob/master/README.md
Command to import data from Doctrine entities into Typesense collections. This synchronizes your database with your Typesense index.
```bash
php bin/console typesense:import
```
--------------------------------
### Register Controller Services
Source: https://context7.com/acseo/typesensebundle/llms.txt
Map specific Typesense finder services to controller arguments in the Symfony service container.
```yaml
# config/services.yaml
services:
App\Controller\SearchController:
arguments:
$autocompleteBookFinder: '@typesense.specificfinder.books.autocomplete'
$featuredBookFinder: '@typesense.specificfinder.books.featured'
```
--------------------------------
### Manage Collection Schemas
Source: https://context7.com/acseo/typesensebundle/llms.txt
Use CollectionManager to retrieve definitions, list existing collections, and perform lifecycle operations like creation and deletion.
```php
collectionManager->getCollectionDefinitions();
// ['books' => ['entity' => 'App\Entity\Book', 'fields' => [...]], ...]
// Get entity class to collection mapping
$classNames = $this->collectionManager->getManagedClassNames();
// ['books' => 'App\Entity\Book', 'authors' => 'App\Entity\Author']
// List all existing collections in Typesense
$existing = $this->collectionManager->getAllCollections();
foreach ($existing as $collection) {
$output->writeln("Found: {$collection['name']} ({$collection['num_documents']} docs)");
}
// Recreate a specific collection (delete + create)
try {
$this->collectionManager->deleteCollection('books');
$output->writeln('Deleted books collection');
} catch (\Typesense\Exceptions\ObjectNotFound $e) {
$output->writeln('Collection did not exist');
}
$this->collectionManager->createCollection('books');
$output->writeln('Created books collection');
// Or create all configured collections
$this->collectionManager->createAllCollections();
return Command::SUCCESS;
}
}
```
--------------------------------
### Perform Document CRUD Operations
Source: https://context7.com/acseo/typesensebundle/llms.txt
Use DocumentManager to index, delete, and bulk import documents into Typesense collections.
```php
transformer->convert($book);
// Upsert single document (creates or updates)
return $this->documentManager->index('books', $data);
// Returns: ['id' => '123', 'title' => 'My Book', ...]
}
public function deleteBook(string $documentId): array
{
return $this->documentManager->delete('books', $documentId);
// Returns: ['id' => '123']
}
public function bulkImport(array $books, string $action = 'upsert'): array
{
$data = array_map(
fn(Book $book) => $this->transformer->convert($book),
$books
);
// Bulk import with action: 'create', 'upsert', or 'update'
$results = $this->documentManager->import('books', $data, $action);
// Returns array of results:
// [
// ['success' => true],
// ['success' => true],
// ['success' => false, 'error' => 'Document already exists', 'document' => '...'],
// ]
$errors = array_filter($results, fn($r) => !$r['success']);
if (count($errors) > 0) {
throw new \Exception('Import failed for ' . count($errors) . ' documents');
}
return $results;
}
}
```
--------------------------------
### TypesenseQuery - Building Search Queries
Source: https://context7.com/acseo/typesensebundle/llms.txt
The TypesenseQuery class provides a fluent interface for constructing Typesense search queries with all supported parameters including filtering, sorting, faceting, and pagination.
```APIDOC
## TypesenseQuery - Building Search Queries
### Description
The `TypesenseQuery` class provides a fluent interface for constructing Typesense search queries with all supported parameters including filtering, sorting, faceting, and pagination.
### Usage Examples
**Basic search query:**
```php
use ACSEO\TypesenseBundle\Finder\TypesenseQuery;
$query = new TypesenseQuery('harry potter', 'title,description');
```
**Complex query with all options:**
```php
$query = (new TypesenseQuery('fantasy adventure', 'title,description,genres'))
->filterBy('author_country:=France && published_at:>1609459200')
->sortBy('published_at:desc,_text_match:desc')
->facetBy('author_country,genres')
->maxFacetValues(100)
->facetQuery('author_country:Fran')
->page(1)
->perPage(20)
->numTypos(2)
->prefix(true) // Enable prefix matching for autocomplete
->infix('always') // Enable infix search
->groupBy('author_country')
->groupLimit(3)
->includeFields('id,title,author,published_at')
->excludeFields('embeddings')
->highlightFullFields('title')
->snippetThreshold(30)
->dropTokensThreshold(1)
->typoTokensThreshold(1)
->pinnedHits('123:1,456:2') // Pin document 123 to position 1
->hiddenHits('789,012') // Hide specific documents
->maxHits(100)
->addParameter('vector_query', 'embeddings:([], k:10)'); // Custom parameter
```
**Get query parameters for debugging:**
```php
$params = $query->getParameters();
// Result: ['q' => 'fantasy adventure', 'query_by' => 'title,description,genres', 'filter_by' => '...', ...]
```
### Parameters
- **search_term** (string) - Required - The main search term.
- **query_by** (string) - Required - A comma-separated list of fields to search within.
### Methods
- `filterBy(string $filter)`: Sets the filter criteria.
- `sortBy(string $sort)`: Sets the sorting order.
- `facetBy(string $facet)`: Specifies fields for faceting.
- `maxFacetValues(int $limit)`: Sets the maximum number of facet values.
- `facetQuery(string $facetQuery)`: Applies a query to filter facet values.
- `page(int $page)`: Sets the current page number.
- `perPage(int $limit)`: Sets the number of results per page.
- `numTypos(int $typos)`: Sets the number of allowed typos.
- `prefix(bool $enable)`: Enables prefix matching.
- `infix(string $mode)`: Enables infix search.
- `groupBy(string $field)`: Groups results by a specific field.
- `groupLimit(int $limit)`: Sets the limit for grouped results.
- `includeFields(string $fields)`: Specifies fields to include in the results.
- `excludeFields(string $fields)`: Specifies fields to exclude from the results.
- `highlightFullFields(string $fields)`: Fields to highlight.
- `snippetThreshold(int $threshold)`: Threshold for snippet generation.
- `dropTokensThreshold(int $threshold)`: Threshold for dropping tokens.
- `typoTokensThreshold(int $threshold)`: Threshold for typo tokens.
- `pinnedHits(string $hits)`: Specifies pinned documents and their positions.
- `hiddenHits(string $hits)`: Specifies documents to hide.
- `maxHits(int $max)`: Sets the maximum number of hits to return.
- `addParameter(string $key, mixed $value)`: Adds a custom parameter to the query.
- `getParameters()`: Returns the query parameters as an array.
```
--------------------------------
### Execute Search with Doctrine Hydration
Source: https://context7.com/acseo/typesensebundle/llms.txt
Use CollectionFinderInterface to execute a TypesenseQuery and automatically hydrate the results into Doctrine entities. This service maintains the order of search results.
```php
filterBy('author_country:=France')
->sortBy('published_at:desc')
->perPage(10);
// Get hydrated Doctrine entities
$response = $this->bookFinder->query($query);
$books = $response->getResults(); // App\Entity\Book[] - Doctrine entities
$totalFound = $response->getFound(); // Total matching documents
$currentPage = $response->getPage(); // Current page number
$facets = $response->getFacetCounts(); // Facet counts array
// Get raw Typesense results without hydration
$rawResponse = $this->bookFinder->rawQuery($query);
$rawHits = $rawResponse->getRawResults();
// [
// ['document' => ['id' => '1', 'title' => '...'], 'highlights' => [...], 'text_match' => 123],
// ['document' => ['id' => '2', 'title' => '...'], 'highlights' => [...], 'text_match' => 100],
// ]
// Hydrate a raw response later
$hydratedResponse = $this->bookFinder->hydrateResponse($rawResponse);
return $this->render('book/search.html.twig', [
'books' => $books,
'total' => $totalFound,
'facets' => $facets,
]);
}
}
```
--------------------------------
### Manage Automatic Doctrine Indexing
Source: https://context7.com/acseo/typesensebundle/llms.txt
The TypesenseIndexer automatically syncs entities on flush. Disable it by removing the event listener tags in services.yaml.
```php
setTitle('New Book');
$book->setAuthor($author);
$entityManager->persist($book);
$entityManager->flush(); // Automatically indexed in Typesense
$book->setTitle('Updated Title');
$entityManager->flush(); // Automatically updated in Typesense
$entityManager->remove($book);
$entityManager->flush(); // Automatically deleted from Typesense
```
```yaml
# To disable automatic indexing, remove the event listener
# config/services.yaml
services:
ACSEO\TypesenseBundle\EventListener\TypesenseIndexer:
tags: [] # Remove doctrine.event_listener tags
```
--------------------------------
### Inject Generic Finder in Symfony Services
Source: https://github.com/acseo/typesensebundle/blob/master/README.md
Configure a generic finder service for a specific collection in your Symfony services configuration.
```yaml
# config/services.yaml
services:
App\Controller\BookController:
arguments:
$bookFinder: '@typesense.finder.books'
```
--------------------------------
### Inject Specific Finder in Symfony Services
Source: https://github.com/acseo/typesensebundle/blob/master/README.md
Inject the custom finder service into your controller.
```yaml
# config/services.yaml
services:
App\Controller\BookController:
arguments:
$autocompleteBookFinder: '@typesense.specificfinder.books.books_autocomplete'
```
--------------------------------
### Create or Update Alias with TypesenseClient
Source: https://context7.com/acseo/typesensebundle/llms.txt
Creates or updates an alias for a Typesense collection. This is useful for managing collection versions or redirects.
```php
public function createAlias(string $alias, string $collection): array
{
return $this->client->getAliases()->upsert($alias, [
'collection_name' => $collection
]);
}
```
--------------------------------
### CollectionFinder - Search with Doctrine Hydration
Source: https://context7.com/acseo/typesensebundle/llms.txt
The CollectionFinder service executes searches against Typesense and automatically hydrates results with corresponding Doctrine entities, maintaining the search result order.
```APIDOC
## CollectionFinder - Search with Doctrine Hydration
### Description
The `CollectionFinder` service executes searches against Typesense and automatically hydrates results with corresponding Doctrine entities, maintaining the search result order.
### Usage Example
```php
filterBy('author_country:=France')
->sortBy('published_at:desc')
->perPage(10);
// Get hydrated Doctrine entities
$response = $this->bookFinder->query($query);
$books = $response->getResults(); // App\Entity\Book[] - Doctrine entities
$totalFound = $response->getFound(); // Total matching documents
$currentPage = $response->getPage(); // Current page number
$facets = $response->getFacetCounts(); // Facet counts array
// Get raw Typesense results without hydration
$rawResponse = $this->bookFinder->rawQuery($query);
$rawHits = $rawResponse->getRawResults();
// [
// ['document' => ['id' => '1', 'title' => '...'], 'highlights' => [...], 'text_match' => 123],
// ['document' => ['id' => '2', 'title' => '...'], 'highlights' => [...], 'text_match' => 100],
// ]
// Hydrate a raw response later
$hydratedResponse = $this->bookFinder->hydrateResponse($rawResponse);
return $this->render('book/search.html.twig', [
'books' => $books,
'total' => $totalFound,
'facets' => $facets,
]);
}
}
```
### Methods
- `query(TypesenseQuery $query)`: Executes a search query and returns hydrated results.
- `rawQuery(TypesenseQuery $query)`: Executes a search query and returns raw Typesense results.
- `hydrateResponse(object $rawResponse)`: Hydrates a raw Typesense response.
### Response Object Properties
- `getResults()`: Returns an array of hydrated Doctrine entities.
- `getFound()`: Returns the total number of matching documents.
- `getPage()`: Returns the current page number.
- `getFacetCounts()`: Returns the facet counts array.
- `getRawResults()`: Returns the raw search results from Typesense.
```
--------------------------------
### Convert Doctrine Entities to Typesense Documents
Source: https://context7.com/acseo/typesensebundle/llms.txt
Use the DoctrineToTypesenseTransformer to map entities to Typesense documents. Custom service converters can be implemented to handle specific field logic.
```php
transformer->convert($book);
// Result based on field configuration:
// [
// 'id' => '123', // primary -> string
// 'sortable_id' => 123, // int32
// 'title' => 'The Great Book', // string
// 'author' => 'John Doe', // object -> __toString()
// 'author_country' => 'France', // nested property
// 'genres' => ['Fiction', 'Adventure'], // collection -> string[]
// 'published_at' => 1609459200, // datetime -> int64 timestamp
// 'cover_url' => 'https://...', // from service converter
// ]
return $data;
}
}
// Custom service converter example
namespace App\Service;
use App\Entity\Book;
class BookService
{
public function getCoverUrl(Book $book): ?string
{
if (!$book->getCoverImage()) {
return null;
}
return 'https://cdn.example.com/covers/' . $book->getCoverImage();
}
}
```
--------------------------------
### Check Typesense Operational Status
Source: https://context7.com/acseo/typesensebundle/llms.txt
Verifies if the Typesense client is operational. This method returns a boolean indicating the operational status.
```php
public function checkOperational(): bool
{
return $this->client->isOperationnal();
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.