{"id":19621622,"url":"https://github.com/pkg6/think-scout","last_synced_at":"2025-04-23T21:22:16.714Z","repository":{"id":57080379,"uuid":"488796505","full_name":"pkg6/think-scout","owner":"pkg6","description":"Thinkphp Scout provides a driver based solution to searching your Eloquent models. Inspired By Laravel Scout.","archived":false,"fork":false,"pushed_at":"2023-08-08T03:42:41.000Z","size":17,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-03-30T03:41:11.874Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pkg6.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-05-05T01:40:39.000Z","updated_at":"2025-01-08T08:35:50.000Z","dependencies_parsed_at":"2024-11-11T11:26:39.116Z","dependency_job_id":"b947db40-1839-46f7-9c03-b53cc19fed3c","html_url":"https://github.com/pkg6/think-scout","commit_stats":{"total_commits":2,"total_committers":1,"mean_commits":2.0,"dds":0.0,"last_synced_commit":"aff7a62ddb19f9841721f2fb4828e0ad1bdefa5f"},"previous_names":["tp5er/think-scouts"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pkg6%2Fthink-scout","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pkg6%2Fthink-scout/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pkg6%2Fthink-scout/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pkg6%2Fthink-scout/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pkg6","download_url":"https://codeload.github.com/pkg6/think-scout/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250515326,"owners_count":21443371,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-11T11:23:45.499Z","updated_at":"2025-04-23T21:22:16.696Z","avatar_url":"https://github.com/pkg6.png","language":"PHP","readme":"前言\n\n\u003e [tp5er/think-scout](https://github.com/tp5er/think-scouts)根据thinkphp设计思想参考[laravel/scout](https://github.com/laravel/scout)进行扩展\n\ntp5er/think-scout 为模型的全文搜索提供了一个简单的、基于驱动程序的解决方案。\n\n目前，Scout 自带了一个 Elasticsearch 驱动；而编写自定义驱动程序很简单，你可以自由地使用自己的搜索实现来扩展 Scout。\n\n\n\n## 命令行使用\n\n~~~\n//创建模型索引\nphp think scout:index \"app\\\\model\\\\User\"\n//删除模型的索引\nphp think scout:delete-index \"app\\\\model\\\\User\"\n//分批将模型中的数据同步到引擎中\nphp think scout:import \"app\\\\model\\\\User\"\n//清空引擎中的数据（危险操作慎重使用）\nphp think scout:flush \"app\\\\model\\\\User\"\n~~~\n\n## Scout事件\n\n| 事件               | 描述                  | 事件使用方法名                                    |\n| ------------------ | --------------------- | ------------------------------------------------- |\n| onScoutUpdated     | 注册模型新增/更新事件 | Event::trigger('onScoutUpdated', User::find(1));  |\n| onScoutDeleted     | 注册模型删除事件      | Event::trigger('onScoutDeleted', User::find(1));  |\n| onScoutImported    | 注册模型全量新增/更新 | Event::trigger('onScoutImported', new User());    |\n| onScoutFlushed     | 注册模型全量删除数据  | Event::trigger('onScoutFlushed', new User());     |\n| onScoutCreateIndex | 注册模型索引创建      | Event::trigger('onScoutCreateIndex', new User()); |\n| onScoutDeleteIndex | 注册模型索引删除      | Event::trigger('onScoutDeleteIndex', new User()); |\n\n## 模型事件\n\n\u003e 官网参考地址：https://www.kancloud.cn/manual/thinkphp6_0/1037598\n\n| 事件           | 描述   | 事件方法名      |\n| :------------- | :----- | :-------------- |\n| after_read     | 查询后 | onAfterRead     |\n| before_insert  | 新增前 | onBeforeInsert  |\n| after_insert   | 新增后 | onAfterInsert   |\n| before_update  | 更新前 | onBeforeUpdate  |\n| after_update   | 更新后 | onAfterUpdate   |\n| before_write   | 写入前 | onBeforeWrite   |\n| after_write    | 写入后 | onAfterWrite    |\n| before_delete  | 删除前 | onBeforeDelete  |\n| after_delete   | 删除后 | onAfterDelete   |\n| before_restore | 恢复前 | onBeforeRestore |\n| after_restore  | 恢复后 | onAfterRestore  |\n\n## 注册Scout事件到模型事件中\n\n\u003e 如果需要通过模型事件来自动完成Scout数据增量同步到引擎中需要进行手动注册\n\u003e\n\u003e 重要事情说三遍：\n\u003e\n\u003e 手动注册Scout事件到模型事件中！\n\u003e\n\u003e 手动注册Scout事件到模型事件中！\n\u003e\n\u003e 手动注册Scout事件到模型事件中！\n\n### 手动依次注册\n\n\u003e 最佳的方式是使用队列\n\n~~~\n\u003c?php\ndeclare (strict_types = 1);\nnamespace app\\model;\nuse think\\Model;\nuse tp5er\\think\\scout\\Searchable;\nuse think\\facade\\Event;\nuse tp5er\\think\\scout\\DataSync;\n/**\n * @mixin \\think\\Model\n */\nclass User extends Model\n{\n    use Searchable;\n    \n    public static function onAfterDelete(Model $model)\n    {\n       // Event::trigger('onScoutDeleted', $model);\n       // 或\n       // (new DataSync($model))-\u003echunkDeleted(1);\n       \n    }\n\n    public static function onAfterWrite(Model $model)\n    {\n       // Event::trigger('onScoutUpdated', $model);\n       // 或\n       // (new DataSync($model))-\u003echunkUpdated(1);\n    }\n}\n~~~\n\n## 安装\n\n引入组件包和 Elasticsearch 驱动\n\n~~~\ncomposer require tp5er/think-scout\n// 根据自己的elasticsearch版本进行安装\ncomposer require elasticsearch/elasticsearch\n~~~\n\n最后，在你要做搜索的模型中添加`tp5er\\think\\scout\\Searchable` trait。这个 trait 会注册一个模型观察者来保持模型和所有驱动的同步：\n\n```\n\u003c?php\ndeclare (strict_types = 1);\nnamespace app\\model;\nuse think\\Model;\nuse tp5er\\think\\scout\\Searchable;\n\n/**\n * @mixin \\think\\Model\n */\nclass User extends Model\n{\n    use Searchable;\n}\n```\n\n## 配置文件`config/scout.php`\n\n~~~\n\u003c?php\n\nreturn [\n    /**\n     * Default Search Engine\n     * Supported:  \"collection\", \"null\" \"elastic\"\n     */\n    'default'     =\u003e env('SCOUT_DRIVER', 'collection'),\n    //Soft Deletes\n    'soft_delete' =\u003e false,\n    //分块处理数据\n    'chunk'       =\u003e 20,\n    //engine Configuration\n    'engine'      =\u003e [\n        'collection' =\u003e [\n            'driver' =\u003e \\tp5er\\think\\scout\\Engines\\CollectionEngine::class,\n        ],\n        'null'       =\u003e [\n            'driver' =\u003e \\tp5er\\think\\scout\\Engines\\NullEngine::class,\n        ],\n        'elastic'    =\u003e [\n            'driver' =\u003e \\tp5er\\think\\scout\\Engines\\ElasticEngine::class,\n            'prefix' =\u003e '',\n            //https://www.elastic.co/guide/cn/elasticsearch/php/current/_configuration.html\n            'hosts'  =\u003e [\n                [\n                    'host'   =\u003e 'localhost',\n                    'port'   =\u003e \"9200\",\n                    'scheme' =\u003e null,\n                    'user'   =\u003e null,\n                    'pass'   =\u003e null,\n                ],\n            ],\n        ]\n    ],\n];\n~~~\n\n## 配置模型索引\n\n每个模型与给定的搜索「索引」同步，这个「索引」包含该模型的所有可搜索记录。换句话说，你可以把每一个「索引」设想为一张 MySQL\n数据表。默认情况下，每个模型都会被持久化到与模型的「表」名（通常是模型名称的复数形式）相匹配的索引。你也可以通过覆盖模型上的 searchableAs 方法来自定义模型的索引：\n\n~~~\n\u003c?php\ndeclare (strict_types = 1);\nnamespace app\\model;\nuse think\\Model;\nuse tp5er\\think\\scout\\Searchable;\n\n/**\n * @mixin \\think\\Model\n */\nclass User extends Model\n{\n    use Searchable;\n    \n    /**\n     * Get the index name for the model.\n     *\n     * @return string\n     */\n    public function searchableAs()\n    {\n        return $this-\u003egetTable();\n    }\n}\n~~~\n\n## 暂停索引\n\n~~~\n\u003c?php\ndeclare (strict_types = 1);\nnamespace app\\model;\nuse think\\Model;\nuse tp5er\\think\\scout\\Searchable;\n\n/**\n * @mixin \\think\\Model\n */\nclass User extends Model\n{\n    use Searchable;\n    \n    /**\n     * Determine if the model should be searchable.\n     *\n     * @return bool\n     */\n    public function shouldBeSearchable()\n    {\n        return true;\n    }\n}\n~~~\n\n## 搜索\n\n你可以使用 search 方法来搜索模型。search 方法接受一个用于搜索模型的字符串。你还需在搜索查询上链式调用 get 方法，才能用给定的搜索语句查询与之匹配的模型模型：\n\n~~~\nUser::search()-\u003eget();\n~~~\n\n如果你想在它们返回模型模型前得到原结果，你应该使用`raw` 方法:\n\n```\nUser::search()-\u003eraw();\n```\n\n搜索查询通常会在模型的 searchableAs 方法指定的索引上执行。当然，你也可以使用 within 方法指定应该搜索的自定义索引:\n\n~~~\nUser::search()-\u003ewithin('tp5er_user')-\u003eget();\n~~~\n\n### Where 语句\n\nScout 允许你在搜索查询中增加简单的「where」语句。目前，这些语句只支持基本的数值等式检查，并且主要是用于根据拥有者的 ID 进行的范围搜索查询。由于搜索索引不是关系型数据库，因此当前不支持更高级的「where」语句：\n\n~~~\nUser::search()-\u003ewhere('user_id', 1)-\u003eget();\n~~~\n\n### 分页\n\n除了检索模型的集合，你也可以使用 paginate 方法对搜索结果进行分页。这个方法会返回一个就像 传统的模型查询分页 一样的 Paginator 实例：\n\n~~~\nUser::search()-\u003epaginate();\n~~~\n\n你可以通过将数量作为第一个参数传递给 paginate 方法来指定每页检索多少个模型：\n\n~~~\nUser::search()-\u003epaginate(15);\n~~~\n\n## 自定义引擎\n\n如果内置的 Scout 搜索引擎不能满足你的需求，你可以写自定义的引擎并且将它注册到 Scout。你的引擎需要继承 `tp5er\\think\\scout\\Engine` 抽象类，这个抽象类包含了你自定义的引擎必须要实现的十种抽象方法：\n\n~~~\nabstract public function update(Collection $models): void;\nabstract public function delete(Collection $models): void;\nabstract public function search(Builder $builder);\nabstract public function paginate(Builder $builder, int $perPage, int $page);\nabstract public function mapIds($results): Collection;\nabstract public function map(Builder $builder, $results, Model $model): Collection;\nabstract public function getTotalCount($results): int;\nabstract public function flush(Model $model): void;\n~~~\n\n### 注册引擎\n\n一旦你写好了自定义引擎，您就可以在配置文件中指定引擎了。举个例子，如果你写好了一个 MySqlSearchEngine，您就可以在配置文件中这样写：\n\n~~~\n\u003c?php\n\nreturn [\n    'default'     =\u003e env('SCOUT_DRIVER', 'mysql'),\n    'soft_delete' =\u003e false,\n    'engine'      =\u003e [\n        'mysql'         =\u003e [\n            'driver' =\u003e MySqlSearchEngine::class,\n            'prefix' =\u003e '',\n        ]\n    ],\n];\n~~~\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpkg6%2Fthink-scout","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpkg6%2Fthink-scout","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpkg6%2Fthink-scout/lists"}