acseo/typesense-bundle

此包提供在Symfony中与Typesense的集成

安装次数: 50 782

依赖关系: 0

建议者: 0

安全: 0

星标: 55

关注者: 5

分支: 33

开放问题: 18

类型:symfony-bundle

v0.7.9 2024-07-19 10:23 UTC

README

此包提供与Typesense的集成。

它依赖于官方的TypeSense PHP

功能包括

  • Doctrine对象转换到Typesense可索引数据
  • 用于在集合中搜索的有用服务
  • Doctrine事件监听器以自动索引

安装

使用composer安装此包

composer require acseo/typesense-bundle

在您的Symfony项目中启用此包

<?php
// config/bundles.php

return [
    ACSEO\TypesenseBundle\ACSEOTypesenseBundle::class => ['all' => true],

配置

配置包

# .env
TYPESENSE_URL=https://:8108
TYPESENSE_KEY=123
# config/packages/acseo_typesense.yml
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
                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

            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.

您可以使用Typesense支持的基本字段类型:字符串、int32、float等。您还可以使用特定的类型名称,例如:primary、collection、object

从Doctrine实体到Typesense数据的转换由ACSEO\TypesenseBundle\Transformer\DoctrineToTypesenseTransformer管理

使用方法

创建索引并填充数据

此包包含创建和索引数据的实用命令

# Creation collections structure
php bin/console typesense:create

# Import collections with Doctrine entities
php bin/console typesense:import

搜索文档

此包创建动态通用查找服务,允许您查询Typesense

查找服务命名如下:typesense.finder.collection_name

您可以将通用查找器注入到您的Controller或其他服务中。

您还可以为集合创建特定的查找器。请参阅下面的文档。

# config/services.yaml
services:
    App\Controller\BookController:
        arguments:
            $bookFinder: '@typesense.finder.books'    
<?php

// src/Controller/BookController.php

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use ACSEO\TypesenseBundle\Finder\TypesenseQuery;

//
class BookController extends AbstractController
{
    private $bookFinder;

    public function __construct($bookFinder)
    {
        $this->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
        //    ]
        // ]
    }

查询Typesense

TypesenseQuery()类接受两个参数

  • 搜索术语(q
  • 搜索的字段(queryBy

您可以使用所有可能的Typesense 搜索参数创建更复杂的查询

<?php

use ACSEO\TypesenseBundle\Finder\TypesenseQuery;

$simpleQuery = new TypesenseQuery('search term', 'collection field to search in');

$complexQuery = new TypesenseQuery('search term', 'collection field to search in')
                      ->filterBy('theme: [adventure, thriller]')
                      ->addParameter('key', 'value')
                      ->sortBy('year:desc');

为集合创建特定查找器

您可以为声明的每个集合轻松创建特定的查找器。

# 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     #

此配置将创建一个名为@typesense.finder.books.books_autocomplete的服务。
您可以将特定查找器注入到您的Controller或其他服务中

# config/services.yaml
services:
    App\Controller\BookController:
        arguments:
            $autocompleteBookFinder: '@typesense.finder.books.books_autocomplete'

然后像这样使用它

<?php
// src/Controller/BookController.php

class BookController extends AbstractController
{
    private $autocompleteBookFinder;

    public function __construct($autocompleteBookFinder)
    {
        $this->autocompleteBookFinder = $autocompleteBookFinder;
    }

    public function autocomplete($term = '')
    {
        $results = $this->autocompleteBookFinder->search($term)->getResults();
        // or if you want raw results
        $rawResults = $this->autocompleteBookFinder->search($term)->getRawResults();
    }

使用不同类型的服务

此包创建了不同的服务,您可以在Controller或其他任何地方使用它们。

  • typesense.client:从官方的typesense-php包继承的基本客户端
  • typesense.collection_client:此服务允许您对集合执行基本操作,并允许执行searchmultisearch操作。
  • typesense.finder.*:此生成的服务允许您在特定集合上执行queryrawQuery。生成的服务示例:typesense.finder.candidates
  • typesense.specificfinder.*.*:此生成的服务允许您运行预配置的请求(在:config/packages/acseo_typesense.yml中声明)。生成的服务示例:typesense.specificfinder.candidates.default

注意:还有其他服务。您可以使用debug:container命令查看所有服务。

Doctrine监听器

Doctrine监听器将在以下事件期间更新Typesense实体数据

  • postPersist
  • postUpdate
  • preDelete

执行多搜索

您可以使用collectionClient服务创建多搜索请求并获取结果。

// 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);

食谱

测试包

测试用例编写在 tests 目录中。

  • 单元测试 不需要运行 Typesense 服务器
  • 功能测试 需要运行 Typesense 服务器

您可以使用以下命令启动测试

# 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