A search package for Laravel 5.

Overview

Search Package for Laravel 5

This package provides a unified API across a variety of different full text search services. It currently supports drivers for Elasticsearch, Algolia, and ZendSearch (good for local use).

Installation Via Composer

Add this to you composer.json file, in the require object:

"mmanos/laravel-search": "dev-master"

After that, run composer install to install the package.

Add the service provider to app/config/app.php, within the providers array.

'providers' => array(
	// ...
	'Mmanos\Search\SearchServiceProvider',
)

Add a class alias to app/config/app.php, within the aliases array.

'aliases' => array(
	// ...
	'Search' => 'Mmanos\Search\Facade',
)

Laravel 4

Use the 0.0 branch or the v0.* tags for Laravel 4 support.

Configuration

Publish the default config file to your application so you can make modifications.

$ php artisan vendor:publish

Dependencies

The following dependencies are needed for the listed search drivers:

  • ZendSearch: zendframework/zendsearch
  • Elasticsearch: elasticsearch/elasticsearch
  • Algolia: algolia/algoliasearch-client-php

Default Index

This package provides a convenient syntax for working with a "default" index. Edit the default_index field in the config file to change this value. If you need to work with more than one index, see Working With Multiple Indicies below.

Indexing Operations

Indexing is very easy with this package. Simply provide a unique identifier for the document and an associative array of fields to index.

The index will be created automatically if it does not exist the first time you access it.

Index A Document

Add a document to the "default" index with an id of "1".

Search::insert(1, array(
	'title' => 'My title',
	'content' => 'The quick brown fox...',
	'status' => 'published',
));

Note: id may be a string or an integer. This id is used to delete records and is also returned in search results.

Store Extra Parameters With A Document

You may store extra parameters with a document so they can be retrieved at a later point from search results. This can be useful for referencing timestamps or other record identifiers.

Search::insert(
	"post-1",
	array(
		'title' => 'My title',
		'content' => 'The quick brown fox...',
		'status' => 'published',
	),
	array(
		'created_at' => time(),
		'creator_id' => 5,
	)
);

Note: Extra parameters are not indexed but are stored in the index for future retrieval.

Delete A Document

Delete a document from the "default" index with an id of "1":

Search::delete(1);

Delete An Index

Search::deleteIndex();

Search Operations

Search For A Document

Search the "default" index for documents who's content field contains the word "fox":

$results = Search::search('content', 'fox')->get();

Search More Than One Field

$results = Search::search(array('title', 'content'), 'fox')->get();

Search All Fields

$results = Search::search(null, 'fox')->get();

Perform A Fuzzy Search

Perform a fuzzy search to find results with similar, but not exact, spelling. For example, you want to return documents containing the word "updates" by searching for the word "update":

$results = Search::search('content', 'update', array('fuzzy'=>true))->get();

Note: You may also pass a numeric value between 0 and 1 for the fuzzy parameter, where a value closer to 1 requires a higher similarity. Defaults to 0.5.

Apply A Filter To Your Query

You can apply filters to your search queries as well. Filters attempt to match the value you specify as an entire "phrase".

$results = Search::search('content', 'fox')
	->where('status', 'published')
	->get();

Note: Filters do not guarantee an exact match of the entire field value if the value contains multiple words.

Geo-Search

Some drivers support location-aware searching:

$results = Search::search('content', 'fox')
	->whereLocation(36.16781, -96.023561, 10000)
	->get();

Where the parameters are latitude, longitude, and distance (in meters).

Note: Currently, only the algolia driver supports geo-searching. Ensure each indexed record contains the location information: _geoloc => ['lat' => 1.23, 'lng' => 1.23].

Limit Your Result Set

$results = Search::search('content', 'fox')
	->where('status', 'published')
	->limit(10) // Limit 10
	->get();

$results = Search::search('content', 'fox')
	->where('status', 'published')
	->limit(10, 30) // Limit 10, offset 30
	->get();

Paginate Your Result Set

You can also paginate your result set using a Laravel paginator instance.

$paginator = Search::search('content', 'fox')->paginate(15);

Limit The Fields You Want Back From The Response

$results = Search::select('id', 'created_at')
	->search('content', 'fox')
	->get();

Chain Multiple Searches And Filters

$results = Search::select('id', 'created_at')
	->where('title', 'My title')
	->where('status', 'published')
	->search('content', 'fox')
	->search('content', 'quick')
	->limit(10)
	->get();

Note: Chained filters/searches are constructed as boolean queries where each must provide a match.

Delete All Documents That Match A Query

Search::search('content', 'fox')->delete();

Working With Multiple Indicies

