首页
/ FOSElasticaBundle 技术文档

FOSElasticaBundle 技术文档

2024-12-25 18:17:48作者:晏闻田Solitary

1. 安装指南

1.1 系统要求

  • PHP 版本:^7.4 或 ^8.0
  • Symfony 版本:^5.4 或 ^6.4 或 ^7.0
  • Elasticsearch 版本:7.*
  • Elastica 版本:^7.1

1.2 安装步骤

  1. 使用 Composer 安装 FOSElasticaBundle:

    composer require friendsofsymfony/elastica-bundle
    
  2. 如果使用 Symfony Flex,安装过程中会自动配置 recipe。如果没有使用 Symfony Flex,需要手动配置 bundle。

  3. config/bundles.php 中添加以下内容:

    return [
        // 其他 bundles
        FOS\ElasticaBundle\FOSElasticaBundle::class => ['all' => true],
    ];
    
  4. 配置 Elasticsearch 连接信息,编辑 config/packages/fos_elastica.yaml 文件:

    fos_elastica:
        clients:
            default: { host: localhost, port: 9200 }
        indexes:
            app:
                types:
                    user:
                        properties:
                            username: ~
                            email: ~
                        persistence:
                            driver: orm
                            model: App\Entity\User
                            provider: ~
                            listener: ~
                            finder: ~
    

2. 项目的使用说明

2.1 基本使用

FOSElasticaBundle 提供了与 Elasticsearch 的集成,支持自动索引和数据映射。以下是基本使用步骤:

  1. 配置索引:在 fos_elastica.yaml 中配置索引和类型。
  2. 自动索引:通过 Doctrine 事件监听器,自动将数据索引到 Elasticsearch。
  3. 查询数据:使用 Finder 服务查询 Elasticsearch 中的数据。

2.2 示例代码

// 查询示例
$finder = $container->get('fos_elastica.finder.app.user');
$users = $finder->find('search query');

3. 项目API使用文档

3.1 客户端 API

FOSElasticaBundle 提供了 Elastica 客户端的封装,可以直接使用 Elastica 的 API 进行操作。

$client = $container->get('fos_elastica.client');
$index = $client->getIndex('app');
$type = $index->getType('user');

// 添加文档
$type->addDocument(new \Elastica\Document(1, ['username' => 'test', 'email' => 'test@example.com']));

// 搜索文档
$resultSet = $type->search('test');

3.2 Finder API

Finder 服务用于在 Elasticsearch 中查询数据。

$finder = $container->get('fos_elastica.finder.app.user');
$users = $finder->find('search query');

4. 项目安装方式

4.1 使用 Composer 安装

composer require friendsofsymfony/elastica-bundle

4.2 手动配置

如果未使用 Symfony Flex,需要手动配置 bundle 和 Elasticsearch 连接信息。

  1. config/bundles.php 中添加:

    FOS\ElasticaBundle\FOSElasticaBundle::class => ['all' => true],
    
  2. 配置 config/packages/fos_elastica.yaml 文件。

通过以上步骤,您可以成功安装并使用 FOSElasticaBundle 进行 Elasticsearch 的集成。

登录后查看全文
热门项目推荐