Este pacote facilita o uso de recursos nativos de pesquisa de texto completo do PostGresql com o Laravel Scout.
Se você achar este pacote útil, considere me por um café.
Você pode instalar o pacote via compositor:
composer require pmatseykanets/laravel-scout-postgresSe você estiver usando o Laravel <5.5 ou se tiver uma descoberta automática de pacotes desativada, precisará registrar manualmente o provedor de serviços:
// config/app.php
' providers ' => [
...
ScoutEngines Postgres PostgresEngineServiceProvider::class,
], O provedor de serviços de escoteiros usa config_path Helper que não está incluído no lúmen. Para corrigir isso, inclui o seguinte snippet diretamente no bootstrap.app ou no seu arquivo de auxiliares com automóveis com automóveis, ie app/helpers.php .
if (! function_exists ( ' config_path ' )) {
/**
* Get the configuration path.
*
* @param string $path
* @return string
*/
function config_path ( $ path = '' )
{
return app ()-> basePath () . ' /config ' .( $ path ? DIRECTORY_SEPARATOR . $ path : $ path );
}
} Crie o arquivo de configuração scout.php na pasta app/config com o seguinte conteúdo
<?php
return [
' driver ' => env ( ' SCOUT_DRIVER ' , ' pgsql ' ),
' prefix ' => env ( ' SCOUT_PREFIX ' , '' ),
' queue ' => false ,
' pgsql ' => [
' connection ' => ' pgsql ' ,
' maintain_index ' => true ,
' config ' => ' english ' ,
],
];Registrar provedores de serviços:
// bootstrap/app.php
$ app -> register ( Laravel Scout ScoutServiceProvider::class);
$ app -> configure ( ' scout ' );
$ app -> register ( ScoutEngines Postgres PostgresEngineServiceProvider::class); Especifique a conexão do banco de dados que deve ser usada para acessar documentos indexados no arquivo de configuração do Laravel Scout config/scout.php :
// config/scout.php
. . .
' pgsql ' => [
// Connection to use. See config/database.php
' connection ' => env ( ' DB_CONNECTION ' , ' pgsql ' ),
// You may want to update index documents directly in PostgreSQL (i.e. via triggers).
// In this case you can set this value to false.
' maintain_index ' => true ,
// You can explicitly specify what PostgreSQL text search config to use by scout.
// Use dF in psql to see all available configurations in your database.
' config ' => ' english ' ,
// You may set the default querying method
// Possible values: plainquery, phrasequery, tsquery
// plainquery is used if this option is omitted.
' search_using ' => ' tsquery '
],
... Verifique se uma configuração de pesquisa de texto padrão apropriada está definida GlobBaly (no postgresql.conf ), para um banco de dados específico ( ALTER DATABASE ... SET default_text_search_config TO ... ) ou defina alternativamente default_text_search_config em cada sessão.
Para verificar o valor atual
SHOW default_text_search_config; Por padrão, o mecanismo espera que os documentos analisados (dados do modelo) sejam armazenados na mesma tabela que o modelo em uma coluna searchable do tipo tsvector . Você precisaria criar esta coluna e um índice em seu esquema. Você pode escolher entre os índices GIN e GiST no PostgreSQL.
class CreatePostsTable extends Migration
{
public function up ()
{
Schema:: create ( ' posts ' , function ( Blueprint $ table ) {
$ table -> increments ( ' id ' );
$ table -> text ( ' title ' );
$ table -> text ( ' content ' )-> nullable ();
$ table -> integer ( ' user_id ' );
$ table -> timestamps ();
});
DB :: statement ( ' ALTER TABLE posts ADD searchable tsvector NULL ' );
DB :: statement ( ' CREATE INDEX posts_searchable_index ON posts USING GIN (searchable) ' );
// Or alternatively
// DB::statement('CREATE INDEX posts_searchable_index ON posts USING GIST (searchable)');
}
public function down ()
{
Schema:: drop ( ' posts ' );
}
}Além dos atributos do modelo, você pode trazer outros dados para o documento de índice. Ou seja, uma lista de tags para uma postagem.
public function toSearchableArray ()
{
return [
' title ' => $ this -> title ,
' content ' => $ this -> content ,
' author ' => $ this -> user -> name ,
' tags ' => $ this -> tags -> pluck ( ' tag ' )-> implode ( ' ' ),
];
} Você pode ajustar o comportamento do motor para um modelo específico, implementando searchableOptions() em seu modelo.
class Post extends Model
{
use Searchable;
// ...
public function searchableOptions ()
{
return [
// You may wish to change the default name of the column
// that holds parsed documents
' column ' => ' indexable ' ,
// You may want to store the index outside of the Model table
// In that case let the engine know by setting this parameter to true.
' external ' => true ,
// If you don't want scout to maintain the index for you
// You can turn it off either for a Model or globally
' maintain_index ' => true ,
// Ranking groups that will be assigned to fields
// when document is being parsed.
// Available groups: A, B, C and D.
' rank ' => [
' fields ' => [
' title ' => ' A ' ,
' content ' => ' B ' ,
' author ' => ' D ' ,
' tags ' => ' C ' ,
],
// Ranking weights for searches.
// [D-weight, C-weight, B-weight, A-weight].
// Default [0.1, 0.2, 0.4, 1.0].
' weights ' => [ 0.1 , 0.2 , 0.4 , 1.0 ],
// Ranking function [ts_rank | ts_rank_cd]. Default ts_rank.
' function ' => ' ts_rank_cd ' ,
// Normalization index. Default 0.
' normalization ' => 32 ,
],
// You can explicitly specify a PostgreSQL text search configuration for the model.
// Use dF in psql to see all available configurationsin your database.
' config ' => ' simple ' ,
];
}
}
. . . Se você decidir manter o índice do seu modelo fora da tabela do modelo, poderá informar o mecanismo de que deseja empurrar campos adicionais na tabela de índice que você pode usar para filtrar o conjunto de resultados aplicando where() com o Scout Builder . Nesse caso, você precisará implementar searchableAdditionalArray() em seu modelo. Obviamente, o esquema da tabela externa deve incluir essas colunas adicionais.
public function searchableAdditionalArray ()
{
return [
' user_id ' => $ this -> user_id ,
];
}Você pode querer deixar sua coluna pesquisável escondida para que não esteja no seu caminho
protected $ hidden = [
' searchable ' ,
]; // plainto_tsquery()
$ posts = App Post:: search ( ' cat rat ' )
-> usingPlainQuery ()->get()
// phraseto_tsquery()
$ posts = App Post:: search ( ' cat rat ' )
-> usingPhraseQuery ()->get()
// to_tsquery()
$ posts = App Post:: search ( ' fat & (cat | rat) ' )
-> usingTsQuery ()->get()
// websearch_to_tsquery()
// uses web search syntax
$ posts = App Post:: search ( ' "sad cat" or "fat rat" -mouse ' )
-> usingWebSearchQuery ()->get()
// DIY using a callback
use ScoutEngines Postgres TsQuery ToTsQuery ;
$ results = App Post:: search ( ' fat & (cat | rat) ' , function ( $ builder , $ config ) {
return new ToTsQuery ( $ builder -> query , $ config );
})-> get ();Consulte a documentação oficial sobre como usar o Laravel Scout.
composer test Se você descobrir algum problema relacionado à segurança, envie um email para [email protected] em vez de usar o rastreador de problemas.
Consulte Changelog para obter mais informações o que mudou recentemente.
Por favor, consulte a contribuição para obter detalhes.
A licença do MIT (MIT). Consulte o arquivo de licença para obter mais informações.