If you need to work with more than one index, you may access all of the same methods mentioned above after you specify the index name.

Add a document to an index called "posts":

Search::index('posts')->insert(1, array(
	'title' => 'My title',
	'content' => 'The quick brown fox...',
	'status' => 'published',
));

Search the "posts" index for documents who's content field contains the word "fox" and who's status is "published":

$results = Search::index('posts')->search('content', 'fox')
	->where('status', 'published')
	->get();

Delete a document from the "posts" index with an id of "1":

Search::index('posts')->delete(1);

Delete the entire "posts" index:

Search::index('posts')->deleteIndex();

Advanced Query Callbacks

If you need more control over a search query you may add a callback function which will be called after all conditions have been added to the query but before the query has been executed. You can then make changes to the native query instance and return it to be executed.

$results = Search::index('posts')->select('id', 'created_at')
	->search('content', 'fox')
	->addCallback(function ($query) {
		// Make changes to $query...
		return $query;
	})
	->get();

Since each driver has it's own native $query object/array, you may only want to execute your callback for one of the drivers:

$results = Search::index('posts')->select('id', 'created_at')
	->search('content', 'fox')
	->addCallback(function ($query) {
		// Adjust pagination for an elasticsearch query array.
		$query['from'] = 0;
		$query['size'] = 20;
		return $query;
	}, 'elasticsearch')
	->get();

Note: You may also pass an array of drivers as the second parameter.

