• Stars
    star
    131
  • Rank 275,867 (Top 6 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 3 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Laravel Scout Driver for Typesense

This package makes it easy to add full text search support to your models with Laravel 7.* to 10.*.

Contents

Installation

The Typesense PHP SDK uses httplug to interface with various PHP HTTP libraries through a single API.

First, install the correct httplug adapter based on your guzzlehttp/guzzle version. For example, if you're on Laravel 8, which includes Guzzle 7, then run this:

composer require php-http/guzzle7-adapter

Then install the driver:

composer require typesense/laravel-scout-typesense-driver

And add the service provider:

// config/app.php
'providers' => [
    // ...
    Typesense\LaravelTypesense\TypesenseServiceProvider::class,
],

Ensure you have Laravel Scout as a provider too otherwise you will get an "unresolvable dependency" error

// config/app.php
'providers' => [
    // ...
    Laravel\Scout\ScoutServiceProvider::class,
],

Add SCOUT_DRIVER=typesense to your .env file

Then you should publish scout.php configuration file to your config directory

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

In your config/scout.php add:

'typesense' => [
    'api_key'         => 'abcd',
    'nodes'           => [
      [
        'host'     => 'localhost',
        'port'     => '8108',
        'path'     => '',
        'protocol' => 'http',
      ],
    ],
    'nearest_node'    => [
        'host'     => 'localhost',
        'port'     => '8108',
        'path'     => '',
        'protocol' => 'http',
    ],
    'connection_timeout_seconds'   => 2,
    'healthcheck_interval_seconds' => 30,    
    'num_retries'                  => 3,
    'retry_interval_seconds'       => 1,
  ],

Usage

If you are unfamiliar with Laravel Scout, we suggest reading it's documentation first.

After you have installed scout and the Typesense driver, you need to add the Searchable trait to your models that you want to make searchable. Additionaly, define the fields you want to make searchable by defining the toSearchableArray method on the model and implement TypesenseSearch:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Typesense\LaravelTypesense\Interfaces\TypesenseDocument;
use Laravel\Scout\Searchable;

class Todo extends Model implements TypesenseDocument
{
    use Searchable;
    
     /**
     * Get the indexable data array for the model.
     *
     * @return array
     */
    public function toSearchableArray()
    {
        return array_merge(
            $this->toArray(), 
            [
                // Cast id to string and turn created_at into an int32 timestamp
                // in order to maintain compatibility with the Typesense index definition below
                'id' => (string) $this->id,
                'created_at' => $this->created_at->timestamp,
            ]
        );
    }

     /**
     * The Typesense schema to be created.
     *
     * @return array
     */
    public function getCollectionSchema(): array {
        return [
            'name' => $this->searchableAs(),
            'fields' => [
                [
                    'name' => 'id',
                    'type' => 'string',
                ],
                [
                    'name' => 'name',
                    'type' => 'string',
                ],
                [
                    'name' => 'created_at',
                    'type' => 'int64',
                ],
            ],
            'default_sorting_field' => 'created_at',
        ];
    }

     /**
     * The fields to be queried against. See https://typesense.org/docs/0.24.0/api/search.html.
     *
     * @return array
     */
    public function typesenseQueryBy(): array {
        return [
            'name',
        ];
    }    
}

Then, sync the data with the search service like:

php artisan scout:import App\\Models\\Todo

After that you can search your models with:

Todo::search('Test')->get();

Adding via Query

The searchable() method will chunk the results of the query and add the records to your search index. Examples:

$todo = Todo::find(1);
$todo->searchable();

$todos = Todo::where('created_at', '<', now())->get();
$todos->searchable();

Multi Search

You can send multiple search requests in a single HTTP request, using the Multi-Search feature.

$searchRequests = [
    [
      'collection' => 'todo',
      'q' => 'todo'
    ],
    [
      'collection' => 'todo',
      'q' => 'foo'
    ]
];

Todo::search('')->searchMulti($searchRequests)->paginateRaw();

Generate Scoped Search Key

You can generate scoped search API keys that have embedded search parameters in them. This is useful in a few different scenarios:

  1. You can index data from multiple users/customers in a single Typesense collection (aka multi-tenancy) and create scoped search keys with embedded filter_by parameters that only allow users access to their own subset of data.
  2. You can embed any search parameters (for eg: exclude_fields or limit_hits) to prevent users from being able to modify it client-side.

When you use these scoped search keys in a search API call, the parameters you embedded in them will be automatically applied by Typesense and users will not be able to override them.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
use Typesense\LaravelTypesense\Concerns\HasScopedApiKey;
use Typesense\LaravelTypesense\Interfaces\TypesenseDocument;

class Todo extends Model implements TypesenseDocument
{
    use Searchable, HasScopedApiKey;
}

Usage

Todo::setScopedApiKey('xyz')->search('todo')->get();

Migrating from devloopsnet/laravel-typesense

  • Replace devloopsnet/laravel-typesense in your composer.json requirements with typesense/laravel-scout-typesense-driver
  • The Scout driver is now called typesense, instead of typesensesearch. This should be reflected by setting the SCOUT_DRIVER env var to typesense, and changing the config/scout.php config key from typesensesearch to typesense
  • Instead of importing Devloops\LaravelTypesense\*, you should import Typesense\LaravelTypesense\*
  • Instead of models implementing Devloops\LaravelTypesense\Interfaces\TypesenseSearch, they should implement Typesense\LaravelTypesense\Interfaces\TypesenseDocument

Authors

This package was originally authored by Abdullah Al-Faqeir and his company DevLoops: https://github.com/devloopsnet/laravel-scout-typesense-engine. It has since been adopted into the Typesense Github org.

Other key contributors include:

License

The MIT License (MIT). Please see the License File for more information.

More Repositories

1

typesense

Open Source alternative to Algolia and an Easier-to-Use alternative to ElasticSearch ⚑ πŸ” ✨ Fast, typo tolerant, in-memory fuzzy Search Engine for building delightful search experiences
C++
12,770
star
2

showcase-recipe-search

Instantly search 2M cooking recipes using Typesense Search (an open source alternative to Algolia / ElasticSearch) ⚑ πŸ₯˜ πŸ”
JavaScript
437
star
3

typesense-js

JavaScript / TypeScript client for Typesense
JavaScript
266
star
4

typesense-instantsearch-adapter

A JS adapter library to build rich search interfaces with Typesense and InstantSearch.js
JavaScript
262
star
5

typesense-php

PHP client for Typesense: https://github.com/typesense/typesense
PHP
181
star
6

showcase-songs-search

A site to instantly search 32M songs from the MusicBrainz songs database, using Typesense Search (an open source alternative to Algolia / ElasticSearch) ⚑ 🎡 πŸ”
JavaScript
135
star
7

showcase-books-search

A site to instantly search 28M books from OpenLibrary using Typesense Search (an open source alternative to Algolia / ElasticSearch) ⚑ πŸ“š πŸ”
JavaScript
130
star
8

typesense-go

Go client for Typesense: https://github.com/typesense/typesense
Go
124
star
9

firestore-typesense-search

Firebase Extension to automatically push Firestore documents to Typesense for full-text search with typo tolerance, faceting, and more
JavaScript
122
star
10

typesense-python

Python client for Typesense: https://github.com/typesense/typesense
Python
104
star
11

typesense-docsearch-scraper

A fork of Algolia's awesome DocSearch Scraper, customized to index data in Typesense (an open source alternative to Algolia)
Python
70
star
12

typesense-dart

Dart client for Typesense
Dart
65
star
13

docusaurus-theme-search-typesense

A fork of the awesome @docusaurus/theme-search-algolia library customized to work with Typesense
TypeScript
48
star
14

typesense-ruby

Ruby client for Typesense: https://github.com/typesense/typesense
Ruby
43
star
15

typesense-instantsearch-demo

A demo app that shows how to use the Typesense InstantSearch adapter, to build rich search interfaces.
JavaScript
41
star
16

typesense-swift

Swift Client for Typesense βš‘οΈπŸ”Ž
Swift
40
star
17

typesense-website

Typesense website and documentation | An open source search engine alternative to Algolia, Elasticsearch and Pinecone
Vue
38
star
18

showcase-nextjs-typesense-ecommerce-store

An app showing how you can use Typesense & Next.js / React to build a full-fledged ecommerce browsing and searching experience
JavaScript
36
star
19

typesense-java

Java client for Typesense
Java
31
star
20

showcase-ecommerce-store

An app showing how you can use Typesense to build a full-fledged ecommerce browsing and searching experience
JavaScript
31
star
21

gatsby-plugin-typesense

A Gatsby plugin to automatically index content to Typesense post-build
JavaScript
30
star
22

showcase-linux-commits-search

Instantly search 1M Linux Kernel Commit Messages using Typesense Search (an open source alternative to Algolia / ElasticSearch) ⚑ πŸ’» πŸ”
JavaScript
29
star
23

typesense-kubernetes

Typesense Kubernetes
24
star
24

postman

Postman collection for Typesense
21
star
25

typesense-rust

Rust client for Typesense | Work In Progress & Help Wanted
Rust
21
star
26

typesense-mongodb

A Node.js CLI to sync documents from a MongoDB collection to Typesense.
TypeScript
21
star
27

showcase-hn-comments-semantic-search

Semantic Search + Keyword Search + Hybrid Search + Filtering + Faceting on 300K HN Comments
JavaScript
20
star
28

typesense-docsearch.js

A fork of Algolia's awesome DocSearch.js, customized to use data from Typesense.
TypeScript
20
star
29

typesense-api-spec

Contains the API specs for the Typesense HTTP API
14
star
30

typesense-autocomplete-demo

A demo app that shows you how to use Algolia's autocomplete.js library with Typesense
HTML
13
star
31

typesense-instantsearch-semantic-search-demo

A demo that shows how to build a semantic search experience with Typesense's vector search feature and Instantsearch.js
JavaScript
13
star
32

showcase-xkcd-search

Search & Browse xkcd by topic & keywords | Using Typesense, an open source Algolia alternative and an easier-to-use alternative to Elasticsearch
JavaScript
12
star
33

typesense-rails

Rails Integration for Typesense | Work in Progress | Help Needed
Ruby
10
star
34

showcase-spellcheck

Use Typesense to build a type-ahead spellchecker
JavaScript
8
star
35

typesense-instantsearch-demo-no-npm-yarn

A demo that shows how to use typesense-instantsearch-adapter without NPM or YARN
HTML
8
star
36

showcase-airbnb-geosearch

Browse & GeoSearch 1 Million AirBnB listings with Typesense βš‘πŸ” ️🌎
JavaScript
8
star
37

typesense-wordpress-plugin

Deprecated in favor of https://wordpress.org/plugins/search-with-typesense/
JavaScript
7
star
38

typesense-vue-instantsearch-demo

A demo app that shows you how to use Vue & the Typesense InstantSearch adapter, to build rich search interfaces.
Vue
6
star
39

homebrew-tap

Homebrew Formulae for Typesense
Ruby
4
star
40

user-admin-search-laravel-demo

A demo Laravel app that integrates with Typesense
PHP
4
star
41

showcase-federated-search

An app that showcases federated search in Typesense (Open source alternative to Algolia)
JavaScript
3
star
42

typesense-lando-plugin

A Lando plugin for Typesense
JavaScript
2
star
43

typesense-flutter-demo

1
star
44

.github

Org-wide shared github configs
1
star
45

solr-xml-to-jsonl

A CLI utility to convert a solr data file to a simple JSONL file
JavaScript
1
star