Este paquete facilita el uso de capacidades de búsqueda de texto completo de PostgreSQL nativo con Laravel Scout.
Si encuentra útil este paquete, considere que me bese un café.
Puede instalar el paquete a través del compositor:
composer require pmatseykanets/laravel-scout-postgresSi está utilizando Laravel <5.5 o si tiene un paquete desactivado automático, debe registrar manualmente el proveedor de servicios:
// config/app.php
' providers ' => [
...
ScoutEngines Postgres PostgresEngineServiceProvider::class,
], El proveedor de servicios de Scout utiliza config_path helper que no está incluido en lumen. Para solucionar esto, incluya el siguiente fragmento directamente en bootstrap.app o en su archivo de ayudantes automatizado, es decir, 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 );
}
} Cree el archivo de configuración scout.php en la carpeta app/config con los siguientes contenidos
<?php
return [
' driver ' => env ( ' SCOUT_DRIVER ' , ' pgsql ' ),
' prefix ' => env ( ' SCOUT_PREFIX ' , '' ),
' queue ' => false ,
' pgsql ' => [
' connection ' => ' pgsql ' ,
' maintain_index ' => true ,
' config ' => ' english ' ,
],
];Registrar proveedores de servicios:
// bootstrap/app.php
$ app -> register ( Laravel Scout ScoutServiceProvider::class);
$ app -> configure ( ' scout ' );
$ app -> register ( ScoutEngines Postgres PostgresEngineServiceProvider::class); Especifique la conexión de la base de datos que debe usarse para acceder a documentos indexados en el archivo de configuración de 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 '
],
... Asegúrese de que una configuración de búsqueda de texto predeterminada apropiada se establezca GlobBaly (en postgresql.conf ), para una base de datos particular ( ALTER DATABASE ... SET default_text_search_config TO ... ) o alternativamente establecer default_text_search_config en cada sesión.
Para verificar el valor actual
SHOW default_text_search_config; De manera predeterminada, el motor espera que los documentos analizados (datos del modelo) se almacenen en la misma tabla que el modelo en una columna searchable de tipo tsvector . Debería crear esta columna y un índice en su esquema. Puede elegir entre los índices GIN y GiST en 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 ' );
}
}Además de los atributos del Modelo, puede traer otros datos al documento de índice. Es decir, una lista de etiquetas para una publicación.
public function toSearchableArray ()
{
return [
' title ' => $ this -> title ,
' content ' => $ this -> content ,
' author ' => $ this -> user -> name ,
' tags ' => $ this -> tags -> pluck ( ' tag ' )-> implode ( ' ' ),
];
} Puede ajustar el comportamiento del motor para un modelo particular implementando searchableOptions() en su 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 ' ,
];
}
}
. . . Si decide mantener el índice de su modelo fuera de la tabla del modelo, puede informar al motor que desea empujar campos adicionales en la tabla de índice que luego puede usar para filtrar el resultado establecido aplicando where() con el Builder de exploradores. En este caso, necesitaría implementar searchableAdditionalArray() en su modelo. Por supuesto, el esquema para la tabla externa debe incluir estas columnas adicionales.
public function searchableAdditionalArray ()
{
return [
' user_id ' => $ this -> user_id ,
];
}Es posible que desee ocultar su columna de búsqueda para que no se interponga en su camino
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 la documentación oficial sobre cómo usar Laravel Scout.
composer test Si descubre algún problema relacionado con la seguridad, envíe un correo electrónico a [email protected] en lugar de usar el rastreador de problemas.
Consulte ChangeLog para obtener más información lo que ha cambiado recientemente.
Consulte contribuyendo para obtener más detalles.
La licencia MIT (MIT). Consulte el archivo de licencia para obtener más información.