Comments
  • Error in Laravel 4.2.17 - base64_decode() expects parameter 1 to be string, array given

    Error in Laravel 4.2.17 - base64_decode() expects parameter 1 to be string, array given

    Hi,

    When I run the following line on my index:

    $results = Search::index('acpdata')->search('campaign_id', 272)->get();

    I get this error:

    base64_decode() expects parameter 1 to be string, array given

    Error is @ line 190 of file /vendor/mmanos/laravel-search/src/Mmanos/Search/Index/Elasticsearch.php

    json_decode(base64_decode(array_get($hit, '_source._parameters', array())), true)

    Help!

    Regards

    opened by hmpmarketing 6
  • Elasticsearch not working

    Elasticsearch not working

    Error thrown when indexing:

    Argument 1 passed to Elasticsearch\Client::__construct() must be an instance of Elasticsearch\Transport, array given

    I have installed elasticsearch/elasticsearch (v2.1.3)

    Please look into this matter

    opened by hetunandu 4
  • Laravel 5.1 error

    Laravel 5.1 error

    Hi,

    I have some issue with Laravel 5.1.

    When I call the facade Search::search() for example, I have an error:

    Call to undefined method Mmanos\Search\Search::methodName

    It's me or your package is not compatible with Laravel 5.1 ?

    With IoC I have no error but the result is an empty array.

    Thx

    opened by rtransat 2
  • Delete index doesn't delete

    Delete index doesn't delete

    Hey,

    Firstly, thanks for this package - Awesome.

    I have created a few indexes and in an attempt to build the management side of things, I have found that I can't delete an individual index: Search::index('users')->deleteIndex();

    If I then search for a result, it seems the index still exists. If I then: curl -XDELETE 'http://localhost:9200/users/' And repeat the search, the index has been deleted.

    In this case I am using ElasticSearch.

    I'll take a look to see if I can figure out what is going wrong here. In the meantime, if you can point me in the right direction, that would be awesome.

    Cheers.

    opened by t2thec 2
  • Added where null method to query to match null values

    Added where null method to query to match null values

    This adds a whereNull() method to query class similar to Eloquent has which will match null values across all search drivers since a simple Search::where('field', null) will not work with search drivers with complex data type support such arrays.

    opened by dmyers 1
  • Zend adapter - fuzzy search bug

    Zend adapter - fuzzy search bug

    ~ modifier must follow word or phrase Fuzzy search is supported only for non-multiple word terms Eg: If search terms contain a dash (-).

    Would be nice if the package could escape search queries automatically.

    opened by dmyers 1
  • Changed elastic search driver to return stored fields with results

    Changed elastic search driver to return stored fields with results

    In ElasticSearch, by default fields are stored in the index and returned with hits and now they will be returned with the results and match the latest change to the Zend driver.

    opened by dmyers 0
  • Added location support to elasticsearch driver using using geopoint

    Added location support to elasticsearch driver using using geopoint

    Only thing I'm having trouble with is chaining search(), where(), and whereLocation() conditions at the same time.

    In order to get this to work you have to create an index like so:

    $fields = [
        'name' => $name,
        '_geoloc' => [
            'lat' => $lat,
            'lon' => $long,
        ],
    ];
    
    \Search::insert($id, $fields);
    
    opened by dmyers 0
  • Added ability to get query instance for an index without a condition

    Added ability to get query instance for an index without a condition

    This lets you chain conditions better in a controller.

    $users = Search::query();
    
    if ($condition) {
        $users->where('key', $value);
    }
    
    if ($condition) {
        $users->whereLocation($lat, $long);
    }
    
    opened by dmyers 0
  • array_merge(): Argument #2 is not an array

    array_merge(): Argument #2 is not an array

    Hi, I am using zend search and I am getting issue while running the search documents. There is an issue in array_merge and it is occur because of json_decode(base64_decode($hit->_parameters), true) is null. I checked and $hit->_parameters returns "" and I am not sure why you try to array_merge. I am going to remove this line and is it okay? Please answer my question asap. Thanks

    mmanos/laravel-search/src/mmanos/search/index/zend.php

    public function runQuery($query, array $options = array())
    	{
            $response = $this->getIndex()->find($query);
    		$this->stored_query_totals[md5(serialize($query))] = count($response);
    
    		$results = array();
    
    		if (!empty($response)) {
    			foreach ($response as $hit) {
    				$fields = array(
    						'id'     => $hit->xref_id,
    						'_score' => $hit->score,
    				);
    				
    				foreach ($hit->getDocument()->getFieldNames() as $name) {
    					if ($name == 'xref_id') continue;
    					
    					$fields[$name] = $hit->getDocument()->getFieldValue($name);
    				}
    				
    				$results[] = array_merge(
    					$fields,
    					json_decode(base64_decode($hit->_parameters), true)
    				);
    			}
    		}
    		
    		if (isset($options['limit']) && isset($options['offset'])) {
    			$results = array_slice($results, $options['offset'], $options['limit']);
    		}
    		
    		return $results;
    	}
    
    opened by lee-corey 0
  • Error when using fuzzy search

    Error when using fuzzy search

    Hi,

    I'm trying to use fuzzy search, but i'm getting an error:

    {"error":{"root_cause":[{"type":"query_parsing_exception","reason":"No query registered for [fuzzy_like_this]","index":"default","line":1,"col":67}],"type":"search_phase_execution_exception","reason":"all shards failed","phase":"query","grouped":true,"failed_shards":[{"shard":0,"index":"default","node":"hcsfsArwQ9OwOkw0Wrt5TQ","reason":{"type":"query_parsing_exception","reason":"No query registered for [fuzzy_like_this]","index":"default","line":1,"col":67}}]},"status":400}" on line 239 of /vendor/elasticsearch/elasticsearch/src/Elasticsearch/Connections/GuzzleConnection.php

    I used this code:

    $results = ESearch::search(array('question','keywords'), $question,array('phrase'=>true,'fuzzy'=>1)) ->where('status', 'published') ->get();

    When removing fuzzy, the search query is giving me results. I'm using Elasticsearch 1.0.

    opened by Roywcm 0
  • Error when use

    Error when use

    Hi everyone , When i use : \Search::insert(1, array( 'title' => 'My title', 'content' => 'The quick brown fox...', 'status' => 'published', )); My app show error : Argument 1 passed to Elasticsearch\Client::__construct() must be an instance of Elasticsearch\Transport, array given, called in ..../vendor/mmanos/laravel-search/src/Mmanos/Search/Index/Elasticsearch.php on line 38 and defined Please help me ! Thanks

    opened by thantai574 4
  • Call to undefined method Mmanos\Search\Search::insert()

    Call to undefined method Mmanos\Search\Search::insert()

    Hello, thank you for the package. Please guide me on how to index my Models with this package and output the results. When trying to run it, I am getting the following errors

    Whoops, looks like something went wrong.

    1/1 FatalErrorException in API.php line 118: Call to undefined method Mmanos\Search\Search::insert()
            </h2>
            <div class="block">
                <ol class="traces list_exception">
                    <li> in 
                        <a title="C:\xampp\htdocs\event\app\Http\Controllers\API.php line 118" ondblclick="var f=this.innerHTML;this.innerHTML=this.title;this.title=f;">API.php line 118</a>
                    </li>
    
                </ol>
            </div>
    

    opened by kevosomi 5
Releases(v1.0.5)
Owner
Mark Manos
Mark Manos
Driver for Laravel Scout search package based on https://github.com/teamtnt/tntsearch

TNTSearch Driver for Laravel Scout - Laravel 5.3 - 8.0 This package makes it easy to add full text search support to your models with Laravel 5.3 to 8

