TNTSearch es un motor de búsqueda de texto completo (FTS) escrito íntegramente en PHP. Una configuración simple le permite agregar una experiencia de búsqueda increíble en solo minutos. Las características incluyen:
También creamos algunas páginas de demostración que muestran la recuperación tolerante con n-gramas en acción. El paquete tiene un montón de funciones auxiliares como Jaro-Winkler y similitud de coseno para cálculos de distancia. Admite derivaciones en inglés, croata, árabe, italiano, ruso, portugués y ucraniano. Si los tallos incorporados no son suficientes, el motor le permite conectar fácilmente cualquier tallo de bola de nieve compatible. Algunas bifurcaciones del paquete incluso admiten chino. ¡Y por favor contribuya en otros idiomas!
A diferencia de muchos otros motores, el índice se puede actualizar fácilmente sin necesidad de volver a indexar ni utilizar deltas.
Ver demostración en línea | Síguenos en Twitter o Facebook | Visita nuestros patrocinadores :
Si está utilizando TNT Search y lo encuentra útil, eche un vistazo a nuestra herramienta de análisis premium:
La forma más sencilla de instalar TNTSearch es mediante Composer:
composer require teamtnt/tntsearch
Antes de continuar, asegúrese de que su servidor cumpla con los siguientes requisitos:
Para poder realizar consultas de búsqueda de texto completo, debe crear un índice.
Uso:
use TeamTNT TNTSearch TNTSearch ;
$ tnt = new TNTSearch ;
$ tnt -> loadConfig ([
' driver ' => ' mysql ' ,
' host ' => ' localhost ' ,
' database ' => ' dbname ' ,
' username ' => ' user ' ,
' password ' => ' pass ' ,
' storage ' => ' /var/www/tntsearch/examples/ ' ,
' stemmer ' => TeamTNT TNTSearch Stemmer PorterStemmer ::class//optional
]);
$ indexer = $ tnt -> createIndex ( ' name.index ' );
$ indexer -> query ( ' SELECT id, article FROM articles; ' );
//$indexer->setLanguage('german');
$ indexer -> run ();
Importante: la configuración de "almacenamiento" marca la carpeta donde se guardarán todos sus índices, así que asegúrese de tener permiso para escribir en esta carpeta, de lo contrario, podría esperar que se produzca la siguiente excepción:
Nota: Si su clave principal es diferente a id
configúrela como:
$ indexer -> setPrimaryKey ( ' article_id ' );
De forma predeterminada, la clave principal no se puede buscar. Si desea que se pueda buscar, simplemente ejecute:
$ indexer -> includePrimaryKey ();
Buscar una frase o palabra clave es trivial:
use TeamTNT TNTSearch TNTSearch ;
$ tnt = new TNTSearch ;
$ tnt -> loadConfig ( $ config );
$ tnt -> selectIndex ( " name.index " );
$ res = $ tnt -> search ( " This is a test search " , 12 );
print_r ( $ res ); //returns an array of 12 document ids that best match your query
// to display the results you need an additional query against your application database
// SELECT * FROM articles WHERE id IN $res ORDER BY FIELD(id, $res);
La cláusula ORDER BY FIELD es importante; de lo contrario, el motor de la base de datos no devolverá los resultados en el orden requerido.
use TeamTNT TNTSearch TNTSearch ;
$ tnt = new TNTSearch ;
$ tnt -> loadConfig ( $ config );
$ tnt -> selectIndex ( " name.index " );
//this will return all documents that have romeo in it but not juliet
$ res = $ tnt -> searchBoolean ( " romeo -juliet " );
//returns all documents that have romeo or hamlet in it
$ res = $ tnt -> searchBoolean ( " romeo or hamlet " );
//returns all documents that have either romeo AND juliet or prince AND hamlet
$ res = $ tnt -> searchBoolean ( " (romeo juliet) or (prince hamlet) " );
La borrosidad se puede modificar configurando las siguientes variables miembro:
public $ fuzzy_prefix_length = 2 ;
public $ fuzzy_max_expansions = 50 ;
public $ fuzzy_distance = 2 ; //represents the Levenshtein distance;
use TeamTNT TNTSearch TNTSearch ;
$ tnt = new TNTSearch ;
$ tnt -> loadConfig ( $ config );
$ tnt -> selectIndex ( " name.index " );
$ tnt -> fuzziness ( true );
//when the fuzziness flag is set to true, the keyword juleit will return
//documents that match the word juliet, the default Levenshtein distance is 2
$ res = $ tnt -> search ( " juleit " );
Una vez que haya creado un índice, no necesita volver a indexarlo cada vez que realice algunos cambios en su colección de documentos. TNTSearch admite actualizaciones dinámicas de índice.
use TeamTNT TNTSearch TNTSearch ;
$ tnt = new TNTSearch ;
$ tnt -> loadConfig ( $ config );
$ tnt -> selectIndex ( " name.index " );
$ index = $ tnt -> getIndex ();
//to insert a new document to the index
$ index -> insert ([ ' id ' => ' 11 ' , ' title ' => ' new title ' , ' article ' => ' new article ' ]);
//to update an existing document
$ index -> update ( 11 , [ ' id ' => ' 11 ' , ' title ' => ' updated title ' , ' article ' => ' updated article ' ]);
//to delete the document from index
$ index -> delete ( 12 );
Primero, crea tu propia clase Tokenizer. Debe extender la clase AbstractTokenizer, definir el valor del patrón $ de división de palabras y debe implementar TokenizerInterface:
use TeamTNT TNTSearch Support AbstractTokenizer ;
use TeamTNT TNTSearch Support TokenizerInterface ;
class SomeTokenizer extends AbstractTokenizer implements TokenizerInterface
{
static protected $ pattern = ' /[s,.]+/ ' ;
public function tokenize ( $ text ) {
return preg_split ( $ this -> getPattern (), strtolower ( $ text ), - 1 , PREG_SPLIT_NO_EMPTY );
}
}
Este tokenizador dividirá palabras usando espacios, comas y puntos.
Una vez que tenga listo el tokenizador, debe pasarlo a TNTIndexer
mediante el método setTokenizer
.
$ someTokenizer = new SomeTokenizer ;
$ indexer = new TNTIndexer ;
$ indexer -> setTokenizer ( $ someTokenizer );
Otra forma sería pasar el tokenizador a través de la configuración:
use TeamTNT TNTSearch TNTSearch ;
$ tnt = new TNTSearch ;
$ tnt -> loadConfig ([
' driver ' => ' mysql ' ,
' host ' => ' localhost ' ,
' database ' => ' dbname ' ,
' username ' => ' user ' ,
' password ' => ' pass ' ,
' storage ' => ' /var/www/tntsearch/examples/ ' ,
' stemmer ' => TeamTNT TNTSearch Stemmer PorterStemmer ::class//optional,
' tokenizer ' => TeamTNT TNTSearch Support SomeTokenizer ::class
]);
$ indexer = $ tnt -> createIndex ( ' name.index ' );
$ indexer -> query ( ' SELECT id, article FROM articles; ' );
$ indexer -> run ();
$ candyShopIndexer = new TNTGeoIndexer ;
$ candyShopIndexer -> loadConfig ( $ config );
$ candyShopIndexer -> createIndex ( ' candyShops.index ' );
$ candyShopIndexer -> query ( ' SELECT id, longitude, latitude FROM candy_shops; ' );
$ candyShopIndexer -> run ();
$ currentLocation = [
' longitude ' => 11.576124 ,
' latitude ' => 48.137154
];
$ distance = 2 ; //km
$ candyShopIndex = new TNTGeoSearch ();
$ candyShopIndex -> loadConfig ( $ config );
$ candyShopIndex -> selectIndex ( ' candyShops.index ' );
$ candyShops = $ candyShopIndex -> findNearest ( $ currentLocation , $ distance , 10 );
use TeamTNT TNTSearch Classifier TNTClassifier ;
$ classifier = new TNTClassifier ();
$ classifier -> learn ( " A great game " , " Sports " );
$ classifier -> learn ( " The election was over " , " Not sports " );
$ classifier -> learn ( " Very clean match " , " Sports " );
$ classifier -> learn ( " A clean but forgettable game " , " Sports " );
$ guess = $ classifier -> predict ( " It was a close election " );
var_dump ( $ guess [ ' label ' ]); //returns "Not sports"
$ classifier -> save ( ' sports.cls ' );
$ classifier = new TNTClassifier ();
$ classifier -> load ( ' sports.cls ' );
Eres libre de utilizar este paquete, pero si llega a tu entorno de producción, te agradeceríamos mucho que nos enviaras un juego de PS4 de tu elección. De esta manera, nos apoya para seguir desarrollando y agregando nuevas funciones.
Nuestra dirección es: TNT Studio, Sv. Mateja 19, 10010 Zagreb, Croacia.
Publicaremos todos los juegos recibidos aquí.
Apóyanos con una donación mensual y ayúdanos a continuar con nuestras actividades. [Conviértete en patrocinador]
Conviértase en patrocinador y obtenga su logotipo en nuestro README en Github con un enlace a su sitio. [Conviértete en patrocinador]
La Licencia MIT (MIT). Consulte el archivo de licencia para obtener más información.
Desde Croacia con ♥ de TNT Studio (@tntstudiohr, blog)