Skip to content
Clémentine Urquizar edited this page Jan 14, 2021 · 20 revisions

⚠️ This page is not up-to-date, please don't use it to develop your project with meilisearch-php.

Usage

The search method returns a SearchResult instance.

public function search($query, array $searchParams = [], array $options = [])

$query: the query words.

$searchParams: the search parameters handled by MeiliSearch.

$options: options you can pass during the search. There are described in the next section.

Options

Here are the different options you can pass in the $options parameter.

  • raw (default: false): to get the raw results returned by MeiliSearch. The search() will return an array instead of a class instance.
$index->search('prince', $options = [ raw => true ]);
  • removeZeroFacets (default: false): to get the raw results returned by MeiliSearch. The search() will return an array instead of a class instance.
$index->search('prince', $options = [ removeZeroFacets => true ]);

// With removeZeroFacets = false
// "facet": {
//   "genre": {
//     "horror: 443,
//     "thriller": 200,
//     "comedy": 0
//   }
// }

// With removeZeroFacets = true
// "facet": {
//   "genre": {
//     "horror: 443,
//     "thriller": 200,
//   }
// }
  • transformHits: the callback that will be applied to the hits array returned by MeiliSearch.
$index->search('prince', [], [
    'transformHits' => function (array $hit) {
        $hit['title'] = strtoupper($hit['title']);
        return $hit;
    },
]);
// Before PHP 7.4
function titlesToUpperCase(array $hits) {
    return array_map($hits, function (array $hit) {
        $hit['title'] = strtoupper($hit['title']);
        return $hit;
    }
}

// PHP 7.4 and later
function titlesToUpperCase(array $hits) {
    return array_map($hits, function (array $hit) {
        return [
            ...$hit,
            title: strtoupper($hit['title']
        ]
    }
}

$index->search('prince', $options = [ 'transformHits' => 'titlesToUpperCase' ])
  • customizeFacetsDistribution (WIP): the callback that will be applied to the facetsDistribution array returned by MeiliSearch.

Examples

  • To remove some specifics hits in the results:
$response = $index->search('prince', [], [
    'transformHits' => function (array $hit) {
        if ('AMERICAN SNIPER' === $hit['title']) {
            return $hit;
        }
    },
]);
  • To make the title in upercase:
$index->search('prince', [], [
    'transformHits' => function (array $hit) {
        $hit['title'] = strtoupper($hit['title']);
        return $hit;
    },
]);

Filters

With filters, both single and double quotes are supported.

// Enclosing with double quotes
$index->search('prince', ['filters' => "title = 'Le Petit Prince' OR author = 'J. R. R. Tolkien'"]);

// Enclosing with single quotes
$index->search('hobbit', ['filters' => 'title = "The Hitchhiker\'s Guide to the Galaxy" OR author = "J. R. R. Tolkien"']);
Clone this wiki locally