PHP code example of lingxi / ali-opensearch-sdk

1. Go to this page and download the library: Download lingxi/ali-opensearch-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

lingxi / ali-opensearch-sdk example snippets




return [
    'driver' => 'opensearch',

    'prefix' => '', // 应用前缀

    'queue' => true, // 是否开启队列同步数据

    'opensearch' => [

        'access_key_id'     => env('OPENSEARCH_ACCESS_KEY'),

        'access_key_secret' => env('OPENSEARCH_ACCESS_SECRET'),
        
        'host'              => env('OPENSEARCH_HOST'),

        'debug'             => env('OPENSEARCH_DEBUG'),

    ],

    'count' => [

        'unsearchable' => 20, // 一次性删除文档的 Model 数量

        'searchable' => 20, // 一次性同步文档的 Model 数量

        'updateSearchable' => 20, // 一次性更新(先删除,再更新)文档的 Model 数量

    ],
]

Laravel\Scout\ScoutServiceProvider::class,
Lingxi\AliOpenSearch\OpenSearchServiceProvider::class,



namespace App\Models;

use Lingxi\AliOpenSearch\Searchable;

class User extends Model
{
    use Searchable;

    /**
     * Get the index name for the model.
     *
     * @return string
     */
    public function searchableAs()
    {
        return 'user';
    }

    public function toSearchableDocCallbacks($actions = ['update', 'delete'])
    {
        throw new Exception('这个应用不需要手动维护数据');
    }

    public function getSearchableFields()
    {
        return 'id';
    }
}



$result = User::search(['name' => 'lingxi'])
    ->select([
        'id',
        'name',
        'age',
    ])
    ->filter(['age', '<', '30'])
    ->filter(['age', '>', '18'])
    ->orderBy('id', 'desc')
    ->paginate(15);



use Lingxi\AliOpenSearch\Query\QueryStructureBuilder as Query;

$q = $_GET['query'];

$query = Query::make()
    ->where(function ($query) use ($q) {
            return $query->where('name', $q)
        ->when(strpos($q, "@") !== false && $q != "@", function ($query) use ($q) {
            return $query->orWhere('email', $q);
        })
        ->when(is_numeric($q), function ($query) use ($q) {
            return $query->orWhere('mobile', $q);
        });
    });

$users = User::search($query)
    ->filter('age', 18)
    ->take(5)
    ->get();