TNT Studio 1k Dec 27, 2022
Laravel package to search through multiple Eloquent models. Supports sorting, pagination, scoped queries, eager load relationships and searching through single or multiple columns.

Laravel Cross Eloquent Search This Laravel package allows you to search through multiple Eloquent models. It supports sorting, pagination, scoped quer

Protone Media 844 Dec 25, 2022
Laravel Searchable - This package makes it easy to get structured search from a variety of sources

This package makes it easy to get structured search from a variety of sources. Here's an example where we search through some model

Spatie 1.1k Dec 31, 2022
SphinxQL Query Builder generates SphinxQL, a SQL dialect, which is used to query the Sphinx search engine. (Composer Package)

Query Builder for SphinxQL About This is a SphinxQL Query Builder used to work with SphinxQL, a SQL dialect used with the Sphinx search engine and it'

FoolCode 318 Oct 21, 2022
A php trait to search laravel models

Searchable, a search trait for Laravel Searchable is a trait for Laravel 4.2+ and Laravel 5.0 that adds a simple search function to Eloquent Models. S

Nicolás López Jullian 2k Dec 27, 2022
Unmaintained: Laravel Searchy makes user driven searching easy with fuzzy search, basic string matching and more to come!

!! UNMAINTAINED !! This package is no longer maintained Please see Issue #117 Here are some links to alternatives that you may be able to use (I do no

Tom Lingham 533 Nov 25, 2022
Search among multiple models with ElasticSearch and Laravel Scout

For PHP8 support use php8 branch For Laravel Framework < 6.0.0 use 3.x branch The package provides the perfect starting point to integrate ElasticSear

Sergey Shlyakhov 592 Dec 25, 2022
This is an open source demo of smart search feature implemented with Laravel and Selectize plugin

Laravel smart search implementation See demo at: http://demos.maxoffsky.com/shop-search/ Tutorial at: http://maxoffsky.com/code-blog/laravel-shop-tuto

Maksim Surguy 215 Sep 8, 2022
A fully featured full text search engine written in PHP

TNTSearch TNTSearch is a full-text search (FTS) engine written entirely in PHP. A simple configuration allows you to add an amazing search experience

TNT Studio 2.9k Jan 8, 2023
Sphinx Search library provides SphinxQL indexing and searching features

Sphinx Search Sphinx Search library provides SphinxQL indexing and searching features. Introduction Installation Configuration (simple) Usage Search I

Ripa Club 62 Mar 14, 2022
Kirby docs search workflow for Alfred

Kirby Docs search workflow for Alfred 4 An ultra-fast Kirby Docs search workflow for Alfred 4 Installation Download the latest version Install the wor

Adam Kiss 30 Dec 29, 2022
Build and execute an Elasticsearch search query using a fluent PHP API

PACKAGE IN DEVELOPMENT, DO NOT USE YET Build and execute ElasticSearch queries using a fluent PHP API This package is a lightweight query builder for

Spatie 94 Dec 14, 2022
A TYPO3 extension that integrates the Apache Solr search server with TYPO3 CMS. dkd Internet Service GmbH is developing the extension. Community contributions are welcome. See CONTRIBUTING.md for details.

Apache Solr for TYPO3 CMS A TYPO3 extension that integrates the Apache Solr enterprise search server with TYPO3 CMS. The extension has initially been

Apache Solr for TYPO3 126 Dec 7, 2022
A site search engine

THIS PACKAGE IS IN DEVELOPMENT, DO NOT USE IN PRODUCTION YET A site search engine This package can crawl your entire site and index it. Support us We

Spatie 219 Nov 8, 2022
Support search in flarum by sonic

flarum-sonic Support search by Sonic Install Sonic following this guide Install the extension: composer require ganuonglachanh/sonic Change info in a

null 18 Dec 21, 2022
Your personal job-search assistant

JobsToMail Your personal job-search assistant About JobsToMail is an open source web application that allows users to sign up to receive emails with j

JobApis 93 Nov 13, 2022
This modules provides a Search API Backend for Elasticsearch.

Search API ElasticSearch This modules provides a Search API Backend for Elasticsearch. This module uses the official Elasticsearch PHP Client. Feature

null 1 Jan 20, 2022
Search products, categories, brands or tags with ElasticSearch

ElasticSearch for Shopaholic This plugin allows you to use ElasticSearch as search engine for Shopaholic. Benefits Easy to install, easy to use Opened

Biz-Mark 4 Feb 18, 2022
Illusionist Searcher - Generates database queries based on search syntax

Illusionist Searcher Generates database queries based on search syntax. English | 中文 ✨ Features Zero configuration Compatible with laravel/scout and l

A doer with magic 2 Feb 24, 2022